@falai/agent 0.9.0-alpha-1 → 0.9.0-alpha-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.
Files changed (166) hide show
  1. package/README.md +34 -22
  2. package/dist/cjs/src/core/Agent.d.ts +52 -24
  3. package/dist/cjs/src/core/Agent.d.ts.map +1 -1
  4. package/dist/cjs/src/core/Agent.js +266 -39
  5. package/dist/cjs/src/core/Agent.js.map +1 -1
  6. package/dist/cjs/src/core/PersistenceManager.d.ts.map +1 -1
  7. package/dist/cjs/src/core/PersistenceManager.js +48 -25
  8. package/dist/cjs/src/core/PersistenceManager.js.map +1 -1
  9. package/dist/cjs/src/core/PromptComposer.d.ts +1 -1
  10. package/dist/cjs/src/core/PromptComposer.d.ts.map +1 -1
  11. package/dist/cjs/src/core/PromptComposer.js.map +1 -1
  12. package/dist/cjs/src/core/ResponseEngine.d.ts +13 -12
  13. package/dist/cjs/src/core/ResponseEngine.d.ts.map +1 -1
  14. package/dist/cjs/src/core/ResponseEngine.js +4 -4
  15. package/dist/cjs/src/core/ResponseEngine.js.map +1 -1
  16. package/dist/cjs/src/core/ResponsePipeline.d.ts +66 -38
  17. package/dist/cjs/src/core/ResponsePipeline.d.ts.map +1 -1
  18. package/dist/cjs/src/core/ResponsePipeline.js +71 -3
  19. package/dist/cjs/src/core/ResponsePipeline.js.map +1 -1
  20. package/dist/cjs/src/core/Route.d.ts +24 -5
  21. package/dist/cjs/src/core/Route.d.ts.map +1 -1
  22. package/dist/cjs/src/core/Route.js +45 -1
  23. package/dist/cjs/src/core/Route.js.map +1 -1
  24. package/dist/cjs/src/core/RoutingEngine.d.ts +31 -6
  25. package/dist/cjs/src/core/RoutingEngine.d.ts.map +1 -1
  26. package/dist/cjs/src/core/RoutingEngine.js +113 -9
  27. package/dist/cjs/src/core/RoutingEngine.js.map +1 -1
  28. package/dist/cjs/src/core/SessionManager.d.ts +14 -4
  29. package/dist/cjs/src/core/SessionManager.d.ts.map +1 -1
  30. package/dist/cjs/src/core/SessionManager.js +25 -5
  31. package/dist/cjs/src/core/SessionManager.js.map +1 -1
  32. package/dist/cjs/src/core/Step.d.ts +10 -10
  33. package/dist/cjs/src/core/Step.d.ts.map +1 -1
  34. package/dist/cjs/src/core/Step.js.map +1 -1
  35. package/dist/cjs/src/core/ToolExecutor.d.ts +4 -2
  36. package/dist/cjs/src/core/ToolExecutor.d.ts.map +1 -1
  37. package/dist/cjs/src/core/ToolExecutor.js +13 -3
  38. package/dist/cjs/src/core/ToolExecutor.js.map +1 -1
  39. package/dist/cjs/src/types/agent.d.ts +41 -21
  40. package/dist/cjs/src/types/agent.d.ts.map +1 -1
  41. package/dist/cjs/src/types/agent.js.map +1 -1
  42. package/dist/cjs/src/types/index.d.ts +1 -1
  43. package/dist/cjs/src/types/index.d.ts.map +1 -1
  44. package/dist/cjs/src/types/index.js.map +1 -1
  45. package/dist/cjs/src/types/persistence.d.ts +0 -1
  46. package/dist/cjs/src/types/persistence.d.ts.map +1 -1
  47. package/dist/cjs/src/types/route.d.ts +22 -16
  48. package/dist/cjs/src/types/route.d.ts.map +1 -1
  49. package/dist/cjs/src/types/session.d.ts +6 -11
  50. package/dist/cjs/src/types/session.d.ts.map +1 -1
  51. package/dist/cjs/src/types/tool.d.ts +12 -6
  52. package/dist/cjs/src/types/tool.d.ts.map +1 -1
  53. package/dist/cjs/src/utils/session.d.ts +2 -2
  54. package/dist/cjs/src/utils/session.d.ts.map +1 -1
  55. package/dist/cjs/src/utils/session.js +6 -26
  56. package/dist/cjs/src/utils/session.js.map +1 -1
  57. package/dist/src/core/Agent.d.ts +52 -24
  58. package/dist/src/core/Agent.d.ts.map +1 -1
  59. package/dist/src/core/Agent.js +266 -39
  60. package/dist/src/core/Agent.js.map +1 -1
  61. package/dist/src/core/PersistenceManager.d.ts.map +1 -1
  62. package/dist/src/core/PersistenceManager.js +48 -25
  63. package/dist/src/core/PersistenceManager.js.map +1 -1
  64. package/dist/src/core/PromptComposer.d.ts +1 -1
  65. package/dist/src/core/PromptComposer.d.ts.map +1 -1
  66. package/dist/src/core/PromptComposer.js.map +1 -1
  67. package/dist/src/core/ResponseEngine.d.ts +13 -12
  68. package/dist/src/core/ResponseEngine.d.ts.map +1 -1
  69. package/dist/src/core/ResponseEngine.js +4 -4
  70. package/dist/src/core/ResponseEngine.js.map +1 -1
  71. package/dist/src/core/ResponsePipeline.d.ts +66 -38
  72. package/dist/src/core/ResponsePipeline.d.ts.map +1 -1
  73. package/dist/src/core/ResponsePipeline.js +71 -3
  74. package/dist/src/core/ResponsePipeline.js.map +1 -1
  75. package/dist/src/core/Route.d.ts +24 -5
  76. package/dist/src/core/Route.d.ts.map +1 -1
  77. package/dist/src/core/Route.js +45 -1
  78. package/dist/src/core/Route.js.map +1 -1
  79. package/dist/src/core/RoutingEngine.d.ts +31 -6
  80. package/dist/src/core/RoutingEngine.d.ts.map +1 -1
  81. package/dist/src/core/RoutingEngine.js +113 -9
  82. package/dist/src/core/RoutingEngine.js.map +1 -1
  83. package/dist/src/core/SessionManager.d.ts +14 -4
  84. package/dist/src/core/SessionManager.d.ts.map +1 -1
  85. package/dist/src/core/SessionManager.js +25 -5
  86. package/dist/src/core/SessionManager.js.map +1 -1
  87. package/dist/src/core/Step.d.ts +10 -10
  88. package/dist/src/core/Step.d.ts.map +1 -1
  89. package/dist/src/core/Step.js.map +1 -1
  90. package/dist/src/core/ToolExecutor.d.ts +4 -2
  91. package/dist/src/core/ToolExecutor.d.ts.map +1 -1
  92. package/dist/src/core/ToolExecutor.js +13 -3
  93. package/dist/src/core/ToolExecutor.js.map +1 -1
  94. package/dist/src/types/agent.d.ts +41 -21
  95. package/dist/src/types/agent.d.ts.map +1 -1
  96. package/dist/src/types/agent.js.map +1 -1
  97. package/dist/src/types/index.d.ts +1 -1
  98. package/dist/src/types/index.d.ts.map +1 -1
  99. package/dist/src/types/index.js.map +1 -1
  100. package/dist/src/types/persistence.d.ts +0 -1
  101. package/dist/src/types/persistence.d.ts.map +1 -1
  102. package/dist/src/types/route.d.ts +22 -16
  103. package/dist/src/types/route.d.ts.map +1 -1
  104. package/dist/src/types/session.d.ts +6 -11
  105. package/dist/src/types/session.d.ts.map +1 -1
  106. package/dist/src/types/tool.d.ts +12 -6
  107. package/dist/src/types/tool.d.ts.map +1 -1
  108. package/dist/src/utils/session.d.ts +2 -2
  109. package/dist/src/utils/session.d.ts.map +1 -1
  110. package/dist/src/utils/session.js +6 -26
  111. package/dist/src/utils/session.js.map +1 -1
  112. package/docs/README.md +3 -3
  113. package/docs/api/README.md +35 -4
  114. package/docs/api/overview.md +166 -12
  115. package/docs/core/agent/README.md +162 -17
  116. package/docs/core/agent/context-management.md +39 -15
  117. package/docs/core/agent/session-management.md +49 -16
  118. package/docs/core/ai-integration/prompt-composition.md +38 -14
  119. package/docs/core/ai-integration/response-processing.md +28 -17
  120. package/docs/core/conversation-flows/data-collection.md +103 -25
  121. package/docs/core/conversation-flows/route-dsl.md +45 -22
  122. package/docs/core/conversation-flows/routes.md +74 -18
  123. package/docs/core/conversation-flows/step-transitions.md +3 -3
  124. package/docs/core/conversation-flows/steps.md +39 -15
  125. package/docs/core/routing/intelligent-routing.md +18 -9
  126. package/docs/core/tools/tool-definition.md +8 -8
  127. package/docs/core/tools/tool-execution.md +26 -26
  128. package/docs/core/tools/tool-scoping.md +5 -5
  129. package/docs/guides/getting-started/README.md +54 -32
  130. package/examples/advanced-patterns/knowledge-based-agent.ts +37 -28
  131. package/examples/advanced-patterns/persistent-onboarding.ts +70 -41
  132. package/examples/advanced-patterns/route-lifecycle-hooks.ts +28 -2
  133. package/examples/advanced-patterns/streaming-responses.ts +28 -23
  134. package/examples/ai-providers/anthropic-integration.ts +40 -33
  135. package/examples/ai-providers/openai-integration.ts +25 -25
  136. package/examples/conversation-flows/completion-transitions.ts +36 -32
  137. package/examples/core-concepts/basic-agent.ts +76 -78
  138. package/examples/core-concepts/schema-driven-extraction.ts +20 -16
  139. package/examples/core-concepts/session-management.ts +65 -53
  140. package/examples/integrations/database-integration.ts +49 -34
  141. package/examples/integrations/healthcare-integration.ts +96 -91
  142. package/examples/integrations/search-integration.ts +79 -82
  143. package/examples/integrations/server-session-management.ts +25 -17
  144. package/examples/persistence/database-persistence.ts +61 -45
  145. package/examples/persistence/memory-sessions.ts +52 -63
  146. package/examples/persistence/redis-persistence.ts +81 -95
  147. package/examples/tools/basic-tools.ts +73 -62
  148. package/examples/tools/data-enrichment-tools.ts +52 -44
  149. package/package.json +1 -1
  150. package/src/core/Agent.ts +418 -128
  151. package/src/core/PersistenceManager.ts +51 -27
  152. package/src/core/PromptComposer.ts +1 -1
  153. package/src/core/ResponseEngine.ts +21 -19
  154. package/src/core/ResponsePipeline.ts +174 -59
  155. package/src/core/Route.ts +58 -6
  156. package/src/core/RoutingEngine.ts +174 -27
  157. package/src/core/SessionManager.ts +32 -8
  158. package/src/core/Step.ts +20 -12
  159. package/src/core/ToolExecutor.ts +19 -5
  160. package/src/types/agent.ts +46 -23
  161. package/src/types/index.ts +2 -0
  162. package/src/types/persistence.ts +0 -1
  163. package/src/types/route.ts +22 -16
  164. package/src/types/session.ts +6 -12
  165. package/src/types/tool.ts +15 -9
  166. package/src/utils/session.ts +6 -31
