@falai/agent 0.9.0-alpha-1 → 0.9.0
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 +34 -22
- package/dist/cjs/src/core/Agent.d.ts +77 -59
- package/dist/cjs/src/core/Agent.d.ts.map +1 -1
- package/dist/cjs/src/core/Agent.js +284 -1060
- package/dist/cjs/src/core/Agent.js.map +1 -1
- package/dist/cjs/src/core/PersistenceManager.d.ts.map +1 -1
- package/dist/cjs/src/core/PersistenceManager.js +48 -25
- package/dist/cjs/src/core/PersistenceManager.js.map +1 -1
- package/dist/cjs/src/core/PromptComposer.d.ts +1 -1
- package/dist/cjs/src/core/PromptComposer.d.ts.map +1 -1
- package/dist/cjs/src/core/PromptComposer.js.map +1 -1
- package/dist/cjs/src/core/ResponseEngine.d.ts +13 -12
- package/dist/cjs/src/core/ResponseEngine.d.ts.map +1 -1
- package/dist/cjs/src/core/ResponseEngine.js +4 -4
- package/dist/cjs/src/core/ResponseEngine.js.map +1 -1
- package/dist/cjs/src/core/ResponseModal.d.ts +205 -0
- package/dist/cjs/src/core/ResponseModal.d.ts.map +1 -0
- package/dist/cjs/src/core/ResponseModal.js +1328 -0
- package/dist/cjs/src/core/ResponseModal.js.map +1 -0
- package/dist/cjs/src/core/ResponsePipeline.d.ts +66 -38
- package/dist/cjs/src/core/ResponsePipeline.d.ts.map +1 -1
- package/dist/cjs/src/core/ResponsePipeline.js +72 -4
- package/dist/cjs/src/core/ResponsePipeline.js.map +1 -1
- package/dist/cjs/src/core/Route.d.ts +24 -5
- package/dist/cjs/src/core/Route.d.ts.map +1 -1
- package/dist/cjs/src/core/Route.js +45 -1
- package/dist/cjs/src/core/Route.js.map +1 -1
- package/dist/cjs/src/core/RoutingEngine.d.ts +31 -6
- package/dist/cjs/src/core/RoutingEngine.d.ts.map +1 -1
- package/dist/cjs/src/core/RoutingEngine.js +113 -9
- package/dist/cjs/src/core/RoutingEngine.js.map +1 -1
- package/dist/cjs/src/core/SessionManager.d.ts +14 -4
- package/dist/cjs/src/core/SessionManager.d.ts.map +1 -1
- package/dist/cjs/src/core/SessionManager.js +25 -5
- package/dist/cjs/src/core/SessionManager.js.map +1 -1
- package/dist/cjs/src/core/Step.d.ts +10 -10
- package/dist/cjs/src/core/Step.d.ts.map +1 -1
- package/dist/cjs/src/core/Step.js.map +1 -1
- package/dist/cjs/src/core/ToolExecutor.d.ts +4 -2
- package/dist/cjs/src/core/ToolExecutor.d.ts.map +1 -1
- package/dist/cjs/src/core/ToolExecutor.js +13 -3
- package/dist/cjs/src/core/ToolExecutor.js.map +1 -1
- package/dist/cjs/src/index.d.ts +3 -1
- package/dist/cjs/src/index.d.ts.map +1 -1
- package/dist/cjs/src/index.js +7 -1
- package/dist/cjs/src/index.js.map +1 -1
- package/dist/cjs/src/types/agent.d.ts +42 -21
- package/dist/cjs/src/types/agent.d.ts.map +1 -1
- package/dist/cjs/src/types/agent.js.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 +1 -1
- package/dist/cjs/src/types/index.d.ts.map +1 -1
- package/dist/cjs/src/types/index.js.map +1 -1
- package/dist/cjs/src/types/persistence.d.ts +0 -1
- package/dist/cjs/src/types/persistence.d.ts.map +1 -1
- package/dist/cjs/src/types/route.d.ts +22 -16
- package/dist/cjs/src/types/route.d.ts.map +1 -1
- package/dist/cjs/src/types/session.d.ts +6 -11
- package/dist/cjs/src/types/session.d.ts.map +1 -1
- package/dist/cjs/src/types/tool.d.ts +12 -6
- package/dist/cjs/src/types/tool.d.ts.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/cjs/src/utils/session.d.ts +2 -2
- package/dist/cjs/src/utils/session.d.ts.map +1 -1
- package/dist/cjs/src/utils/session.js +6 -26
- package/dist/cjs/src/utils/session.js.map +1 -1
- package/dist/src/core/Agent.d.ts +77 -59
- package/dist/src/core/Agent.d.ts.map +1 -1
- package/dist/src/core/Agent.js +285 -1061
- package/dist/src/core/Agent.js.map +1 -1
- package/dist/src/core/PersistenceManager.d.ts.map +1 -1
- package/dist/src/core/PersistenceManager.js +48 -25
- package/dist/src/core/PersistenceManager.js.map +1 -1
- package/dist/src/core/PromptComposer.d.ts +1 -1
- package/dist/src/core/PromptComposer.d.ts.map +1 -1
- package/dist/src/core/PromptComposer.js.map +1 -1
- package/dist/src/core/ResponseEngine.d.ts +13 -12
- package/dist/src/core/ResponseEngine.d.ts.map +1 -1
- package/dist/src/core/ResponseEngine.js +4 -4
- package/dist/src/core/ResponseEngine.js.map +1 -1
- package/dist/src/core/ResponseModal.d.ts +205 -0
- package/dist/src/core/ResponseModal.d.ts.map +1 -0
- package/dist/src/core/ResponseModal.js +1323 -0
- package/dist/src/core/ResponseModal.js.map +1 -0
- package/dist/src/core/ResponsePipeline.d.ts +66 -38
- package/dist/src/core/ResponsePipeline.d.ts.map +1 -1
- package/dist/src/core/ResponsePipeline.js +72 -4
- package/dist/src/core/ResponsePipeline.js.map +1 -1
- package/dist/src/core/Route.d.ts +24 -5
- package/dist/src/core/Route.d.ts.map +1 -1
- package/dist/src/core/Route.js +45 -1
- package/dist/src/core/Route.js.map +1 -1
- package/dist/src/core/RoutingEngine.d.ts +31 -6
- package/dist/src/core/RoutingEngine.d.ts.map +1 -1
- package/dist/src/core/RoutingEngine.js +113 -9
- package/dist/src/core/RoutingEngine.js.map +1 -1
- package/dist/src/core/SessionManager.d.ts +14 -4
- package/dist/src/core/SessionManager.d.ts.map +1 -1
- package/dist/src/core/SessionManager.js +25 -5
- package/dist/src/core/SessionManager.js.map +1 -1
- package/dist/src/core/Step.d.ts +10 -10
- package/dist/src/core/Step.d.ts.map +1 -1
- package/dist/src/core/Step.js.map +1 -1
- package/dist/src/core/ToolExecutor.d.ts +4 -2
- package/dist/src/core/ToolExecutor.d.ts.map +1 -1
- package/dist/src/core/ToolExecutor.js +13 -3
- package/dist/src/core/ToolExecutor.js.map +1 -1
- package/dist/src/index.d.ts +3 -1
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +2 -1
- package/dist/src/index.js.map +1 -1
- package/dist/src/types/agent.d.ts +42 -21
- package/dist/src/types/agent.d.ts.map +1 -1
- package/dist/src/types/agent.js.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 +1 -1
- package/dist/src/types/index.d.ts.map +1 -1
- package/dist/src/types/index.js.map +1 -1
- package/dist/src/types/persistence.d.ts +0 -1
- package/dist/src/types/persistence.d.ts.map +1 -1
- package/dist/src/types/route.d.ts +22 -16
- package/dist/src/types/route.d.ts.map +1 -1
- package/dist/src/types/session.d.ts +6 -11
- package/dist/src/types/session.d.ts.map +1 -1
- package/dist/src/types/tool.d.ts +12 -6
- package/dist/src/types/tool.d.ts.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/dist/src/utils/session.d.ts +2 -2
- package/dist/src/utils/session.d.ts.map +1 -1
- package/dist/src/utils/session.js +6 -26
- package/dist/src/utils/session.js.map +1 -1
- package/docs/README.md +5 -4
- package/docs/api/README.md +195 -4
- package/docs/api/overview.md +232 -13
- package/docs/core/agent/README.md +162 -17
- package/docs/core/agent/context-management.md +39 -15
- package/docs/core/agent/session-management.md +49 -16
- package/docs/core/ai-integration/prompt-composition.md +38 -14
- package/docs/core/ai-integration/response-processing.md +28 -17
- package/docs/core/conversation-flows/data-collection.md +103 -25
- package/docs/core/conversation-flows/route-dsl.md +45 -22
- package/docs/core/conversation-flows/routes.md +74 -18
- package/docs/core/conversation-flows/step-transitions.md +3 -3
- package/docs/core/conversation-flows/steps.md +39 -15
- package/docs/core/routing/intelligent-routing.md +18 -9
- package/docs/core/tools/tool-definition.md +8 -8
- package/docs/core/tools/tool-execution.md +26 -26
- package/docs/core/tools/tool-scoping.md +5 -5
- package/docs/guides/getting-started/README.md +54 -32
- 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 +37 -28
- package/examples/advanced-patterns/persistent-onboarding.ts +70 -41
- package/examples/advanced-patterns/route-lifecycle-hooks.ts +28 -2
- package/examples/advanced-patterns/streaming-responses.ts +197 -119
- package/examples/ai-providers/anthropic-integration.ts +40 -33
- package/examples/ai-providers/openai-integration.ts +25 -25
- package/examples/conversation-flows/completion-transitions.ts +36 -32
- package/examples/core-concepts/basic-agent.ts +76 -78
- package/examples/core-concepts/modern-streaming-api.ts +309 -0
- package/examples/core-concepts/schema-driven-extraction.ts +20 -16
- package/examples/core-concepts/session-management.ts +65 -53
- package/examples/integrations/database-integration.ts +49 -34
- package/examples/integrations/healthcare-integration.ts +96 -91
- package/examples/integrations/search-integration.ts +79 -82
- package/examples/integrations/server-session-management.ts +25 -17
- package/examples/persistence/database-persistence.ts +61 -45
- package/examples/persistence/memory-sessions.ts +52 -63
- package/examples/persistence/redis-persistence.ts +81 -95
- package/examples/tools/basic-tools.ts +73 -62
- package/examples/tools/data-enrichment-tools.ts +52 -44
- package/package.json +1 -1
- package/src/core/Agent.ts +396 -1499
- package/src/core/PersistenceManager.ts +51 -27
- package/src/core/PromptComposer.ts +1 -1
- package/src/core/ResponseEngine.ts +21 -19
- package/src/core/ResponseModal.ts +1722 -0
- package/src/core/ResponsePipeline.ts +175 -60
- package/src/core/Route.ts +58 -6
- package/src/core/RoutingEngine.ts +174 -27
- package/src/core/SessionManager.ts +32 -8
- package/src/core/Step.ts +20 -12
- package/src/core/ToolExecutor.ts +19 -5
- package/src/index.ts +11 -0
- package/src/types/agent.ts +47 -23
- package/src/types/ai.ts +1 -1
- package/src/types/index.ts +2 -0
- package/src/types/persistence.ts +0 -1
- package/src/types/route.ts +22 -16
- package/src/types/session.ts +6 -12
- package/src/types/tool.ts +15 -9
- package/src/utils/clone.ts +6 -8
- package/src/utils/history.ts +190 -27
- package/src/utils/index.ts +4 -0
- package/src/utils/session.ts +6 -31
|
@@ -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,7 +65,7 @@ interface FeedbackData {
|
|
|
65
65
|
// ==============================================================================
|
|
66
66
|
|
|
67
67
|
// Tool: Fetch latest company news (context enrichment)
|
|
68
|
-
const fetchNewsTool: Tool<CompanyContext, [], void> = {
|
|
68
|
+
const fetchNewsTool: Tool<CompanyContext, UnifiedData, [], void> = {
|
|
69
69
|
id: "fetch_news",
|
|
70
70
|
name: "Company News Fetcher",
|
|
71
71
|
description: "Retrieve latest company news and updates",
|
|
@@ -96,7 +96,7 @@ const fetchNewsTool: Tool<CompanyContext, [], void> = {
|
|
|
96
96
|
};
|
|
97
97
|
|
|
98
98
|
// Tool: Search knowledge base (context enrichment)
|
|
99
|
-
const searchKnowledgeTool: Tool<CompanyContext, [], string> = {
|
|
99
|
+
const searchKnowledgeTool: Tool<CompanyContext,UnifiedData, [], string> = {
|
|
100
100
|
id: "search_knowledge",
|
|
101
101
|
name: "Knowledge Base Search",
|
|
102
102
|
description: "Search FAQs and documentation",
|
|
@@ -139,7 +139,28 @@ const searchKnowledgeTool: Tool<CompanyContext, [], string> = {
|
|
|
139
139
|
// AGENT SETUP
|
|
140
140
|
// ==============================================================================
|
|
141
141
|
|
|
142
|
-
|
|
142
|
+
// Define unified data schema for all interactions
|
|
143
|
+
interface UnifiedData extends FeedbackData {}
|
|
144
|
+
|
|
145
|
+
const unifiedSchema = {
|
|
146
|
+
type: "object",
|
|
147
|
+
properties: {
|
|
148
|
+
// Feedback fields
|
|
149
|
+
rating: {
|
|
150
|
+
type: "number",
|
|
151
|
+
description: "A rating from 1 to 5",
|
|
152
|
+
minimum: 1,
|
|
153
|
+
maximum: 5,
|
|
154
|
+
},
|
|
155
|
+
comments: { type: "string", description: "Open-ended feedback" },
|
|
156
|
+
contactPermission: {
|
|
157
|
+
type: "boolean",
|
|
158
|
+
description: "Permission to contact the user for more details",
|
|
159
|
+
},
|
|
160
|
+
},
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
const agent = new Agent<CompanyContext, UnifiedData>({
|
|
143
164
|
name: "Acme Support Agent",
|
|
144
165
|
goal: "Answer questions about Acme Corp and our products",
|
|
145
166
|
description:
|
|
@@ -150,6 +171,8 @@ const agent = new Agent<CompanyContext>({
|
|
|
150
171
|
apiKey: process.env.OPENAI_API_KEY || "test-key",
|
|
151
172
|
model: "gpt-5o-mini",
|
|
152
173
|
}),
|
|
174
|
+
// NEW: Agent-level schema
|
|
175
|
+
schema: unifiedSchema,
|
|
153
176
|
|
|
154
177
|
// Initialize with company knowledge
|
|
155
178
|
context: {
|
|
@@ -360,27 +383,14 @@ agent.createRoute({
|
|
|
360
383
|
// Initial step is enough for fallback conversations
|
|
361
384
|
|
|
362
385
|
// Route 7: Collect Feedback (Stepful Example)
|
|
363
|
-
const feedbackRoute = agent.createRoute
|
|
386
|
+
const feedbackRoute = agent.createRoute({
|
|
364
387
|
title: "Collect Feedback",
|
|
365
388
|
description: "Collect user feedback about their experience",
|
|
366
389
|
conditions: ["User wants to leave feedback", "User seems satisfied or upset"],
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
type: "number",
|
|
372
|
-
description: "A rating from 1 to 5",
|
|
373
|
-
minimum: 1,
|
|
374
|
-
maximum: 5,
|
|
375
|
-
},
|
|
376
|
-
comments: { type: "string", description: "Open-ended feedback" },
|
|
377
|
-
contactPermission: {
|
|
378
|
-
type: "boolean",
|
|
379
|
-
description: "Permission to contact the user for more details",
|
|
380
|
-
},
|
|
381
|
-
},
|
|
382
|
-
required: ["rating", "comments"],
|
|
383
|
-
},
|
|
390
|
+
// NEW: Required fields for route completion
|
|
391
|
+
requiredFields: ["rating", "comments"],
|
|
392
|
+
// NEW: Optional fields
|
|
393
|
+
optionalFields: ["contactPermission"],
|
|
384
394
|
endStep: {
|
|
385
395
|
prompt:
|
|
386
396
|
"Thank the user warmly for their valuable feedback and let them know we appreciate their time",
|
|
@@ -456,7 +466,7 @@ async function exampleConversations() {
|
|
|
456
466
|
},
|
|
457
467
|
];
|
|
458
468
|
|
|
459
|
-
const response2 = await agent.respond({ history: history2
|
|
469
|
+
const response2 = await agent.respond({ history: history2 });
|
|
460
470
|
console.log("AI:", response2.message);
|
|
461
471
|
console.log("Route:", response2.session?.currentRoute?.title);
|
|
462
472
|
// Expected: "We offer two main products: Acme Widget ($99.99)..."
|
|
@@ -474,7 +484,7 @@ async function exampleConversations() {
|
|
|
474
484
|
},
|
|
475
485
|
];
|
|
476
486
|
|
|
477
|
-
const response3 = await agent.respond({ history: history3
|
|
487
|
+
const response3 = await agent.respond({ history: history3 });
|
|
478
488
|
console.log("AI:", response3.message);
|
|
479
489
|
console.log("Route:", response3.session?.currentRoute?.title);
|
|
480
490
|
// Expected: "We offer a 30-day money-back guarantee..."
|
|
@@ -492,7 +502,7 @@ async function exampleConversations() {
|
|
|
492
502
|
},
|
|
493
503
|
];
|
|
494
504
|
|
|
495
|
-
const response4 = await agent.respond({ history: history4
|
|
505
|
+
const response4 = await agent.respond({ history: history4 });
|
|
496
506
|
console.log("AI:", response4.message);
|
|
497
507
|
console.log("Route:", response4.session?.currentRoute?.title);
|
|
498
508
|
// Tool fetches news → Updates context → AI responds with news
|
|
@@ -512,7 +522,7 @@ async function exampleConversations() {
|
|
|
512
522
|
name: "User",
|
|
513
523
|
},
|
|
514
524
|
];
|
|
515
|
-
const resp1 = await agent.respond({ history: turn1
|
|
525
|
+
const resp1 = await agent.respond({ history: turn1 });
|
|
516
526
|
console.log("User: Tell me about the Acme Widget");
|
|
517
527
|
console.log("AI:", resp1.message);
|
|
518
528
|
|
|
@@ -551,14 +561,13 @@ async function exampleConversations() {
|
|
|
551
561
|
|
|
552
562
|
const feedbackResponse = await agent.respond({
|
|
553
563
|
history: feedbackHistory,
|
|
554
|
-
session,
|
|
555
564
|
});
|
|
556
565
|
console.log("AI:", feedbackResponse.message);
|
|
557
566
|
console.log("Route:", feedbackResponse.session?.currentRoute?.title);
|
|
558
567
|
|
|
559
568
|
if (feedbackResponse.isRouteComplete) {
|
|
560
569
|
console.log("\n✅ Feedback collection complete!");
|
|
561
|
-
await processFeedback(agent.
|
|
570
|
+
await processFeedback(agent.getCollectedData());
|
|
562
571
|
} else {
|
|
563
572
|
console.log("\n⏳ Feedback collection in progress...");
|
|
564
573
|
}
|
|
@@ -568,7 +577,7 @@ async function exampleConversations() {
|
|
|
568
577
|
* Mock function to process collected feedback.
|
|
569
578
|
* @param data The feedback data collected from the user.
|
|
570
579
|
*/
|
|
571
|
-
async function processFeedback(data: Partial<
|
|
580
|
+
async function processFeedback(data: Partial<UnifiedData>) {
|
|
572
581
|
console.log("\n" + "=".repeat(60));
|
|
573
582
|
console.log("Processing user feedback...");
|
|
574
583
|
console.log("=".repeat(60));
|