@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.
Files changed (179) hide show
  1. package/README.md +42 -34
  2. package/dist/cjs/src/core/Agent.d.ts +48 -44
  3. package/dist/cjs/src/core/Agent.d.ts.map +1 -1
  4. package/dist/cjs/src/core/Agent.js +151 -1110
  5. package/dist/cjs/src/core/Agent.js.map +1 -1
  6. package/dist/cjs/src/core/ResponseModal.d.ts +211 -0
  7. package/dist/cjs/src/core/ResponseModal.d.ts.map +1 -0
  8. package/dist/cjs/src/core/ResponseModal.js +1394 -0
  9. package/dist/cjs/src/core/ResponseModal.js.map +1 -0
  10. package/dist/cjs/src/core/ResponsePipeline.d.ts +8 -4
  11. package/dist/cjs/src/core/ResponsePipeline.d.ts.map +1 -1
  12. package/dist/cjs/src/core/ResponsePipeline.js +48 -20
  13. package/dist/cjs/src/core/ResponsePipeline.js.map +1 -1
  14. package/dist/cjs/src/core/Route.d.ts +12 -5
  15. package/dist/cjs/src/core/Route.d.ts.map +1 -1
  16. package/dist/cjs/src/core/Route.js +26 -5
  17. package/dist/cjs/src/core/Route.js.map +1 -1
  18. package/dist/cjs/src/core/RoutingEngine.d.ts +5 -0
  19. package/dist/cjs/src/core/RoutingEngine.d.ts.map +1 -1
  20. package/dist/cjs/src/core/RoutingEngine.js +37 -25
  21. package/dist/cjs/src/core/RoutingEngine.js.map +1 -1
  22. package/dist/cjs/src/core/SessionManager.d.ts +9 -1
  23. package/dist/cjs/src/core/SessionManager.d.ts.map +1 -1
  24. package/dist/cjs/src/core/SessionManager.js +27 -5
  25. package/dist/cjs/src/core/SessionManager.js.map +1 -1
  26. package/dist/cjs/src/core/Step.d.ts +60 -7
  27. package/dist/cjs/src/core/Step.d.ts.map +1 -1
  28. package/dist/cjs/src/core/Step.js +151 -4
  29. package/dist/cjs/src/core/Step.js.map +1 -1
  30. package/dist/cjs/src/core/ToolManager.d.ts +234 -0
  31. package/dist/cjs/src/core/ToolManager.d.ts.map +1 -0
  32. package/dist/cjs/src/core/ToolManager.js +1117 -0
  33. package/dist/cjs/src/core/ToolManager.js.map +1 -0
  34. package/dist/cjs/src/index.d.ts +5 -4
  35. package/dist/cjs/src/index.d.ts.map +1 -1
  36. package/dist/cjs/src/index.js +11 -3
  37. package/dist/cjs/src/index.js.map +1 -1
  38. package/dist/cjs/src/types/agent.d.ts +2 -1
  39. package/dist/cjs/src/types/agent.d.ts.map +1 -1
  40. package/dist/cjs/src/types/ai.d.ts +1 -1
  41. package/dist/cjs/src/types/ai.d.ts.map +1 -1
  42. package/dist/cjs/src/types/index.d.ts +3 -2
  43. package/dist/cjs/src/types/index.d.ts.map +1 -1
  44. package/dist/cjs/src/types/index.js +3 -1
  45. package/dist/cjs/src/types/index.js.map +1 -1
  46. package/dist/cjs/src/types/route.d.ts +6 -4
  47. package/dist/cjs/src/types/route.d.ts.map +1 -1
  48. package/dist/cjs/src/types/tool.d.ts +84 -14
  49. package/dist/cjs/src/types/tool.d.ts.map +1 -1
  50. package/dist/cjs/src/types/tool.js +13 -0
  51. package/dist/cjs/src/types/tool.js.map +1 -1
  52. package/dist/cjs/src/utils/clone.d.ts.map +1 -1
  53. package/dist/cjs/src/utils/clone.js +0 -4
  54. package/dist/cjs/src/utils/clone.js.map +1 -1
  55. package/dist/cjs/src/utils/history.d.ts +30 -1
  56. package/dist/cjs/src/utils/history.d.ts.map +1 -1
  57. package/dist/cjs/src/utils/history.js +169 -23
  58. package/dist/cjs/src/utils/history.js.map +1 -1
  59. package/dist/cjs/src/utils/index.d.ts +1 -1
  60. package/dist/cjs/src/utils/index.d.ts.map +1 -1
  61. package/dist/cjs/src/utils/index.js +5 -1
  62. package/dist/cjs/src/utils/index.js.map +1 -1
  63. package/dist/src/core/Agent.d.ts +48 -44
  64. package/dist/src/core/Agent.d.ts.map +1 -1
  65. package/dist/src/core/Agent.js +152 -1111
  66. package/dist/src/core/Agent.js.map +1 -1
  67. package/dist/src/core/ResponseModal.d.ts +211 -0
  68. package/dist/src/core/ResponseModal.d.ts.map +1 -0
  69. package/dist/src/core/ResponseModal.js +1389 -0
  70. package/dist/src/core/ResponseModal.js.map +1 -0
  71. package/dist/src/core/ResponsePipeline.d.ts +8 -4
  72. package/dist/src/core/ResponsePipeline.d.ts.map +1 -1
  73. package/dist/src/core/ResponsePipeline.js +48 -20
  74. package/dist/src/core/ResponsePipeline.js.map +1 -1
  75. package/dist/src/core/Route.d.ts +12 -5
  76. package/dist/src/core/Route.d.ts.map +1 -1
  77. package/dist/src/core/Route.js +26 -5
  78. package/dist/src/core/Route.js.map +1 -1
  79. package/dist/src/core/RoutingEngine.d.ts +5 -0
  80. package/dist/src/core/RoutingEngine.d.ts.map +1 -1
  81. package/dist/src/core/RoutingEngine.js +37 -25
  82. package/dist/src/core/RoutingEngine.js.map +1 -1
  83. package/dist/src/core/SessionManager.d.ts +9 -1
  84. package/dist/src/core/SessionManager.d.ts.map +1 -1
  85. package/dist/src/core/SessionManager.js +27 -5
  86. package/dist/src/core/SessionManager.js.map +1 -1
  87. package/dist/src/core/Step.d.ts +60 -7
  88. package/dist/src/core/Step.d.ts.map +1 -1
  89. package/dist/src/core/Step.js +151 -4
  90. package/dist/src/core/Step.js.map +1 -1
  91. package/dist/src/core/ToolManager.d.ts +234 -0
  92. package/dist/src/core/ToolManager.d.ts.map +1 -0
  93. package/dist/src/core/ToolManager.js +1111 -0
  94. package/dist/src/core/ToolManager.js.map +1 -0
  95. package/dist/src/index.d.ts +5 -4
  96. package/dist/src/index.d.ts.map +1 -1
  97. package/dist/src/index.js +3 -2
  98. package/dist/src/index.js.map +1 -1
  99. package/dist/src/types/agent.d.ts +2 -1
  100. package/dist/src/types/agent.d.ts.map +1 -1
  101. package/dist/src/types/ai.d.ts +1 -1
  102. package/dist/src/types/ai.d.ts.map +1 -1
  103. package/dist/src/types/index.d.ts +3 -2
  104. package/dist/src/types/index.d.ts.map +1 -1
  105. package/dist/src/types/index.js +1 -0
  106. package/dist/src/types/index.js.map +1 -1
  107. package/dist/src/types/route.d.ts +6 -4
  108. package/dist/src/types/route.d.ts.map +1 -1
  109. package/dist/src/types/tool.d.ts +84 -14
  110. package/dist/src/types/tool.d.ts.map +1 -1
  111. package/dist/src/types/tool.js +12 -1
  112. package/dist/src/types/tool.js.map +1 -1
  113. package/dist/src/utils/clone.d.ts.map +1 -1
  114. package/dist/src/utils/clone.js +0 -4
  115. package/dist/src/utils/clone.js.map +1 -1
  116. package/dist/src/utils/history.d.ts +30 -1
  117. package/dist/src/utils/history.d.ts.map +1 -1
  118. package/dist/src/utils/history.js +165 -23
  119. package/dist/src/utils/history.js.map +1 -1
  120. package/dist/src/utils/index.d.ts +1 -1
  121. package/dist/src/utils/index.d.ts.map +1 -1
  122. package/dist/src/utils/index.js +1 -1
  123. package/dist/src/utils/index.js.map +1 -1
  124. package/docs/CONTRIBUTING.md +40 -0
  125. package/docs/README.md +14 -6
  126. package/docs/api/README.md +235 -45
  127. package/docs/api/overview.md +140 -33
  128. package/docs/core/agent/session-management.md +152 -5
  129. package/docs/core/ai-integration/response-processing.md +115 -4
  130. package/docs/core/conversation-flows/routes.md +130 -0
  131. package/docs/core/error-handling.md +638 -0
  132. package/docs/core/tools/tool-definition.md +684 -60
  133. package/docs/core/tools/tool-scoping.md +244 -53
  134. package/docs/guides/error-handling-patterns.md +578 -0
  135. package/docs/guides/getting-started/README.md +139 -28
  136. package/docs/guides/migration/README.md +72 -0
  137. package/docs/guides/migration/response-modal-refactor.md +518 -0
  138. package/examples/advanced-patterns/knowledge-based-agent.ts +6 -6
  139. package/examples/advanced-patterns/persistent-onboarding.ts +30 -43
  140. package/examples/advanced-patterns/streaming-responses.ts +169 -96
  141. package/examples/ai-providers/anthropic-integration.ts +9 -5
  142. package/examples/ai-providers/openai-integration.ts +11 -7
  143. package/examples/core-concepts/basic-agent.ts +106 -67
  144. package/examples/core-concepts/modern-streaming-api.ts +309 -0
  145. package/examples/core-concepts/schema-driven-extraction.ts +10 -7
  146. package/examples/core-concepts/session-management.ts +71 -18
  147. package/examples/integrations/healthcare-integration.ts +15 -29
  148. package/examples/integrations/server-session-management.ts +3 -3
  149. package/examples/persistence/memory-sessions.ts +3 -3
  150. package/examples/tools/basic-tools.ts +293 -89
  151. package/examples/tools/data-enrichment-tools.ts +185 -75
  152. package/package.json +1 -1
  153. package/src/core/Agent.ts +190 -1529
  154. package/src/core/ResponseModal.ts +1798 -0
  155. package/src/core/ResponsePipeline.ts +83 -57
  156. package/src/core/Route.ts +39 -12
  157. package/src/core/RoutingEngine.ts +46 -42
  158. package/src/core/SessionManager.ts +39 -7
  159. package/src/core/Step.ts +198 -20
  160. package/src/core/ToolManager.ts +1394 -0
  161. package/src/index.ts +19 -3
  162. package/src/types/agent.ts +2 -1
  163. package/src/types/ai.ts +1 -1
  164. package/src/types/index.ts +13 -2
  165. package/src/types/route.ts +6 -4
  166. package/src/types/tool.ts +116 -25
  167. package/src/utils/clone.ts +6 -8
  168. package/src/utils/history.ts +190 -27
  169. package/src/utils/index.ts +4 -0
  170. package/dist/cjs/src/core/ToolExecutor.d.ts +0 -45
  171. package/dist/cjs/src/core/ToolExecutor.d.ts.map +0 -1
  172. package/dist/cjs/src/core/ToolExecutor.js +0 -84
  173. package/dist/cjs/src/core/ToolExecutor.js.map +0 -1
  174. package/dist/src/core/ToolExecutor.d.ts +0 -45
  175. package/dist/src/core/ToolExecutor.d.ts.map +0 -1
  176. package/dist/src/core/ToolExecutor.js +0 -80
  177. package/dist/src/core/ToolExecutor.js.map +0 -1
  178. package/docs/core/tools/tool-execution.md +0 -815
  179. package/src/core/ToolExecutor.ts +0 -126