@@ -17,7 +17,7 @@ The tool execution system provides:
17
17
  ### Basic Tool Structure
18
18
 
19
19
  ```typescript
20
- interface Tool<TContext, TArgs extends unknown[], TResult, TData> {
20
+ interface Tool<TContext, TData, TArgs extends unknown[], TResult> {
21
21
  id: string;
22
22
  name?: string; // Human-readable name shown to AI models
23
23
  description: string;
@@ -32,7 +32,7 @@ interface Tool<TContext, TArgs extends unknown[], TResult, TData> {
32
32
  import { Tool } from "@falai/agent";
33
33
 
34
34
  // Simple data retrieval tool
35
- const getWeather: Tool<unknown, [], string, WeatherData> = {
35
+ const getWeather: Tool<unknown, WeatherData, [], string> = {
36
36
  id: "get_weather",
37
37
  name: "Weather Checker",
38
38
  description: "Get current weather for a location",
@@ -56,7 +56,7 @@ const getWeather: Tool<unknown, [], string, WeatherData> = {
56
56
  };
57
57
 
58
58
  // Data modification tool
59
- const updateUserProfile: Tool<unknown, [], string, ProfileData> = {
59
+ const updateUserProfile: Tool<unknown, ProfileData, [], string> = {
60
60
  id: "update_profile",
61
61
  name: "Profile Updater",
62
62
  description: "Update user profile information",
@@ -136,9 +136,9 @@ Tools can modify agent context:
136
136
  ```typescript
