@falai/agent 0.9.0-alpha-2 → 0.9.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -34
- package/dist/cjs/src/core/Agent.d.ts +48 -44
- package/dist/cjs/src/core/Agent.d.ts.map +1 -1
- package/dist/cjs/src/core/Agent.js +151 -1110
- package/dist/cjs/src/core/Agent.js.map +1 -1
- package/dist/cjs/src/core/ResponseModal.d.ts +211 -0
- package/dist/cjs/src/core/ResponseModal.d.ts.map +1 -0
- package/dist/cjs/src/core/ResponseModal.js +1394 -0
- package/dist/cjs/src/core/ResponseModal.js.map +1 -0
- package/dist/cjs/src/core/ResponsePipeline.d.ts +8 -4
- package/dist/cjs/src/core/ResponsePipeline.d.ts.map +1 -1
- package/dist/cjs/src/core/ResponsePipeline.js +48 -20
- package/dist/cjs/src/core/ResponsePipeline.js.map +1 -1
- package/dist/cjs/src/core/Route.d.ts +12 -5
- package/dist/cjs/src/core/Route.d.ts.map +1 -1
- package/dist/cjs/src/core/Route.js +26 -5
- package/dist/cjs/src/core/Route.js.map +1 -1
- package/dist/cjs/src/core/RoutingEngine.d.ts +5 -0
- package/dist/cjs/src/core/RoutingEngine.d.ts.map +1 -1
- package/dist/cjs/src/core/RoutingEngine.js +37 -25
- package/dist/cjs/src/core/RoutingEngine.js.map +1 -1
- package/dist/cjs/src/core/SessionManager.d.ts +9 -1
- package/dist/cjs/src/core/SessionManager.d.ts.map +1 -1
- package/dist/cjs/src/core/SessionManager.js +27 -5
- package/dist/cjs/src/core/SessionManager.js.map +1 -1
- package/dist/cjs/src/core/Step.d.ts +60 -7
- package/dist/cjs/src/core/Step.d.ts.map +1 -1
- package/dist/cjs/src/core/Step.js +151 -4
- package/dist/cjs/src/core/Step.js.map +1 -1
- package/dist/cjs/src/core/ToolManager.d.ts +234 -0
- package/dist/cjs/src/core/ToolManager.d.ts.map +1 -0
- package/dist/cjs/src/core/ToolManager.js +1117 -0
- package/dist/cjs/src/core/ToolManager.js.map +1 -0
- package/dist/cjs/src/index.d.ts +5 -4
- package/dist/cjs/src/index.d.ts.map +1 -1
- package/dist/cjs/src/index.js +11 -3
- package/dist/cjs/src/index.js.map +1 -1
- package/dist/cjs/src/types/agent.d.ts +2 -1
- package/dist/cjs/src/types/agent.d.ts.map +1 -1
- package/dist/cjs/src/types/ai.d.ts +1 -1
- package/dist/cjs/src/types/ai.d.ts.map +1 -1
- package/dist/cjs/src/types/index.d.ts +3 -2
- package/dist/cjs/src/types/index.d.ts.map +1 -1
- package/dist/cjs/src/types/index.js +3 -1
- package/dist/cjs/src/types/index.js.map +1 -1
- package/dist/cjs/src/types/route.d.ts +6 -4
- package/dist/cjs/src/types/route.d.ts.map +1 -1
- package/dist/cjs/src/types/tool.d.ts +84 -14
- package/dist/cjs/src/types/tool.d.ts.map +1 -1
- package/dist/cjs/src/types/tool.js +13 -0
- package/dist/cjs/src/types/tool.js.map +1 -1
- package/dist/cjs/src/utils/clone.d.ts.map +1 -1
- package/dist/cjs/src/utils/clone.js +0 -4
- package/dist/cjs/src/utils/clone.js.map +1 -1
- package/dist/cjs/src/utils/history.d.ts +30 -1
- package/dist/cjs/src/utils/history.d.ts.map +1 -1
- package/dist/cjs/src/utils/history.js +169 -23
- package/dist/cjs/src/utils/history.js.map +1 -1
- package/dist/cjs/src/utils/index.d.ts +1 -1
- package/dist/cjs/src/utils/index.d.ts.map +1 -1
- package/dist/cjs/src/utils/index.js +5 -1
- package/dist/cjs/src/utils/index.js.map +1 -1
- package/dist/src/core/Agent.d.ts +48 -44
- package/dist/src/core/Agent.d.ts.map +1 -1
- package/dist/src/core/Agent.js +152 -1111
- package/dist/src/core/Agent.js.map +1 -1
- package/dist/src/core/ResponseModal.d.ts +211 -0
- package/dist/src/core/ResponseModal.d.ts.map +1 -0
- package/dist/src/core/ResponseModal.js +1389 -0
- package/dist/src/core/ResponseModal.js.map +1 -0
- package/dist/src/core/ResponsePipeline.d.ts +8 -4
- package/dist/src/core/ResponsePipeline.d.ts.map +1 -1
- package/dist/src/core/ResponsePipeline.js +48 -20
- package/dist/src/core/ResponsePipeline.js.map +1 -1
- package/dist/src/core/Route.d.ts +12 -5
- package/dist/src/core/Route.d.ts.map +1 -1
- package/dist/src/core/Route.js +26 -5
- package/dist/src/core/Route.js.map +1 -1
- package/dist/src/core/RoutingEngine.d.ts +5 -0
- package/dist/src/core/RoutingEngine.d.ts.map +1 -1
- package/dist/src/core/RoutingEngine.js +37 -25
- package/dist/src/core/RoutingEngine.js.map +1 -1
- package/dist/src/core/SessionManager.d.ts +9 -1
- package/dist/src/core/SessionManager.d.ts.map +1 -1
- package/dist/src/core/SessionManager.js +27 -5
- package/dist/src/core/SessionManager.js.map +1 -1
- package/dist/src/core/Step.d.ts +60 -7
- package/dist/src/core/Step.d.ts.map +1 -1
- package/dist/src/core/Step.js +151 -4
- package/dist/src/core/Step.js.map +1 -1
- package/dist/src/core/ToolManager.d.ts +234 -0
- package/dist/src/core/ToolManager.d.ts.map +1 -0
- package/dist/src/core/ToolManager.js +1111 -0
- package/dist/src/core/ToolManager.js.map +1 -0
- package/dist/src/index.d.ts +5 -4
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +3 -2
- package/dist/src/index.js.map +1 -1
- package/dist/src/types/agent.d.ts +2 -1
- package/dist/src/types/agent.d.ts.map +1 -1
- package/dist/src/types/ai.d.ts +1 -1
- package/dist/src/types/ai.d.ts.map +1 -1
- package/dist/src/types/index.d.ts +3 -2
- package/dist/src/types/index.d.ts.map +1 -1
- package/dist/src/types/index.js +1 -0
- package/dist/src/types/index.js.map +1 -1
- package/dist/src/types/route.d.ts +6 -4
- package/dist/src/types/route.d.ts.map +1 -1
- package/dist/src/types/tool.d.ts +84 -14
- package/dist/src/types/tool.d.ts.map +1 -1
- package/dist/src/types/tool.js +12 -1
- package/dist/src/types/tool.js.map +1 -1
- package/dist/src/utils/clone.d.ts.map +1 -1
- package/dist/src/utils/clone.js +0 -4
- package/dist/src/utils/clone.js.map +1 -1
- package/dist/src/utils/history.d.ts +30 -1
- package/dist/src/utils/history.d.ts.map +1 -1
- package/dist/src/utils/history.js +165 -23
- package/dist/src/utils/history.js.map +1 -1
- package/dist/src/utils/index.d.ts +1 -1
- package/dist/src/utils/index.d.ts.map +1 -1
- package/dist/src/utils/index.js +1 -1
- package/dist/src/utils/index.js.map +1 -1
- package/docs/CONTRIBUTING.md +40 -0
- package/docs/README.md +14 -6
- package/docs/api/README.md +235 -45
- package/docs/api/overview.md +140 -33
- package/docs/core/agent/session-management.md +152 -5
- package/docs/core/ai-integration/response-processing.md +115 -4
- package/docs/core/conversation-flows/routes.md +130 -0
- package/docs/core/error-handling.md +638 -0
- package/docs/core/tools/tool-definition.md +684 -60
- package/docs/core/tools/tool-scoping.md +244 -53
- package/docs/guides/error-handling-patterns.md +578 -0
- package/docs/guides/getting-started/README.md +139 -28
- package/docs/guides/migration/README.md +72 -0
- package/docs/guides/migration/response-modal-refactor.md +518 -0
- package/examples/advanced-patterns/knowledge-based-agent.ts +6 -6
- package/examples/advanced-patterns/persistent-onboarding.ts +30 -43
- package/examples/advanced-patterns/streaming-responses.ts +169 -96
- package/examples/ai-providers/anthropic-integration.ts +9 -5
- package/examples/ai-providers/openai-integration.ts +11 -7
- package/examples/core-concepts/basic-agent.ts +106 -67
- package/examples/core-concepts/modern-streaming-api.ts +309 -0
- package/examples/core-concepts/schema-driven-extraction.ts +10 -7
- package/examples/core-concepts/session-management.ts +71 -18
- package/examples/integrations/healthcare-integration.ts +15 -29
- package/examples/integrations/server-session-management.ts +3 -3
- package/examples/persistence/memory-sessions.ts +3 -3
- package/examples/tools/basic-tools.ts +293 -89
- package/examples/tools/data-enrichment-tools.ts +185 -75
- package/package.json +1 -1
- package/src/core/Agent.ts +190 -1529
- package/src/core/ResponseModal.ts +1798 -0
- package/src/core/ResponsePipeline.ts +83 -57
- package/src/core/Route.ts +39 -12
- package/src/core/RoutingEngine.ts +46 -42
- package/src/core/SessionManager.ts +39 -7
- package/src/core/Step.ts +198 -20
- package/src/core/ToolManager.ts +1394 -0
- package/src/index.ts +19 -3
- package/src/types/agent.ts +2 -1
- package/src/types/ai.ts +1 -1
- package/src/types/index.ts +13 -2
- package/src/types/route.ts +6 -4
- package/src/types/tool.ts +116 -25
- package/src/utils/clone.ts +6 -8
- package/src/utils/history.ts +190 -27
- package/src/utils/index.ts +4 -0
- package/dist/cjs/src/core/ToolExecutor.d.ts +0 -45
- package/dist/cjs/src/core/ToolExecutor.d.ts.map +0 -1
- package/dist/cjs/src/core/ToolExecutor.js +0 -84
- package/dist/cjs/src/core/ToolExecutor.js.map +0 -1
- package/dist/src/core/ToolExecutor.d.ts +0 -45
- package/dist/src/core/ToolExecutor.d.ts.map +0 -1
- package/dist/src/core/ToolExecutor.js +0 -80
- package/dist/src/core/ToolExecutor.js.map +0 -1
- package/docs/core/tools/tool-execution.md +0 -815
- package/src/core/ToolExecutor.ts +0 -126
|
@@ -0,0 +1,518 @@
|
|
|
1
|
+
# ResponseModal Refactor Migration Guide
|
|
2
|
+
|
|
3
|
+
This guide helps you migrate from the legacy response APIs to the new ResponseModal architecture introduced in the latest version. The refactor provides better architecture, modern streaming APIs, and improved maintainability while maintaining full backward compatibility.
|
|
4
|
+
|
|
5
|
+
## 📋 Table of Contents
|
|
6
|
+
|
|
7
|
+
- [Overview](#overview)
|
|
8
|
+
- [What Changed](#what-changed)
|
|
9
|
+
- [Backward Compatibility](#backward-compatibility)
|
|
10
|
+
- [New Modern APIs](#new-modern-apis)
|
|
11
|
+
- [Migration Strategies](#migration-strategies)
|
|
12
|
+
- [Side-by-Side Comparisons](#side-by-side-comparisons)
|
|
13
|
+
- [Benefits of Migration](#benefits-of-migration)
|
|
14
|
+
- [Troubleshooting](#troubleshooting)
|
|
15
|
+
|
|
16
|
+
## Overview
|
|
17
|
+
|
|
18
|
+
The ResponseModal refactor centralizes all response generation logic into a dedicated `ResponseModal` class, providing:
|
|
19
|
+
|
|
20
|
+
- **🏗️ Better Architecture**: Separation of concerns between Agent configuration and response generation
|
|
21
|
+
- **🚀 Modern APIs**: Simple `stream()` and `generate()` methods with automatic session management
|
|
22
|
+
- **🔄 Backward Compatibility**: All existing `respond()` and `respondStream()` methods work unchanged
|
|
23
|
+
- **⚡ Performance**: Unified response logic eliminates code duplication
|
|
24
|
+
- **🛠️ Maintainability**: Centralized response logic is easier to test and maintain
|
|
25
|
+
|
|
26
|
+
## What Changed
|
|
27
|
+
|
|
28
|
+
### Internal Architecture
|
|
29
|
+
|
|
30
|
+
```mermaid
|
|
31
|
+
graph TD
|
|
32
|
+
subgraph "Before: Monolithic Agent"
|
|
33
|
+
A1[Agent Class<br/>2000+ lines] --> RL[Response Logic]
|
|
34
|
+
A1 --> SM[Session Management]
|
|
35
|
+
A1 --> RE[Response Engine]
|
|
36
|
+
A1 --> RP[Response Pipeline]
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
subgraph "After: Separated Concerns"
|
|
40
|
+
A2[Agent Class<br/>Simplified] --> RM[ResponseModal]
|
|
41
|
+
A2 --> SM2[Session Management]
|
|
42
|
+
RM --> RE2[Response Engine]
|
|
43
|
+
RM --> RP2[Response Pipeline]
|
|
44
|
+
RM --> UL[Unified Logic]
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
style A1 fill:#ffcccc
|
|
48
|
+
style A2 fill:#ccffcc
|
|
49
|
+
style RM fill:#ccffcc
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
### New Classes
|
|
53
|
+
|
|
54
|
+
- **`ResponseModal<TContext, TData>`**: Handles all response generation logic
|
|
55
|
+
- **`ResponseGenerationError`**: Specialized error handling for response failures
|
|
56
|
+
- **New interfaces**: `StreamOptions`, `GenerateOptions`, `ResponseModalOptions`
|
|
57
|
+
|
|
58
|
+
### New Methods
|
|
59
|
+
|
|
60
|
+
- **`agent.stream(message, options?)`**: Modern streaming API with automatic session management
|
|
61
|
+
- **`responseModal.generate(message, options?)`**: Modern non-streaming API (internal)
|
|
62
|
+
|
|
63
|
+
## Backward Compatibility
|
|
64
|
+
|
|
65
|
+
**✅ All existing code continues to work without changes.**
|
|
66
|
+
|
|
67
|
+
```typescript
|
|
68
|
+
// These methods work exactly the same as before
|
|
69
|
+
const response = await agent.respond({ history, session });
|
|
70
|
+
const stream = agent.respondStream({ history, session });
|
|
71
|
+
const chatResponse = await agent.chat("Hello");
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
The only difference is that these methods now delegate to the internal `ResponseModal` class for better architecture.
|
|
75
|
+
|
|
76
|
+
## New Modern APIs
|
|
77
|
+
|
|
78
|
+
### Modern Streaming: `agent.stream()`
|
|
79
|
+
|
|
80
|
+
The new `stream()` method provides a much simpler interface for streaming responses:
|
|
81
|
+
|
|
82
|
+
```typescript
|
|
83
|
+
// NEW: Modern streaming API
|
|
84
|
+
for await (const chunk of agent.stream("Hello, how are you?")) {
|
|
85
|
+
if (chunk.delta) {
|
|
86
|
+
process.stdout.write(chunk.delta);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
if (chunk.done) {
|
|
90
|
+
console.log("Stream complete!");
|
|
91
|
+
// Session history is automatically updated
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
**Key Features:**
|
|
97
|
+
- 🎯 Simple interface: just pass the message
|
|
98
|
+
- 🔄 Automatic session management
|
|
99
|
+
- 🌊 Same streaming performance as `respondStream()`
|
|
100
|
+
- 🛑 Supports AbortSignal for cancellation
|
|
101
|
+
- ⚙️ Optional context override
|
|
102
|
+
|
|
103
|
+
### Options Support
|
|
104
|
+
|
|
105
|
+
```typescript
|
|
106
|
+
// With options
|
|
107
|
+
for await (const chunk of agent.stream("Explain quantum computing", {
|
|
108
|
+
contextOverride: { userId: "123" },
|
|
109
|
+
signal: abortController.signal
|
|
110
|
+
})) {
|
|
111
|
+
// Handle chunk
|
|
112
|
+
}
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
## Migration Strategies
|
|
116
|
+
|
|
117
|
+
### Strategy 1: Gradual Migration (Recommended)
|
|
118
|
+
|
|
119
|
+
Migrate to modern APIs gradually while keeping existing code working:
|
|
120
|
+
|
|
121
|
+
```typescript
|
|
122
|
+
// Phase 1: Keep existing code working
|
|
123
|
+
const response = await agent.respond({ history, session }); // ✅ Still works
|
|
124
|
+
|
|
125
|
+
// Phase 2: Start using modern APIs for new features
|
|
126
|
+
for await (const chunk of agent.stream("New feature message")) {
|
|
127
|
+
// Handle streaming
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// Phase 3: Gradually replace old APIs when convenient
|
|
131
|
+
// Old: agent.respondStream({ history: agent.session.getHistory() })
|
|
132
|
+
// New: agent.stream("message")
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
### Strategy 2: Full Migration
|
|
136
|
+
|
|
137
|
+
Replace all streaming calls with the modern API:
|
|
138
|
+
|
|
139
|
+
```typescript
|
|
140
|
+
// Before: Manual session management
|
|
141
|
+
await agent.session.addMessage("user", userMessage);
|
|
142
|
+
for await (const chunk of agent.respondStream({
|
|
143
|
+
history: agent.session.getHistory()
|
|
144
|
+
})) {
|
|
145
|
+
// Handle chunk
|
|
146
|
+
if (chunk.done) {
|
|
147
|
+
await agent.session.addMessage("assistant", chunk.accumulated);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// After: Automatic session management
|
|
152
|
+
for await (const chunk of agent.stream(userMessage)) {
|
|
153
|
+
// Handle chunk - session is automatically managed
|
|
154
|
+
}
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
### Strategy 3: Hybrid Approach
|
|
158
|
+
|
|
159
|
+
Use modern APIs for new code, keep legacy APIs for complex existing implementations:
|
|
160
|
+
|
|
161
|
+
```typescript
|
|
162
|
+
// Complex existing code - keep using respondStream()
|
|
163
|
+
const complexResponse = await agent.respondStream({
|
|
164
|
+
history: customHistory,
|
|
165
|
+
session: customSession,
|
|
166
|
+
contextOverride: complexContext,
|
|
167
|
+
signal: customSignal
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
// Simple new code - use modern stream()
|
|
171
|
+
for await (const chunk of agent.stream("Simple question")) {
|
|
172
|
+
// Handle chunk
|
|
173
|
+
}
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
## Side-by-Side Comparisons
|
|
177
|
+
|
|
178
|
+
### Basic Streaming
|
|
179
|
+
|
|
180
|
+
```typescript
|
|
181
|
+
// ❌ OLD WAY: respondStream() - Manual session management
|
|
182
|
+
await agent.session.addMessage("user", "What is TypeScript?");
|
|
183
|
+
let fullMessage = "";
|
|
184
|
+
|
|
185
|
+
for await (const chunk of agent.respondStream({
|
|
186
|
+
history: agent.session.getHistory()
|
|
187
|
+
})) {
|
|
188
|
+
if (chunk.delta) {
|
|
189
|
+
process.stdout.write(chunk.delta);
|
|
190
|
+
fullMessage += chunk.delta;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
if (chunk.done) {
|
|
194
|
+
await agent.session.addMessage("assistant", fullMessage);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// ✅ NEW WAY: stream() - Automatic session management
|
|
199
|
+
for await (const chunk of agent.stream("What is TypeScript?")) {
|
|
200
|
+
if (chunk.delta) {
|
|
201
|
+
process.stdout.write(chunk.delta);
|
|
202
|
+
}
|
|
203
|
+
// Session is automatically updated when done
|
|
204
|
+
}
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
### Multi-turn Conversations
|
|
208
|
+
|
|
209
|
+
```typescript
|
|
210
|
+
// ❌ OLD WAY: Manual history management
|
|
211
|
+
const messages = ["Hello", "How are you?", "Tell me about AI"];
|
|
212
|
+
|
|
213
|
+
for (const message of messages) {
|
|
214
|
+
await agent.session.addMessage("user", message);
|
|
215
|
+
|
|
216
|
+
let response = "";
|
|
217
|
+
for await (const chunk of agent.respondStream({
|
|
218
|
+
history: agent.session.getHistory()
|
|
219
|
+
})) {
|
|
220
|
+
if (chunk.delta) response += chunk.delta;
|
|
221
|
+
if (chunk.done) {
|
|
222
|
+
await agent.session.addMessage("assistant", response);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// ✅ NEW WAY: Automatic session management
|
|
228
|
+
const messages = ["Hello", "How are you?", "Tell me about AI"];
|
|
229
|
+
|
|
230
|
+
for (const message of messages) {
|
|
231
|
+
for await (const chunk of agent.stream(message)) {
|
|
232
|
+
if (chunk.delta) process.stdout.write(chunk.delta);
|
|
233
|
+
// Session automatically updated
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
### With Abort Signals
|
|
239
|
+
|
|
240
|
+
```typescript
|
|
241
|
+
// ❌ OLD WAY: Complex parameter structure
|
|
242
|
+
const abortController = new AbortController();
|
|
243
|
+
await agent.session.addMessage("user", "Long story please");
|
|
244
|
+
|
|
245
|
+
for await (const chunk of agent.respondStream({
|
|
246
|
+
history: agent.session.getHistory(),
|
|
247
|
+
signal: abortController.signal
|
|
248
|
+
})) {
|
|
249
|
+
// Handle chunk
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// ✅ NEW WAY: Simple options structure
|
|
253
|
+
const abortController = new AbortController();
|
|
254
|
+
|
|
255
|
+
for await (const chunk of agent.stream("Long story please", {
|
|
256
|
+
signal: abortController.signal
|
|
257
|
+
})) {
|
|
258
|
+
// Handle chunk
|
|
259
|
+
}
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
### Context Override
|
|
263
|
+
|
|
264
|
+
```typescript
|
|
265
|
+
// ❌ OLD WAY: Complex parameter passing
|
|
266
|
+
for await (const chunk of agent.respondStream({
|
|
267
|
+
history: agent.session.getHistory(),
|
|
268
|
+
contextOverride: { userId: "123" }
|
|
269
|
+
})) {
|
|
270
|
+
// Handle chunk
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// ✅ NEW WAY: Clean options structure
|
|
274
|
+
for await (const chunk of agent.stream("Hello", {
|
|
275
|
+
contextOverride: { userId: "123" }
|
|
276
|
+
})) {
|
|
277
|
+
// Handle chunk
|
|
278
|
+
}
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
## Benefits of Migration
|
|
282
|
+
|
|
283
|
+
### 1. Simplified Code
|
|
284
|
+
|
|
285
|
+
**Before:**
|
|
286
|
+
```typescript
|
|
287
|
+
// 6 lines of manual session management
|
|
288
|
+
await agent.session.addMessage("user", userMessage);
|
|
289
|
+
let fullResponse = "";
|
|
290
|
+
for await (const chunk of agent.respondStream({ history: agent.session.getHistory() })) {
|
|
291
|
+
if (chunk.delta) fullResponse += chunk.delta;
|
|
292
|
+
if (chunk.done) await agent.session.addMessage("assistant", fullResponse);
|
|
293
|
+
}
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
**After:**
|
|
297
|
+
```typescript
|
|
298
|
+
// 3 lines with automatic session management
|
|
299
|
+
for await (const chunk of agent.stream(userMessage)) {
|
|
300
|
+
if (chunk.delta) process.stdout.write(chunk.delta);
|
|
301
|
+
}
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
### 2. Reduced Errors
|
|
305
|
+
|
|
306
|
+
Common mistakes eliminated:
|
|
307
|
+
- ❌ Forgetting to add user message to session
|
|
308
|
+
- ❌ Forgetting to add assistant response to session
|
|
309
|
+
- ❌ Incorrect history management
|
|
310
|
+
- ❌ Session state inconsistencies
|
|
311
|
+
|
|
312
|
+
### 3. Better Performance
|
|
313
|
+
|
|
314
|
+
- Unified response logic eliminates code duplication
|
|
315
|
+
- Optimized session management
|
|
316
|
+
- Reduced memory allocations
|
|
317
|
+
|
|
318
|
+
### 4. Improved Maintainability
|
|
319
|
+
|
|
320
|
+
- Centralized response logic in `ResponseModal`
|
|
321
|
+
- Better error handling with `ResponseGenerationError`
|
|
322
|
+
- Cleaner separation of concerns
|
|
323
|
+
|
|
324
|
+
## Troubleshooting
|
|
325
|
+
|
|
326
|
+
### Common Migration Issues
|
|
327
|
+
|
|
328
|
+
#### Issue: "My existing code stopped working"
|
|
329
|
+
|
|
330
|
+
**Solution:** This shouldn't happen! All existing APIs are fully backward compatible. If you're experiencing issues:
|
|
331
|
+
|
|
332
|
+
```typescript
|
|
333
|
+
// These should all still work exactly as before
|
|
334
|
+
const response = await agent.respond({ history, session });
|
|
335
|
+
const stream = agent.respondStream({ history, session });
|
|
336
|
+
const chat = await agent.chat("Hello");
|
|
337
|
+
```
|
|
338
|
+
|
|
339
|
+
#### Issue: "Session history is not being updated with stream()"
|
|
340
|
+
|
|
341
|
+
**Solution:** The modern `stream()` API automatically manages session history. You don't need to manually call `addMessage()`:
|
|
342
|
+
|
|
343
|
+
```typescript
|
|
344
|
+
// ❌ Don't do this with stream()
|
|
345
|
+
await agent.session.addMessage("user", "Hello");
|
|
346
|
+
for await (const chunk of agent.stream("Hello")) {
|
|
347
|
+
// This will duplicate the message!
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// ✅ Do this instead
|
|
351
|
+
for await (const chunk of agent.stream("Hello")) {
|
|
352
|
+
// Session is automatically managed
|
|
353
|
+
}
|
|
354
|
+
```
|
|
355
|
+
|
|
356
|
+
#### Issue: "I need custom history with stream()"
|
|
357
|
+
|
|
358
|
+
**Solution:** Use the `history` option to override session history:
|
|
359
|
+
|
|
360
|
+
```typescript
|
|
361
|
+
// Use custom history without affecting session
|
|
362
|
+
for await (const chunk of agent.stream("Hello", {
|
|
363
|
+
history: customHistory
|
|
364
|
+
})) {
|
|
365
|
+
// Uses custom history, doesn't update session
|
|
366
|
+
}
|
|
367
|
+
```
|
|
368
|
+
|
|
369
|
+
#### Issue: "ResponseGenerationError in my error handling"
|
|
370
|
+
|
|
371
|
+
**Solution:** Update error handling to check for the new error type:
|
|
372
|
+
|
|
373
|
+
```typescript
|
|
374
|
+
try {
|
|
375
|
+
const response = await agent.respond(params);
|
|
376
|
+
} catch (error) {
|
|
377
|
+
if (error instanceof ResponseGenerationError) {
|
|
378
|
+
console.log("Response generation failed:", error.message);
|
|
379
|
+
console.log("Phase:", error.details?.phase);
|
|
380
|
+
console.log("Original error:", error.details?.originalError);
|
|
381
|
+
} else {
|
|
382
|
+
// Handle other errors
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
```
|
|
386
|
+
|
|
387
|
+
### Performance Considerations
|
|
388
|
+
|
|
389
|
+
#### Memory Usage
|
|
390
|
+
|
|
391
|
+
The new architecture is more memory-efficient:
|
|
392
|
+
- Unified response logic reduces code duplication
|
|
393
|
+
- Better session state management
|
|
394
|
+
- Optimized streaming pipeline
|
|
395
|
+
|
|
396
|
+
#### Streaming Performance
|
|
397
|
+
|
|
398
|
+
Both APIs have identical streaming performance:
|
|
399
|
+
- `respondStream()` and `stream()` use the same underlying logic
|
|
400
|
+
- No performance penalty for using modern APIs
|
|
401
|
+
- Same chunk delivery timing and throughput
|
|
402
|
+
|
|
403
|
+
### Debugging Tips
|
|
404
|
+
|
|
405
|
+
#### Enable Debug Mode
|
|
406
|
+
|
|
407
|
+
```typescript
|
|
408
|
+
const agent = new Agent({
|
|
409
|
+
// ... other options
|
|
410
|
+
debug: true // Enable detailed logging
|
|
411
|
+
});
|
|
412
|
+
```
|
|
413
|
+
|
|
414
|
+
#### Access ResponseModal Directly (Advanced)
|
|
415
|
+
|
|
416
|
+
```typescript
|
|
417
|
+
// For advanced debugging only
|
|
418
|
+
const responseModal = (agent as any).responseModal;
|
|
419
|
+
console.log("ResponseModal instance:", responseModal);
|
|
420
|
+
```
|
|
421
|
+
|
|
422
|
+
#### Check Session State
|
|
423
|
+
|
|
424
|
+
```typescript
|
|
425
|
+
// Monitor session state during streaming
|
|
426
|
+
for await (const chunk of agent.stream("Hello")) {
|
|
427
|
+
if (chunk.done) {
|
|
428
|
+
console.log("Session messages:", agent.session.getHistory().length);
|
|
429
|
+
console.log("Session data:", agent.session.getData());
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
```
|
|
433
|
+
|
|
434
|
+
## Best Practices
|
|
435
|
+
|
|
436
|
+
### 1. Use Modern APIs for New Code
|
|
437
|
+
|
|
438
|
+
```typescript
|
|
439
|
+
// ✅ Recommended for new implementations
|
|
440
|
+
for await (const chunk of agent.stream("Hello")) {
|
|
441
|
+
// Handle chunk
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// ❌ Avoid for new code (but still supported)
|
|
445
|
+
for await (const chunk of agent.respondStream({ history })) {
|
|
446
|
+
// More complex
|
|
447
|
+
}
|
|
448
|
+
```
|
|
449
|
+
|
|
450
|
+
### 2. Migrate Gradually
|
|
451
|
+
|
|
452
|
+
```typescript
|
|
453
|
+
// Phase 1: Keep existing complex code
|
|
454
|
+
const complexResponse = await agent.respondStream({
|
|
455
|
+
history: customHistory,
|
|
456
|
+
session: customSession,
|
|
457
|
+
contextOverride: complexContext
|
|
458
|
+
});
|
|
459
|
+
|
|
460
|
+
// Phase 2: Use modern APIs for simple cases
|
|
461
|
+
for await (const chunk of agent.stream("Simple question")) {
|
|
462
|
+
// Handle chunk
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
// Phase 3: Migrate complex code when convenient
|
|
466
|
+
```
|
|
467
|
+
|
|
468
|
+
### 3. Handle Errors Appropriately
|
|
469
|
+
|
|
470
|
+
```typescript
|
|
471
|
+
try {
|
|
472
|
+
for await (const chunk of agent.stream("Hello")) {
|
|
473
|
+
// Handle chunk
|
|
474
|
+
}
|
|
475
|
+
} catch (error) {
|
|
476
|
+
if (error instanceof ResponseGenerationError) {
|
|
477
|
+
// Handle response-specific errors
|
|
478
|
+
console.log("Response failed:", error.details?.phase);
|
|
479
|
+
} else if (error.name === "AbortError") {
|
|
480
|
+
// Handle cancellation
|
|
481
|
+
console.log("Stream was cancelled");
|
|
482
|
+
} else {
|
|
483
|
+
// Handle other errors
|
|
484
|
+
console.error("Unexpected error:", error);
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
```
|
|
488
|
+
|
|
489
|
+
### 4. Use AbortSignal for Long Operations
|
|
490
|
+
|
|
491
|
+
```typescript
|
|
492
|
+
const controller = new AbortController();
|
|
493
|
+
setTimeout(() => controller.abort(), 30000); // 30s timeout
|
|
494
|
+
|
|
495
|
+
for await (const chunk of agent.stream("Complex question", {
|
|
496
|
+
signal: controller.signal
|
|
497
|
+
})) {
|
|
498
|
+
// Handle chunk
|
|
499
|
+
}
|
|
500
|
+
```
|
|
501
|
+
|
|
502
|
+
## Conclusion
|
|
503
|
+
|
|
504
|
+
The ResponseModal refactor provides significant improvements in architecture, usability, and maintainability while maintaining full backward compatibility. You can:
|
|
505
|
+
|
|
506
|
+
1. **Keep existing code working** - No immediate changes required
|
|
507
|
+
2. **Adopt modern APIs gradually** - Migrate at your own pace
|
|
508
|
+
3. **Benefit from improved architecture** - Better performance and maintainability
|
|
509
|
+
4. **Use simpler APIs for new features** - `stream()` is much easier than `respondStream()`
|
|
510
|
+
|
|
511
|
+
The modern `stream()` API is the recommended approach for new streaming implementations, but your existing `respondStream()` code will continue to work exactly as before.
|
|
512
|
+
|
|
513
|
+
---
|
|
514
|
+
|
|
515
|
+
**Need Help?**
|
|
516
|
+
- Check the [examples](../../examples/) directory for complete working examples
|
|
517
|
+
- Review the [API documentation](../../api/) for detailed method signatures
|
|
518
|
+
- Look at the [streaming examples](../../examples/advanced-patterns/streaming-responses.ts) for side-by-side comparisons
|
|
@@ -65,11 +65,11 @@ interface FeedbackData {
|
|
|
65
65
|
// ==============================================================================
|
|
66
66
|
|
|
67
67
|
// Tool: Fetch latest company news (context enrichment)
|
|
68
|
-
const fetchNewsTool: Tool<CompanyContext, UnifiedData
|
|
68
|
+
const fetchNewsTool: Tool<CompanyContext, UnifiedData> = {
|
|
69
69
|
id: "fetch_news",
|
|
70
70
|
name: "Company News Fetcher",
|
|
71
71
|
description: "Retrieve latest company news and updates",
|
|
72
|
-
handler: () => {
|
|
72
|
+
handler: (context, args) => {
|
|
73
73
|
// Simulate API call to news service
|
|
74
74
|
const news = [
|
|
75
75
|
{
|
|
@@ -87,7 +87,7 @@ const fetchNewsTool: Tool<CompanyContext, UnifiedData, [], void> = {
|
|
|
87
87
|
console.log(`[Tool] Fetched ${news.length} news articles`);
|
|
88
88
|
|
|
89
89
|
return {
|
|
90
|
-
data:
|
|
90
|
+
data: `Fetched ${news.length} latest news articles`,
|
|
91
91
|
contextUpdate: {
|
|
92
92
|
recentNews: news,
|
|
93
93
|
},
|
|
@@ -96,12 +96,12 @@ const fetchNewsTool: Tool<CompanyContext, UnifiedData, [], void> = {
|
|
|
96
96
|
};
|
|
97
97
|
|
|
98
98
|
// Tool: Search knowledge base (context enrichment)
|
|
99
|
-
const searchKnowledgeTool: Tool<CompanyContext,UnifiedData
|
|
99
|
+
const searchKnowledgeTool: Tool<CompanyContext, UnifiedData> = {
|
|
100
100
|
id: "search_knowledge",
|
|
101
101
|
name: "Knowledge Base Search",
|
|
102
102
|
description: "Search FAQs and documentation",
|
|
103
|
-
handler: (
|
|
104
|
-
const { history } =
|
|
103
|
+
handler: (toolContext, args) => {
|
|
104
|
+
const { history } = toolContext;
|
|
105
105
|
|
|
106
106
|
// Get last user message
|
|
107
107
|
const lastMessage = history
|
|
@@ -228,12 +228,7 @@ function createPersistentOnboardingAgent(sessionId: string) {
|
|
|
228
228
|
// ============================================================================
|
|
229
229
|
|
|
230
230
|
// OPTION 1: Using contextUpdate in return value
|
|
231
|
-
const saveBusinessInfo: Tool<
|
|
232
|
-
OnboardingContext,
|
|
233
|
-
OnboardingData,
|
|
234
|
-
unknown[],
|
|
235
|
-
unknown
|
|
236
|
-
> = {
|
|
231
|
+
const saveBusinessInfo: Tool<OnboardingContext, OnboardingData> = {
|
|
237
232
|
id: "save_business_info",
|
|
238
233
|
name: "Business Info Saver",
|
|
239
234
|
description: "Save business name and description",
|
|
@@ -245,12 +240,13 @@ function createPersistentOnboardingAgent(sessionId: string) {
|
|
|
245
240
|
},
|
|
246
241
|
required: ["name", "description"],
|
|
247
242
|
},
|
|
248
|
-
handler: (toolContext,
|
|
249
|
-
const
|
|
243
|
+
handler: (toolContext, args) => {
|
|
244
|
+
const name = args?.name as string;
|
|
245
|
+
const description = args?.description as string;
|
|
250
246
|
console.log(`📝 Saving business info: ${name}`);
|
|
251
247
|
|
|
252
248
|
return {
|
|
253
|
-
data:
|
|
249
|
+
data: "Business information saved successfully",
|
|
254
250
|
// Context update is automatically persisted via onContextUpdate hook
|
|
255
251
|
contextUpdate: {
|
|
256
252
|
collectedData: {
|
|
@@ -267,13 +263,8 @@ function createPersistentOnboardingAgent(sessionId: string) {
|
|
|
267
263
|
},
|
|
268
264
|
};
|
|
269
265
|
|
|
270
|
-
// OPTION 2: Using
|
|
271
|
-
const saveIndustry: Tool<
|
|
272
|
-
OnboardingContext,
|
|
273
|
-
OnboardingData,
|
|
274
|
-
unknown[],
|
|
275
|
-
unknown
|
|
276
|
-
> = {
|
|
266
|
+
// OPTION 2: Using contextUpdate in return value
|
|
267
|
+
const saveIndustry: Tool<OnboardingContext, OnboardingData> = {
|
|
277
268
|
id: "save_industry",
|
|
278
269
|
name: "Industry Classifier",
|
|
279
270
|
description: "Save business industry",
|
|
@@ -284,29 +275,24 @@ function createPersistentOnboardingAgent(sessionId: string) {
|
|
|
284
275
|
},
|
|
285
276
|
required: ["industry"],
|
|
286
277
|
},
|
|
287
|
-
handler: async (toolContext,
|
|
288
|
-
const
|
|
278
|
+
handler: async (toolContext, args) => {
|
|
279
|
+
const industry = args?.industry as string;
|
|
289
280
|
console.log(`🏭 Saving industry: ${industry}`);
|
|
290
281
|
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
282
|
+
return {
|
|
283
|
+
data: "Industry information saved successfully",
|
|
284
|
+
contextUpdate: {
|
|
285
|
+
collectedData: {
|
|
286
|
+
...toolContext.context.collectedData,
|
|
287
|
+
industry,
|
|
288
|
+
},
|
|
289
|
+
completedSteps: [...toolContext.context.completedSteps, "industry"],
|
|
296
290
|
},
|
|
297
|
-
|
|
298
|
-
});
|
|
299
|
-
|
|
300
|
-
return { data: true };
|
|
291
|
+
};
|
|
301
292
|
},
|
|
302
293
|
};
|
|
303
294
|
|
|
304
|
-
const saveContactEmail: Tool<
|
|
305
|
-
OnboardingContext,
|
|
306
|
-
OnboardingData,
|
|
307
|
-
unknown[],
|
|
308
|
-
unknown
|
|
309
|
-
> = {
|
|
295
|
+
const saveContactEmail: Tool<OnboardingContext, OnboardingData> = {
|
|
310
296
|
id: "save_contact_email",
|
|
311
297
|
name: "Contact Email Saver",
|
|
312
298
|
description: "Save contact email",
|
|
@@ -317,19 +303,20 @@ function createPersistentOnboardingAgent(sessionId: string) {
|
|
|
317
303
|
},
|
|
318
304
|
required: ["email"],
|
|
319
305
|
},
|
|
320
|
-
handler: async (toolContext,
|
|
321
|
-
const
|
|
306
|
+
handler: async (toolContext, args) => {
|
|
307
|
+
const email = args?.email as string;
|
|
322
308
|
console.log(`📧 Saving contact email: ${email}`);
|
|
323
309
|
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
310
|
+
return {
|
|
311
|
+
data: "Contact email saved successfully",
|
|
312
|
+
contextUpdate: {
|
|
313
|
+
collectedData: {
|
|
314
|
+
...toolContext.context.collectedData,
|
|
315
|
+
contactEmail: email,
|
|
316
|
+
},
|
|
317
|
+
completedSteps: [...toolContext.context.completedSteps, "contact"],
|
|
328
318
|
},
|
|
329
|
-
|
|
330
|
-
});
|
|
331
|
-
|
|
332
|
-
return { data: true };
|
|
319
|
+
};
|
|
333
320
|
},
|
|
334
321
|
};
|
|
335
322
|
|