@@ -74,10 +74,78 @@ Adds a domain glossary term. Returns `this` for chaining.
74
74
 
75
75
  Adds a behavioral guideline. Returns `this` for chaining.
76
76
 
77
+ ##### `addTool(definition: Tool<TContext, TData, TResult>): this`
78
+
79
+ Creates and adds a tool to agent scope using the unified Tool interface. Returns `this` for chaining.
80
+
81
+ ```typescript
82
+ // Simple return value approach
83
+ agent.addTool({
84
+ id: "weather_check",
85
+ description: "Get current weather",
86
+ parameters: {
87
+ type: "object",
88
+ properties: {
89
+ location: { type: "string", description: "City name" }
90
+ },
91
+ required: ["location"]
92
+ },
93
+ handler: async ({ context, data }, args) => {
94
+ const weather = await weatherAPI.get(args.location);
95
+ return `Weather in ${args.location}: ${weather.condition}`;
96
+ }
97
+ });
98
+
99
+ // Advanced ToolResult pattern
100
+ agent.addTool({
101
+ id: "user_lookup",
102
+ description: "Look up user information",
103
+ handler: async ({ context, data }, args) => {
104
+ const user = await userAPI.find(args.userId);
105
+ return {
106
+ data: `Found user: ${user.name}`,
107
+ success: true,
108
+ contextUpdate: { currentUser: user },
109
+ dataUpdate: { userName: user.name }
110
+ };
111
+ }
112
+ });
113
+ ```
114
+
115
+ ##### `tool: ToolManager<TContext, TData>`
116
+
117
+ Access to the ToolManager instance for advanced tool operations.
118
+
119
+ ```typescript
120
+ // Register tools for ID-based reference
121
+ agent.tool.register({
122
+ id: "reusable_search",
123
+ description: "Search across data sources",
124
+ handler: async ({ context, data }, args) => "Search results"
125
+ });
126
+
127
+ // Create tools without adding to scope
128
+ const customTool = agent.tool.create({
129
+ id: "standalone_tool",
130
+ handler: async () => "Custom result"
131
+ });
132
+
133
+ // Use pattern helpers
134
+ const enrichmentTool = agent.tool.createDataEnrichment({
135
+ id: "enrich_profile",
136
+ fields: ['name', 'email'],
137
+ enricher: async (context, data) => ({
138
+ displayName: `${data.name} <${data.email}>`
139
+ })
140
+ });
141
+ ```
142
+
77
143
  ##### `respond(input: RespondInput<TContext>): Promise<RespondOutput>`