137
137
  const locationTracker: Tool<
138
138
  { currentLocation?: string; locationHistory?: string[] },
139
+ { location: string },
139
140
  [],
140
- string,
141
- { location: string }
141
+ string
142
142
  > = {
143
143
  id: "track_location",
144
144
  description: "Track and update location information",
@@ -169,9 +169,9 @@ Tools can access current context:
169
169
  ```typescript
170
170
  const contextualTool: Tool<
171
171
  { userName?: string; currentLocation?: string },
172
+ {},
172
173
  [],
173
- string,
174
- {}
174
+ string
175
175
  > = {
176
176
  id: "personalized_greeting",
177
177
  description: "Generate personalized greeting based on context",
@@ -196,7 +196,7 @@ const contextualTool: Tool<
196
196
  Tools can modify session-collected data:
197
197
 
198
198
  ```typescript
199
- const dataEnrichmentTool: Tool<{}, [], string, { email?: string }> = {
199
+ const dataEnrichmentTool: Tool<{}, { email?: string }, [], string> = {
200
200
  id: "enrich_user_data",
201
201
  description: "Enrich user profile with additional information",
202
202
  handler: async ({ data }) => {
@@ -221,7 +221,7 @@ const dataEnrichmentTool: Tool<{}, [], string, { email?: string }> = {
221
221
  ### Validation Integration
222
222
 
223
223
  ```typescript
224
- const validatingTool: Tool<{}, [], string, any> = {
224
+ const validatingTool: Tool<{}, any, [], string> = {
225
225
  id: "validate_and_save",
226
226
  description: "Validate collected data and save to database",
227
227
  handler: async ({ data }) => {
@@ -362,9 +362,9 @@ while (hasToolCalls && toolLoopCount < MAX_TOOL_LOOPS) {
362
362
  ```typescript
363
363
  const robustTool: Tool<
364
364
  { lastApiCall?: string; errorCount?: number },
365
+ { endpoint: string },
365
366
  [],
366
- string,
367
- { endpoint: string }
367
+ string
368
368
  > = {
369
369
  id: "api_call",
370
370
  description: "Make external API call with error handling",
@@ -400,9 +400,9 @@ const robustTool: Tool<
400
400
  ```typescript
401
401
  const fallbackTool: Tool<
402
402
  { searchFallbackUsed?: boolean },
403
+ { query: string },
403
404
  [],
404
- string,
405
- { query: string }
405
+ string
406
406
  > = {
407
407
  id: "fallback_search",
408
408
  description: "Search with automatic fallback mechanisms",
@@ -452,9 +452,9 @@ let toolState = { conversationId: null };
452
452
 
453
453
  const conversationalTool: Tool<
454
454
  { conversationState?: any; lastMessage?: string },
455
+ { message: string },
455
456
  [],
456
- string,
457
- { message: string }
457
+ string
458
458
  > = {
459
459
  id: "continue_conversation",
460
460
  description: "Continue multi-turn conversation with state management",
@@ -493,9 +493,9 @@ Tools that set up data for other tools:
493
493
  ```typescript
494
494
  const setupTool: Tool<
495
495
  { activeWorkflowId?: string; workflowType?: string; workflowStep?: number },
496
+ { workflowType: string },
496
497
  [],
497
- string,
498
- { workflowType: string }
498
+ string
499
499
  > = {
500
500
  id: "setup_workflow",
501
501
  description: "Initialize a new workflow process",
@@ -526,9 +526,9 @@ const setupTool: Tool<
526
526
 
527
527
  const stepTool: Tool<
528
528
  { activeWorkflowId?: string; workflowStep?: number; lastStepResult?: any },
529
+ {},
529
530
  [],
530
- string,
531
- {}
531
+ string
532
532
  > = {
533
533
  id: "execute_workflow_step",
534
534
  description: "Execute the next step in active workflow",
@@ -559,7 +559,7 @@ const stepTool: Tool<
559
559
 
560
560
  ```typescript
561
561
  // Cache expensive operations
562
- const cachedTool: Tool<{ lastCacheHit?: boolean }, [], any, { key: string }> = {
562
+ const cachedTool: Tool<{ lastCacheHit?: boolean }, { key: string }, [], any> = {
563
563
  id: "cached_data_lookup",
564
564
  description: "Lookup data with caching for performance",
565
565
  parameters: {
@@ -592,9 +592,9 @@ const cachedTool: Tool<{ lastCacheHit?: boolean }, [], any, { key: string }> = {
592
592
  ```typescript
593
593
  const batchTool: Tool<
594
594
  {},
595
+ { items: string[]; processedItems?: any[]; batchCompletedAt?: string },
595
596
  [],
596
- string,
597
- { items: string[]; processedItems?: any[]; batchCompletedAt?: string }
597
+ string
598
598
  > = {
599
599
  id: "batch_process",
600
600
  description: "Process multiple items in a single batch operation",
@@ -629,7 +629,7 @@ const batchTool: Tool<
629
629
  ### Tool Permissions
630
630
 
631
631
  ```typescript
632
- const secureTool: Tool<{ userRole?: string }, [], any, { action: string }> = {
632
+ const secureTool: Tool<{ userRole?: string }, { action: string }, [], any> = {
633
633
  id: "admin_action",
634
634
  description: "Perform administrative actions with permission checks",
635
635
  parameters: {
@@ -662,9 +662,9 @@ const secureTool: Tool<{ userRole?: string }, [], any, { action: string }> = {
662
662
  ```typescript
663
663
  const validatedTool: Tool<
664
664
  { userId?: string; userRole?: string },
665
+ { userId: string; updates: any },
665
666
  [],
666
- any,
667
- { userId: string; updates: any }
667
+ any
668
668
  > = {
669
669
  id: "user_update",
670
670
  description: "Update user data with validation and permission checks",
@@ -717,7 +717,7 @@ const agent = new Agent({
717
717
  ### Performance Monitoring
718
718
 
719
719
  ```typescript
720
- const monitoredTool: Tool<{}, [], any, { args: any }> = {
720
+ const monitoredTool: Tool<{}, { args: any }, [], any> = {
721
721
  id: "monitored_operation",
722
722
  description: "Execute operation with performance monitoring",
723
723
  parameters: {
@@ -214,7 +214,7 @@ const secureTool = {
214
214
  ```typescript
215
215
  import { Tool } from "@falai/agent";
216
216
 
217
- const contextSecureTool: Tool<SecureContext, [], UserData> = {
217
+ const contextSecureTool: Tool<SecureContext, UserData, [], any> = {
218
218
  id: "user_data_access",
219
219
  description: "Access user data with security checks",
220
220
  parameters: {
@@ -415,9 +415,9 @@ class ToolRegistry {
415
415
  ```typescript
416
416
  const multiTenantTool: Tool<
417
417
  { tenantId: string },
418
+ { query: string },
418
419
  [],
419
- string,
420
- { query: string }
420
+ string
421
421
  > = {
422
422
  id: "tenant_search",
423
423
  description: "Search within tenant's data scope",
@@ -472,7 +472,7 @@ const timeSensitiveTool = {
472
472
  ### Usage-Based Limiting
473
473
 
474
474
  ```typescript
475
- const limitedTool: Tool<{ userId: string }, [args: any], string, any> = {
475
+ const limitedTool: Tool<{ userId: string }, any, [args: any], string> = {
476
476
  id: "premium_feature",
477
477
  description: "Execute premium feature with usage limits",
478
478
  parameters: {
@@ -528,7 +528,7 @@ const agent = new Agent({
528
528
  ### Access Audit Logging
529
529
 
530
530
  ```typescript
531
- const auditedTool: Tool<{ userId: string }, [args: any], string, any> = {
531
+ const auditedTool: Tool<{ userId: string }, any, [args: any], string> = {
532
532
  id: "sensitive_operation",
533
533
  description: "Perform sensitive operation with audit logging",
534
534
  parameters: {
@@ -128,7 +128,7 @@ interface BookingData {
128
128
  }
129
129
  ```
130
130
 
131
- ### Create a Schema-Driven Route
131
+ ### Create an Agent with Centralized Data Schema
132
132
 
133
133
  ```typescript
134
134
  import { Agent, GeminiProvider, type Tool } from "@falai/agent";
@@ -154,53 +154,66 @@ const checkAvailability: Tool<{}, [], string, BookingData> = {
154
154
  },
155
155
  };
156
156
 
157
- // Create agent
158
- const agent = new Agent({
157
+ // Create agent with centralized data schema
158
+ const agent = new Agent<{}, BookingData>({
159
159
  name: "TravelAgent",
160
160
  provider: new GeminiProvider({
161
161
  apiKey: process.env.GEMINI_API_KEY!,
162
162
  }),
163
- });
164
-
165
- // Data collection schema
166
- const bookingSchema = {
167
- type: "object",
168
- properties: {
169
- destination: { type: "string", description: "Travel destination" },
170
- travelDate: { type: "string", description: "Travel date" },
171
- travelers: { type: "number", minimum: 1, maximum: 10 },
172
- budget: { type: "number", description: "Budget in USD" },
163
+
164
+ // Agent-level schema defines all possible data fields
165
+ schema: {
166
+ type: "object",
167
+ properties: {
168
+ destination: { type: "string", description: "Travel destination" },
169
+ travelDate: { type: "string", description: "Travel date" },
170
+ travelers: { type: "number", minimum: 1, maximum: 10 },
171
+ budget: { type: "number", description: "Budget in USD" },
172
+ },
173
+ required: ["destination", "travelers"],
173
174
  },
174
- required: ["destination", "travelers"],
175
- } as const;
175
+
176
+ // Agent-level tools available to all routes
177
+ tools: [checkAvailability],
178
+
179
+ // Agent-level data validation and enrichment
180
+ hooks: {
181
+ onDataUpdate: async (data, previousData) => {
182
+ // Auto-set budget range based on travelers
183
+ if (data.travelers && !data.budget) {
184
+ data.budget = data.travelers * 500; // Default $500 per person
185
+ }
186
+ return data;
187
+ }
188
+ }
189
+ });
176
190
 
177
- // Create route with schema
178
- const bookingRoute = agent.createRoute<BookingData>({
191
+ // Routes specify required fields instead of schemas
192
+ const bookingRoute = agent.createRoute({
179
193
  title: "Travel Booking",
180
194
  description: "Help users book travel",
181
- schema: bookingSchema,
182
195
  conditions: ["User wants to book travel"],
196
+ requiredFields: ["destination", "travelDate", "travelers"], // Required for completion
197
+ optionalFields: ["budget"], // Nice to have but not required
198
+
183
199
  initialStep: {
184
200
  prompt: "I'd love to help you book a trip! Where would you like to go?",
185
201
  collect: ["destination"],
186
202
  },
187
203
  });
188
204
 
189
- // Add tool to route
190
- bookingRoute.createTool(checkAvailability);
191
-
192
- // Build conversation flow
205
+ // Build conversation flow with agent-level data awareness
193
206
  const askDate = bookingRoute.initialStep.nextStep({
194
207
  prompt: "When would you like to travel?",
195
208
  collect: ["travelDate"],
196
- requires: ["destination"],
197
- skipIf: (data) => !!data.travelDate,
209
+ requires: ["destination"], // Must have destination from agent data
210
+ skipIf: (data) => !!data.travelDate, // Skip if already collected
198
211
  });
199
212
 
200
213
  const askTravelers = askDate.nextStep({
201
214
  prompt: "How many people are traveling?",
202
215
  collect: ["travelers"],
203
- requires: ["destination"],
216
+ requires: ["destination"], // Prerequisites from agent data
204
217
  skipIf: (data) => data.travelers !== undefined,
205
218
  });
206
219
 
@@ -213,22 +226,27 @@ const askBudget = askTravelers.nextStep({
213
226
 
214
227
  const checkAndBook = askBudget.nextStep({
215
228
  prompt: "Let me check availability for your trip.",
216
- tool: checkAvailability,
217
- requires: ["destination", "travelers"],
229
+ tool: checkAvailability, // Tool accesses complete agent data
230
+ requires: ["destination", "travelers"], // Minimum data needed
218
231
  });
219
232
  ```
220
233
 
221
- ### Test the Data-Driven Agent
234
+ ### Test the Agent-Level Data Collection
222
235
 
223
236
  ```typescript
224
237
  async function testBookingAgent() {
225
- // Create agent with automatic session management
226
- const sessionAgent = new Agent({
238
+ // Create agent with automatic session management and agent-level schema
239
+ const sessionAgent = new Agent<{}, BookingData>({
227
240
  name: "TravelAgent",
228
241
  provider: new GeminiProvider({
229
242
  apiKey: process.env.GEMINI_API_KEY!,
230
243
  }),
231
244
  sessionId: "user-alice", // Automatically manages this session
245
+
246
+ // Same agent-level schema and configuration
247
+ schema: agent.schema,
248
+ tools: agent.tools,
249
+ hooks: agent.hooks
232
250
  });
233
251
 
234
252
  // Copy the route to the session agent
@@ -238,13 +256,17 @@ async function testBookingAgent() {
238
256
  const response1 = await sessionAgent.respond("I want to go to Paris");
239
257
 
240
258
  console.log("Bot:", response1.message);
241
- console.log("Collected:", sessionAgent.session.getData<BookingData>());
259
+ console.log("Agent data:", sessionAgent.getCollectedData()); // Agent-level data access
242
260
 
243
261
  // User provides more details - session automatically maintained
244
262
  const response2 = await sessionAgent.respond("Next Friday, 2 people, $2000 budget");
245
263
 
246
264
  console.log("Bot:", response2.message);
247
- console.log("Final data:", sessionAgent.session.getData<BookingData>());
265
+ console.log("Final agent data:", sessionAgent.getCollectedData());
266
+
267
+ // Check route completion
268
+ console.log("Route complete:", bookingRoute.isComplete(sessionAgent.getCollectedData()));
269
+ console.log("Progress:", Math.round(bookingRoute.getCompletionProgress(sessionAgent.getCollectedData()) * 100) + "%");
248
270
  }
249
271
 
250
272
  testBookingAgent();
@@ -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
- const agent = new Agent<CompanyContext>({
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<FeedbackData>({
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
- schema: {
368
- type: "object",
369
- properties: {
370
- rating: {
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, session });
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, session });
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, session });
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, session });
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.getData(feedbackResponse.session?.id));
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<FeedbackData>) {
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));