-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSessionState.java
More file actions
76 lines (65 loc) · 3.04 KB
/
SessionState.java
File metadata and controls
76 lines (65 loc) · 3.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/**
* Stateful agent using global data for session tracking.
*
* Demonstrates how to use global data to maintain state across tool calls
* within a single conversation.
*/
import com.signalwire.sdk.agent.AgentBase;
import com.signalwire.sdk.swaig.FunctionResult;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class SessionState {
public static void main(String[] args) throws Exception {
var agent = AgentBase.builder()
.name("stateful-agent")
.route("/")
.port(3000)
.build();
agent.promptAddSection("Role",
"You are a shopping assistant. Help users add items to their cart.");
agent.promptAddSection("Instructions", "", List.of(
"Use add_to_cart to add items",
"Use view_cart to show current cart contents",
"Use checkout to complete the order"
));
// Initialize global data with empty cart
agent.updateGlobalData(Map.of(
"cart", Map.of("items", List.of(), "total", 0)
));
// Add to cart tool
agent.defineTool("add_to_cart", "Add an item to the shopping cart",
Map.of("type", "object", "properties", Map.of(
"item", Map.of("type", "string", "description", "Item name"),
"price", Map.of("type", "number", "description", "Item price")
), "required", List.of("item", "price")),
(toolArgs, raw) -> {
String item = (String) toolArgs.get("item");
double price = ((Number) toolArgs.get("price")).doubleValue();
return new FunctionResult(
"Added " + item + " ($" + String.format("%.2f", price) + ") to cart.")
.updateGlobalData(Map.of(
"last_item", item,
"last_price", price
));
});
// View cart tool
agent.defineTool("view_cart", "View the current shopping cart",
Map.of("type", "object", "properties", Map.of()),
(toolArgs, raw) -> {
@SuppressWarnings("unchecked")
Map<String, Object> globalData = (Map<String, Object>) raw.get("global_data");
String lastItem = globalData != null ?
(String) globalData.getOrDefault("last_item", "none") : "none";
return new FunctionResult("Last item added: " + lastItem);
});
// Checkout tool
agent.defineTool("checkout", "Complete the order",
Map.of("type", "object", "properties", Map.of()),
(toolArgs, raw) -> new FunctionResult(
"Order placed successfully! Thank you for shopping with us.")
.hangup());
System.out.println("Starting stateful shopping agent on port 3000...");
agent.run();
}
}