78
144
 
79
145
  Generates an AI response with session step management, tool execution, data extraction, and intelligent routing.
80
146
 
147
+ **Note:** This method now delegates to the internal `ResponseModal` class for improved architecture and maintainability.
148
+
81
149
  **Enhanced Response Pipeline:**
82
150
 
83
151
  1. **Tool Execution** - Execute tools if current step has `tool` (enriches context before AI response)
@@ -454,6 +522,8 @@ See also: [Custom Database Integration Example](../examples/custom-database-pers
454
522
 
455
523
  Generates an AI response as a real-time stream for better user experience. Provides the same structured output as `respond()` but delivers it incrementally.
456
524
 
525
+ **Note:** This method now delegates to the internal `ResponseModal` class for improved architecture and maintainability.
526
+
457
527
  ```typescript
458
528
  interface StreamChunk {
459
529
  /** The incremental text delta */
@@ -515,6 +585,68 @@ for await (const chunk of agent.respondStream({ history, session })) {
515
585
  }
516
586
  ```
517
587
 
588
+ ##### `stream(message?: string, options?: StreamOptions<TContext>): AsyncGenerator<AgentResponseStreamChunk<TData>>`
589
+
590
+ **NEW:** Modern streaming API that provides a simple interface similar to `chat()` but returns a stream. This is the recommended way to implement streaming responses.
591
+
592
+ ```typescript
593
+ interface StreamOptions<TContext = unknown> {
594
+ contextOverride?: Partial<TContext>;
595
+ signal?: AbortSignal;
596
+ history?: History; // Optional: override session history
597
+ }
598
+ ```
599
+
600
+ **Key Features:**
601
+
602
+ - 🎯 **Simple Interface**: Just `agent.stream("message")` - no complex parameters
603
+ - 🔄 **Automatic Session Management**: Handles conversation history automatically
604
+ - 🌊 **Real-time Streaming**: Same performance as `respondStream()` but easier to use
605
+ - 🛑 **Cancellable**: Supports AbortSignal for cancellation
606
+
607
+ **Example:**
608
+
609
+ ```typescript
610
+ // Simple streaming - automatically manages session history
611
+ for await (const chunk of agent.stream("Hello, how are you?")) {
612
+ if (chunk.delta) {
613
+ process.stdout.write(chunk.delta);
614
+ }
615
+
616
+ if (chunk.done) {
617
+ console.log("\n✅ Stream complete!");
618
+ // Session history is automatically updated
619
+ }
620
+ }
621
+
622
+ // With cancellation
623
+ const controller = new AbortController();
624
+ setTimeout(() => controller.abort(), 5000); // Cancel after 5s
625
+
626
+ for await (const chunk of agent.stream("Tell me a long story", {
627
+ signal: controller.signal
628
+ })) {
629
+ process.stdout.write(chunk.delta);
630
+ }
631
+ ```
632
+
633
+ **Migration from `respondStream()`:**
634
+
635
+ ```typescript
636
+ // Old way (still supported)
637
+ for await (const chunk of agent.respondStream({
638
+ history: agent.session.getHistory(),
639
+ session: await agent.session.getOrCreate()
640
+ })) {
641
+ // Handle chunk
642
+ }
643
+
644
+ // New way (recommended)
645
+ for await (const chunk of agent.stream("Your message")) {
646
+ // Handle chunk - session management is automatic
647
+ }
648
+ ```
649
+
518
650
  **With Cancellation:**
519
651
 
520
652
  ```typescript
@@ -582,6 +714,100 @@ Agent's identity template (readonly).
582
714
 
583
715
  ---
584
716
 
717
+ ### `ResponseModal<TContext, TData>`
718
+
719
+ **NEW:** Internal class that handles all response generation logic for the Agent. This class centralizes response processing, provides unified streaming and non-streaming APIs, and improves maintainability.
720
+
721
+ **Note:** This class is primarily used internally by the Agent class. Most users should use the Agent's response methods (`respond`, `respondStream`, `stream`, `chat`) rather than accessing ResponseModal directly.
722
+
723
+ #### Constructor
724
+
725
+ ```typescript
726
+ new ResponseModal<TContext, TData>(
727
+ agent: Agent<TContext, TData>,
728
+ options?: ResponseModalOptions
729
+ )
730
+
731
+ interface ResponseModalOptions {
732
+ /** Maximum number of tool loops allowed during response generation */
733
+ maxToolLoops?: number;
734
+ /** Enable automatic session saving after response generation */
735
+ enableAutoSave?: boolean;
736
+ /** Enable debug mode for detailed logging */
737
+ debugMode?: boolean;
738
+ }
739
+ ```
740
+
741
+ #### Methods
742
+
743
+ ##### `respond(params: RespondParams<TContext, TData>): Promise<AgentResponse<TData>>`
744
+
745
+ Generates a non-streaming response using unified logic. This method consolidates all response generation logic including routing, tool execution, and data collection.
746
+
747
+ ##### `respondStream(params: RespondParams<TContext, TData>): AsyncGenerator<AgentResponseStreamChunk<TData>>`
748
+
749
+ Generates a streaming response using unified logic. Provides the same functionality as `respond()` but delivers results incrementally.
750
+
751
+ ##### `stream(message?: string, options?: StreamOptions<TContext>): AsyncGenerator<AgentResponseStreamChunk<TData>>`
752
+
753
+ Modern streaming API with automatic session management. This is the recommended way to implement streaming responses.
754
+
755
+ ```typescript
756
+ // Simple usage
757
+ for await (const chunk of responseModal.stream("Hello")) {
758
+ console.log(chunk.delta);
759
+ }
760
+
761
+ // With options
762
+ for await (const chunk of responseModal.stream("Hello", {
763
+ contextOverride: { userId: "123" },
764
+ signal: abortController.signal
765
+ })) {
766
+ console.log(chunk.delta);
767
+ }
768
+ ```
769
+
770
+ ##### `generate(message?: string, options?: GenerateOptions<TContext>): Promise<AgentResponse<TData>>`
771
+
772
+ Modern non-streaming API equivalent to `chat()` but more explicit. Provides automatic session management for non-streaming responses.
773
+
774
+ ```typescript
775
+ // Simple usage
776
+ const response = await responseModal.generate("Hello");
777
+ console.log(response.message);
778
+
779
+ // With options
780
+ const response = await responseModal.generate("Hello", {
781
+ contextOverride: { userId: "123" }
782
+ });
783
+ ```
784
+
785
+ #### Error Handling
786
+
787
+ ResponseModal includes comprehensive error handling with the `ResponseGenerationError` class:
788
+
789
+ ```typescript
790
+ try {
791
+ const response = await responseModal.respond(params);
792
+ } catch (error) {
793
+ if (ResponseGenerationError.isResponseGenerationError(error)) {
794
+ console.log("Response generation failed:", error.message);
795
+ console.log("Phase:", error.details?.phase);
796
+ console.log("Original error:", error.details?.originalError);
797
+ }
798
+ }
799
+ ```
800
+
801
+ #### Architecture Benefits
802
+
803
+ - **Separation of Concerns**: Agent focuses on configuration and orchestration, ResponseModal handles response generation
804
+ - **Unified Logic**: Both streaming and non-streaming responses use the same underlying logic
805
+ - **Modern APIs**: Provides simple `stream()` and `generate()` methods alongside legacy compatibility
806
+ - **Error Handling**: Comprehensive error handling with detailed context
807
+ - **Performance**: Optimized response pipeline with minimal duplication
808
+
809
+ ---
810
+
585
811
  ### `Route`
586
812
 
587
813
  Represents a conversation flow with steps and transitions.
@@ -797,7 +1023,7 @@ Represents a step within a conversation route.
797
1023
 
798
1024
  #### Methods
799
1025
 
800
- ##### `nextStep(spec: StepOptions): StepResult`
1026
+ ##### `nextStep(spec: StepOptions): Step`
801
1027
 
802
1028
  Creates a transition from this step and returns a chainable result.
803
1029
 
@@ -822,10 +1048,14 @@ interface StepOptions<TData = unknown> {
822
1048
  condition?: string;
823
1049
  }
824
1050
 
825
- interface StepResult<TData = unknown> {
1051
+ interface Step<TContext = unknown, TData = unknown> {
826
1052
  id: string; // Step identifier
827
1053
  routeId: string; // Route identifier
828
- nextStep: (spec: StepOptions<TData>) => StepResult<TData>;
1054
+ nextStep: (spec: StepOptions<TContext, TData>) => Step<TContext, TData>;
1055
+ description?: string; // Step description
1056
+ collect?: (keyof TData)[]; // Fields to collect in this step
1057
+ skipIf?: (data: Partial<TData>) => boolean; // Skip condition function
1058
+ requires?: (keyof TData)[]; // Required data prerequisites
829
1059
  }
830
1060
  ```
831
1061
 
@@ -833,7 +1063,7 @@ interface StepResult<TData = unknown> {
833
1063
 
834
1064
  - `spec`: The transition specification (see `StepOptions` above). Can include an optional `condition` property for AI-evaluated step selection guidance.
835
1065
 
836
- **Returns:** A `StepResult` that includes the target step's reference (`id`, `routeId`) and a `nextStep` method for chaining additional transitions.
1066
+ **Returns:** A `Step` that includes the target step's reference (`id`, `routeId`) and a `nextStep` method for chaining additional transitions.
837
1067
 
838
1068
  **Example:**
839
1069
 
@@ -950,14 +1180,7 @@ if (step.hasRequires(session.data)) {
950
1180
  }
951
1181
  ```
952
1182
 
953
- ##### `asStepResult(): StepResult<TContext, TData>`
954
1183
 
955
- Creates a transition result for this step that supports chaining.
956
-
957
- ```typescript
958
- const result = step.asStepResult();
959
- // Returns StepResult with nextStep method for chaining
960
- ```
961
1184
 
962
1185
  ##### `configure(config): this`
963
1186
 
@@ -1406,39 +1629,6 @@ Builds a fallback prompt when no routes are configured.
1406
1629
 
1407
1630
  ---
1408
1631
 
1409
- ### `ToolExecutor<TContext, TData>`
1410
-
1411
- Executes tools with context and security enforcement.
1412
-
1413
- #### Constructor
1414
-
1415
- ```typescript
1416
- new ToolExecutor<TContext, TData>();
1417
- ```
1418
-
1419
- #### Methods
1420
-
1421
- ##### `executeTool(params): Promise<ToolExecutionResult>`
1422
-
1423
- Executes a single tool with domain security enforcement.
1424
-
1425
- **Parameters:**
1426
-
1427
- - `tool`: Tool reference to execute
1428
- - `context`: Agent context
1429
- - `updateContext`: Function to update context
1430
- - `history`: Conversation history
1431
- - `data`: Collected session data
1432
- - `allowedDomains`: Array of allowed domain names
1433
-
1434
- **Returns:** Tool execution result with success status and data
1435
-
1436
- ##### `executeTools(params): Promise<ToolExecutionResult[]>`
1437
-
1438
- Executes multiple tools in sequence, stopping on first failure.
1439
-
1440
- ---
1441
-
1442
1632
  ### `Events`
1443
1633
 
1444
1634
  Utility functions for creating and adapting conversation events.
@@ -2856,4 +3046,4 @@ agent.createGuideline({
2856
3046
 
2857
3047
  ---
2858
3048
 
2859
- **Made with ❤️ for the community**
3049
+ **Made with ❤️ for the community**
@@ -6,12 +6,13 @@ Complete API documentation for `@falai/agent`. This framework provides a strongl
6
6
 
7
7
  - [Core Classes](#core-classes)
8
8
  - [Agent](#agent)
9
+ - [ResponseModal](#responsemodal)
9
10
  - [Route](#route)
10
11
  - [Step](#step)
11
12
  - [RoutingEngine](#routingengine)
12
13
  - [ResponseEngine](#responseengine)
13
14
  - [PromptComposer](#promptcomposer)
14
- - [ToolExecutor](#toolexecutor)
15
+
15
16
  - [AI Providers](#ai-providers)
16
17
  - [Persistence Adapters](#persistence-adapters)
17
18
  - [Types & Interfaces](#types--interfaces)
@@ -117,14 +118,76 @@ respondStream(params: {
117
118
  }>
118
119
  ```
119
120
 
120
- Generates a streaming response with real-time updates.
121
+ Generates a streaming response with real-time updates. **Note:** Now delegates to internal ResponseModal class.
122
+
123
+ ```typescript
124
+ stream(message?: string, options?: StreamOptions<TContext>): AsyncGenerator<AgentResponseStreamChunk<TData>>
125
+ ```
126
+
127
+ **NEW:** Modern streaming API with automatic session management. Recommended for new implementations.
128
+
129
+ ```typescript
130
+ // Simple streaming
131
+ for await (const chunk of agent.stream("Hello")) {
132
+ console.log(chunk.delta);
133
+ }
134
+ ```
121
135
 
122
136
  ##### Tool Management
123
137
 
124
138
  ```typescript
125
- createTool(tool: Tool<TContext, unknown[], unknown, unknown>): this
126
- registerTools(tools: Tool<TContext, unknown[], unknown, unknown>[]): this
127
- getTools(): Tool<TContext, unknown[], unknown, unknown>[]
139
+ addTool(definition: Tool<TContext, TData, TResult>): this
140
+ tool: ToolManager<TContext, TData> // Access to ToolManager instance
141
+ ```
142
+
143
+ **Comprehensive Tool Examples:**
144
+
145
+ ```typescript
146
+ // 1. Simple return value (most common)
147
+ agent.addTool({
148
+ id: "calculate_tip",
149
+ description: "Calculate tip amount",
150
+ handler: async ({ context, data }, args) => {
151
+ const tip = args.amount * args.percentage;
152
+ return `Tip: $${tip.toFixed(2)}`; // Simple string return
153
+ }
154
+ });
155
+
156
+ // 2. Complex ToolResult pattern
157
+ agent.addTool({
158
+ id: "process_order",
159
+ description: "Process customer order",
160
+ handler: async ({ context, data }, args) => {
161
+ const order = await orderService.process(args.items);
162
+ return {
163
+ data: `Order ${order.id} processed successfully`,
164
+ success: true,
165
+ contextUpdate: { lastOrderId: order.id },
166
+ dataUpdate: { orderStatus: 'processed' }
167
+ }; // Detailed ToolResult object
168
+ }
169
+ });
170
+
171
+ // 3. Registry for reuse
172
+ agent.tool.register({
173
+ id: "send_notification",
174
+ description: "Send notification to user",
175
+ handler: async ({ context }, args) => {
176
+ await notificationService.send(context.userId, args.message);
177
+ return "Notification sent"; // Simple return
178
+ }
179
+ });
180
+
181
+ // 4. Pattern helper
182
+ const validationTool = agent.tool.createValidation({
183
+ id: "validate_email",
184
+ fields: ['email'],
185
+ validator: async (context, data) => ({
186
+ valid: /\S+@\S+\.\S+/.test(data.email),
187
+ errors: []
188
+ })
189
+ });
190
+ agent.tool.register(validationTool);
128
191
  ```
129
192
 
130
193
  ##### Domain Knowledge
@@ -168,6 +231,57 @@ hasPersistence(): boolean
168
231
 
169
232
  ---
170
233
 
234
+ ### ResponseModal
235
+
236
+ **NEW:** Internal class that centralizes all response generation logic for improved architecture and maintainability.
237
+
238
+ #### Constructor
239
+
240
+ ```typescript
241
+ new ResponseModal<TContext = unknown, TData = unknown>(
242
+ agent: Agent<TContext, TData>,
243
+ options?: ResponseModalOptions
244
+ )
245
+ ```
246
+
247
+ #### Methods
248
+
249
+ ##### Modern APIs (Recommended)
250
+
251
+ ```typescript
252
+ stream(message?: string, options?: StreamOptions<TContext>): AsyncGenerator<AgentResponseStreamChunk<TData>>
253
+ generate(message?: string, options?: GenerateOptions<TContext>): Promise<AgentResponse<TData>>
254
+ ```
255
+
256
+ Modern streaming and non-streaming APIs with automatic session management.
257
+
258
+ ##### Legacy APIs (Backward Compatible)
259
+
260
+ ```typescript
261
+ respond(params: RespondParams<TContext, TData>): Promise<AgentResponse<TData>>
262
+ respondStream(params: RespondParams<TContext, TData>): AsyncGenerator<AgentResponseStreamChunk<TData>>
263
+ ```
264
+
265
+ Legacy APIs that maintain full backward compatibility with existing code.
266
+
267
+ ##### Error Handling
268
+
269
+ ```typescript
270
+ ResponseGenerationError: Error class for response-specific errors
271
+ ```
272
+
273
+ Comprehensive error handling with detailed context and phase information.
274
+
275
+ #### Key Features
276
+
277
+ - **Unified Logic**: Both streaming and non-streaming use the same underlying logic
278
+ - **Modern APIs**: Simple `stream()` and `generate()` methods for new code
279
+ - **Backward Compatibility**: Existing `respond()` and `respondStream()` methods work unchanged
280
+ - **Error Handling**: Detailed error context with phase and original error information
281
+ - **Performance**: Optimized response pipeline with minimal code duplication
282
+
283
+ ---
284
+
171
285
  ### Route
172
286
 
173
287
  Represents a conversational journey with required fields specification and steps that collect data into the agent-level schema.
@@ -236,9 +350,7 @@ getRoutingExtrasSchema(): StructuredSchema | undefined
236
350
  ##### Tool Management
237
351
 
238
352
  ```typescript
239
- createTool(tool: Tool<TContext, unknown[], unknown, TData>): this
240
- registerTools(tools: Tool<TContext, unknown[], unknown, TData>[]): this
241
- getTools(): Tool<TContext, unknown[], unknown, TData>[]
353
+ addTool(definition: Tool<TContext, TData, TResult>): this
242
354
  ```
243
355
 
244
356
  ##### Lifecycle Hooks
@@ -282,9 +394,9 @@ configure(config: Partial<StepOptions<TContext, TData>>): this
282
394
  ##### Transitions
283
395
 
284
396
  ```typescript
285
- nextStep(spec: StepOptions<TContext, TData>): StepResult<TContext, TData>
397
+ nextStep(spec: StepOptions<TContext, TData>): Step<TContext, TData>
286
398
  branch(branches: BranchSpec<TContext, TData>[]): BranchResult<TContext, TData>
287
- endRoute(options?: Omit<StepOptions<TContext, TData>, 'step'>): StepResult<TContext, TData>
399
+ endRoute(options?: Omit<StepOptions<TContext, TData>, 'step'>): Step<TContext, TData>
288
400
  ```
289
401
 
290
402
  ##### Validation
@@ -306,7 +418,6 @@ getTransitions(): Step<TContext, TData>[]
306
418
 
307
419
  ```typescript
308
420
  getRef(): StepRef
309
- asStepResult(): StepResult<TContext, TData>
310
421
  ```
311
422
 
312
423
  ---
@@ -440,23 +551,7 @@ addDirectives(directives?: string[]): Promise<this>
440
551
  build(): Promise<string>
441
552
  ```
442
553
 
443
- ---
444
-
445
- ### ToolExecutor
446
-
447
- Handles tool execution with context updates and data collection.
448
-
449
- #### Methods
450
554
 
451
- ```typescript
452
- executeTool(params: {
453
- tool: Tool;
454
- context: unknown;
455
- updateContext: (updates: Partial<unknown>) => Promise<void>;
456
- history: Event[];
457
- data: unknown;
458
- }): Promise<ToolExecutionResult>
459
- ```
460
555
 
461
556
  ---
462
557
 
@@ -691,21 +786,33 @@ interface StepOptions<TContext = unknown, TData = unknown> {
691
786
  }
692
787
  }
693
788
 
694
- // Example: Using existing tools (new approach)
789
+ // Example: Using existing tools (unified Tool interface)
695
790
  {
696
- prepare: "validate_user_data", // Tool ID string
697
- finalize: myCustomTool, // Tool object
791
+ prepare: "validate_user_data", // Tool ID string - simple return value
792
+ finalize: "send_notification", // Tool ID string - ToolResult pattern
698
793
  }
699
794
 
700
- // Example: Inline tool definition
795
+ // Example: Inline tool definition with flexible returns
701
796
  {
702
797
  prepare: {
703
798
  id: "setup_step_context",
704
799
  description: "Prepare context for this step",
705
800
  parameters: { type: "object", properties: {} },
706
801
  handler: ({ context, data }) => {
707
- // Custom logic here
708
- return { data: "Setup complete" };
802
+ // Simple return value
803
+ return "Setup complete";
804
+ }
805
+ },
806
+ finalize: {
807
+ id: "cleanup_step_context",
808
+ description: "Clean up after step completion",
809
+ handler: ({ context, data }) => {
810
+ // Complex ToolResult pattern
811
+ return {
812
+ data: "Cleanup complete",
813
+ success: true,
814
+ contextUpdate: { lastCleanup: new Date() }
815
+ };
709
816
  }
710
817
  }
711
818
  }