@falai/agent 1.2.8 → 2.0.1
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 +40 -886
- package/dist/adapters/MemoryAdapter.js +2 -2
- package/dist/adapters/MemoryAdapter.js.map +1 -1
- package/dist/adapters/MongoAdapter.js +2 -2
- package/dist/adapters/MongoAdapter.js.map +1 -1
- package/dist/adapters/OpenSearchAdapter.d.ts.map +1 -1
- package/dist/adapters/OpenSearchAdapter.js +9 -7
- package/dist/adapters/OpenSearchAdapter.js.map +1 -1
- package/dist/adapters/PostgreSQLAdapter.d.ts +14 -0
- package/dist/adapters/PostgreSQLAdapter.d.ts.map +1 -1
- package/dist/adapters/PostgreSQLAdapter.js +25 -9
- package/dist/adapters/PostgreSQLAdapter.js.map +1 -1
- package/dist/adapters/PrismaAdapter.js +5 -5
- package/dist/adapters/PrismaAdapter.js.map +1 -1
- package/dist/adapters/RedisAdapter.js +2 -2
- package/dist/adapters/RedisAdapter.js.map +1 -1
- package/dist/adapters/SQLiteAdapter.d.ts +17 -0
- package/dist/adapters/SQLiteAdapter.d.ts.map +1 -1
- package/dist/adapters/SQLiteAdapter.js +30 -11
- package/dist/adapters/SQLiteAdapter.js.map +1 -1
- package/dist/cjs/adapters/MemoryAdapter.js +2 -2
- package/dist/cjs/adapters/MemoryAdapter.js.map +1 -1
- package/dist/cjs/adapters/MongoAdapter.js +2 -2
- package/dist/cjs/adapters/MongoAdapter.js.map +1 -1
- package/dist/cjs/adapters/OpenSearchAdapter.d.ts.map +1 -1
- package/dist/cjs/adapters/OpenSearchAdapter.js +9 -7
- package/dist/cjs/adapters/OpenSearchAdapter.js.map +1 -1
- package/dist/cjs/adapters/PostgreSQLAdapter.d.ts +14 -0
- package/dist/cjs/adapters/PostgreSQLAdapter.d.ts.map +1 -1
- package/dist/cjs/adapters/PostgreSQLAdapter.js +25 -9
- package/dist/cjs/adapters/PostgreSQLAdapter.js.map +1 -1
- package/dist/cjs/adapters/PrismaAdapter.js +5 -5
- package/dist/cjs/adapters/PrismaAdapter.js.map +1 -1
- package/dist/cjs/adapters/RedisAdapter.js +2 -2
- package/dist/cjs/adapters/RedisAdapter.js.map +1 -1
- package/dist/cjs/adapters/SQLiteAdapter.d.ts +17 -0
- package/dist/cjs/adapters/SQLiteAdapter.d.ts.map +1 -1
- package/dist/cjs/adapters/SQLiteAdapter.js +30 -11
- package/dist/cjs/adapters/SQLiteAdapter.js.map +1 -1
- package/dist/cjs/constants/index.d.ts +0 -9
- package/dist/cjs/constants/index.d.ts.map +1 -1
- package/dist/cjs/constants/index.js +2 -11
- package/dist/cjs/constants/index.js.map +1 -1
- package/dist/cjs/core/Agent.d.ts +119 -153
- package/dist/cjs/core/Agent.d.ts.map +1 -1
- package/dist/cjs/core/Agent.js +471 -324
- package/dist/cjs/core/Agent.js.map +1 -1
- package/dist/cjs/core/AutoChainExecutor.d.ts +107 -0
- package/dist/cjs/core/AutoChainExecutor.d.ts.map +1 -0
- package/dist/cjs/core/AutoChainExecutor.js +297 -0
- package/dist/cjs/core/AutoChainExecutor.js.map +1 -0
- package/dist/cjs/core/BranchEvaluator.d.ts +54 -0
- package/dist/cjs/core/BranchEvaluator.d.ts.map +1 -0
- package/dist/cjs/core/BranchEvaluator.js +130 -0
- package/dist/cjs/core/BranchEvaluator.js.map +1 -0
- package/dist/cjs/core/DirectiveBus.d.ts +88 -0
- package/dist/cjs/core/DirectiveBus.d.ts.map +1 -0
- package/dist/cjs/core/DirectiveBus.js +196 -0
- package/dist/cjs/core/DirectiveBus.js.map +1 -0
- package/dist/cjs/core/DirectiveChainTracker.d.ts +49 -0
- package/dist/cjs/core/DirectiveChainTracker.d.ts.map +1 -0
- package/dist/cjs/core/DirectiveChainTracker.js +121 -0
- package/dist/cjs/core/DirectiveChainTracker.js.map +1 -0
- package/dist/cjs/core/Flow.d.ts +186 -0
- package/dist/cjs/core/Flow.d.ts.map +1 -0
- package/dist/cjs/core/Flow.js +550 -0
- package/dist/cjs/core/Flow.js.map +1 -0
- package/dist/cjs/core/FlowRouter.d.ts +182 -0
- package/dist/cjs/core/FlowRouter.d.ts.map +1 -0
- package/dist/cjs/core/{RoutingEngine.js → FlowRouter.js} +323 -306
- package/dist/cjs/core/FlowRouter.js.map +1 -0
- package/dist/cjs/core/PersistenceManager.d.ts +2 -2
- package/dist/cjs/core/PersistenceManager.d.ts.map +1 -1
- package/dist/cjs/core/PersistenceManager.js +7 -7
- package/dist/cjs/core/PersistenceManager.js.map +1 -1
- package/dist/cjs/core/PromptComposer.d.ts +21 -8
- package/dist/cjs/core/PromptComposer.d.ts.map +1 -1
- package/dist/cjs/core/PromptComposer.js +182 -105
- package/dist/cjs/core/PromptComposer.js.map +1 -1
- package/dist/cjs/core/PromptSectionCache.d.ts +1 -1
- package/dist/cjs/core/PromptSectionCache.js +1 -1
- package/dist/cjs/core/ResponseEngine.d.ts +18 -8
- package/dist/cjs/core/ResponseEngine.d.ts.map +1 -1
- package/dist/cjs/core/ResponseEngine.js +38 -36
- package/dist/cjs/core/ResponseEngine.js.map +1 -1
- package/dist/cjs/core/ResponseModal.d.ts +73 -56
- package/dist/cjs/core/ResponseModal.d.ts.map +1 -1
- package/dist/cjs/core/ResponseModal.js +1191 -1014
- package/dist/cjs/core/ResponseModal.js.map +1 -1
- package/dist/cjs/core/ResponsePipeline.d.ts +124 -26
- package/dist/cjs/core/ResponsePipeline.d.ts.map +1 -1
- package/dist/cjs/core/ResponsePipeline.js +509 -136
- package/dist/cjs/core/ResponsePipeline.js.map +1 -1
- package/dist/cjs/core/SignalEvaluator.d.ts +86 -0
- package/dist/cjs/core/SignalEvaluator.d.ts.map +1 -0
- package/dist/cjs/core/SignalEvaluator.js +333 -0
- package/dist/cjs/core/SignalEvaluator.js.map +1 -0
- package/dist/cjs/core/SignalProcessor.d.ts +152 -0
- package/dist/cjs/core/SignalProcessor.d.ts.map +1 -0
- package/dist/cjs/core/SignalProcessor.js +562 -0
- package/dist/cjs/core/SignalProcessor.js.map +1 -0
- package/dist/cjs/core/Step.d.ts +43 -32
- package/dist/cjs/core/Step.d.ts.map +1 -1
- package/dist/cjs/core/Step.js +221 -126
- package/dist/cjs/core/Step.js.map +1 -1
- package/dist/cjs/core/StreamingToolExecutor.d.ts +2 -2
- package/dist/cjs/core/StreamingToolExecutor.d.ts.map +1 -1
- package/dist/cjs/core/StreamingToolExecutor.js.map +1 -1
- package/dist/cjs/core/ToolManager.d.ts +44 -13
- package/dist/cjs/core/ToolManager.d.ts.map +1 -1
- package/dist/cjs/core/ToolManager.js +174 -91
- package/dist/cjs/core/ToolManager.js.map +1 -1
- package/dist/cjs/core/createAgent.d.ts +35 -0
- package/dist/cjs/core/createAgent.d.ts.map +1 -0
- package/dist/cjs/core/createAgent.js +39 -0
- package/dist/cjs/core/createAgent.js.map +1 -0
- package/dist/cjs/core/flow-namespace.d.ts +49 -0
- package/dist/cjs/core/flow-namespace.d.ts.map +1 -0
- package/dist/cjs/core/flow-namespace.js +171 -0
- package/dist/cjs/core/flow-namespace.js.map +1 -0
- package/dist/cjs/index.d.ts +11 -14
- package/dist/cjs/index.d.ts.map +1 -1
- package/dist/cjs/index.js +18 -22
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/providers/AnthropicProvider.d.ts +1 -1
- package/dist/cjs/providers/AnthropicProvider.js +1 -1
- package/dist/cjs/providers/GeminiProvider.d.ts +1 -1
- package/dist/cjs/providers/GeminiProvider.d.ts.map +1 -1
- package/dist/cjs/providers/GeminiProvider.js +1 -1
- package/dist/cjs/providers/GeminiProvider.js.map +1 -1
- package/dist/cjs/providers/OpenAIProvider.d.ts +1 -1
- package/dist/cjs/providers/OpenAIProvider.d.ts.map +1 -1
- package/dist/cjs/providers/OpenAIProvider.js +1 -1
- package/dist/cjs/providers/OpenAIProvider.js.map +1 -1
- package/dist/cjs/types/agent.d.ts +183 -54
- package/dist/cjs/types/agent.d.ts.map +1 -1
- package/dist/cjs/types/agent.js +0 -6
- package/dist/cjs/types/agent.js.map +1 -1
- package/dist/cjs/types/ai.d.ts +3 -3
- package/dist/cjs/types/ai.d.ts.map +1 -1
- package/dist/cjs/types/errors.d.ts +15 -0
- package/dist/cjs/types/errors.d.ts.map +1 -0
- package/dist/cjs/types/errors.js +22 -0
- package/dist/cjs/types/errors.js.map +1 -0
- package/dist/cjs/types/flow.d.ts +513 -0
- package/dist/cjs/types/flow.d.ts.map +1 -0
- package/dist/cjs/types/{route.js → flow.js} +2 -2
- package/dist/cjs/types/flow.js.map +1 -0
- package/dist/cjs/types/index.d.ts +7 -6
- package/dist/cjs/types/index.d.ts.map +1 -1
- package/dist/cjs/types/index.js +6 -2
- package/dist/cjs/types/index.js.map +1 -1
- package/dist/cjs/types/persistence.d.ts +11 -7
- package/dist/cjs/types/persistence.d.ts.map +1 -1
- package/dist/cjs/types/routing.d.ts +1 -1
- package/dist/cjs/types/routing.d.ts.map +1 -1
- package/dist/cjs/types/session.d.ts +24 -23
- package/dist/cjs/types/session.d.ts.map +1 -1
- package/dist/cjs/types/signals.d.ts +248 -0
- package/dist/cjs/types/signals.d.ts.map +1 -0
- package/dist/cjs/types/signals.js +11 -0
- package/dist/cjs/types/signals.js.map +1 -0
- package/dist/cjs/types/template.d.ts +2 -8
- package/dist/cjs/types/template.d.ts.map +1 -1
- package/dist/cjs/types/tool.d.ts +36 -29
- package/dist/cjs/types/tool.d.ts.map +1 -1
- package/dist/cjs/types/tool.js +1 -1
- package/dist/cjs/types/tool.js.map +1 -1
- package/dist/cjs/utils/condition.d.ts +7 -1
- package/dist/cjs/utils/condition.d.ts.map +1 -1
- package/dist/cjs/utils/condition.js.map +1 -1
- package/dist/cjs/utils/id.d.ts +13 -5
- package/dist/cjs/utils/id.d.ts.map +1 -1
- package/dist/cjs/utils/id.js +24 -10
- package/dist/cjs/utils/id.js.map +1 -1
- package/dist/cjs/utils/index.d.ts +2 -2
- package/dist/cjs/utils/index.d.ts.map +1 -1
- package/dist/cjs/utils/index.js +7 -3
- package/dist/cjs/utils/index.js.map +1 -1
- package/dist/cjs/utils/session.d.ts +44 -5
- package/dist/cjs/utils/session.d.ts.map +1 -1
- package/dist/cjs/utils/session.js +197 -38
- package/dist/cjs/utils/session.js.map +1 -1
- package/dist/constants/index.d.ts +0 -9
- package/dist/constants/index.d.ts.map +1 -1
- package/dist/constants/index.js +3 -9
- package/dist/constants/index.js.map +1 -1
- package/dist/core/Agent.d.ts +119 -153
- package/dist/core/Agent.d.ts.map +1 -1
- package/dist/core/Agent.js +472 -325
- package/dist/core/Agent.js.map +1 -1
- package/dist/core/AutoChainExecutor.d.ts +107 -0
- package/dist/core/AutoChainExecutor.d.ts.map +1 -0
- package/dist/core/AutoChainExecutor.js +293 -0
- package/dist/core/AutoChainExecutor.js.map +1 -0
- package/dist/core/BranchEvaluator.d.ts +54 -0
- package/dist/core/BranchEvaluator.d.ts.map +1 -0
- package/dist/core/BranchEvaluator.js +126 -0
- package/dist/core/BranchEvaluator.js.map +1 -0
- package/dist/core/DirectiveBus.d.ts +88 -0
- package/dist/core/DirectiveBus.d.ts.map +1 -0
- package/dist/core/DirectiveBus.js +192 -0
- package/dist/core/DirectiveBus.js.map +1 -0
- package/dist/core/DirectiveChainTracker.d.ts +49 -0
- package/dist/core/DirectiveChainTracker.d.ts.map +1 -0
- package/dist/core/DirectiveChainTracker.js +117 -0
- package/dist/core/DirectiveChainTracker.js.map +1 -0
- package/dist/core/Flow.d.ts +186 -0
- package/dist/core/Flow.d.ts.map +1 -0
- package/dist/core/Flow.js +546 -0
- package/dist/core/Flow.js.map +1 -0
- package/dist/core/FlowRouter.d.ts +182 -0
- package/dist/core/FlowRouter.d.ts.map +1 -0
- package/dist/core/{RoutingEngine.js → FlowRouter.js} +322 -305
- package/dist/core/FlowRouter.js.map +1 -0
- package/dist/core/PersistenceManager.d.ts +2 -2
- package/dist/core/PersistenceManager.d.ts.map +1 -1
- package/dist/core/PersistenceManager.js +7 -7
- package/dist/core/PersistenceManager.js.map +1 -1
- package/dist/core/PromptComposer.d.ts +21 -8
- package/dist/core/PromptComposer.d.ts.map +1 -1
- package/dist/core/PromptComposer.js +183 -106
- package/dist/core/PromptComposer.js.map +1 -1
- package/dist/core/PromptSectionCache.d.ts +1 -1
- package/dist/core/PromptSectionCache.js +1 -1
- package/dist/core/ResponseEngine.d.ts +18 -8
- package/dist/core/ResponseEngine.d.ts.map +1 -1
- package/dist/core/ResponseEngine.js +38 -36
- package/dist/core/ResponseEngine.js.map +1 -1
- package/dist/core/ResponseModal.d.ts +73 -56
- package/dist/core/ResponseModal.d.ts.map +1 -1
- package/dist/core/ResponseModal.js +1193 -1016
- package/dist/core/ResponseModal.js.map +1 -1
- package/dist/core/ResponsePipeline.d.ts +124 -26
- package/dist/core/ResponsePipeline.d.ts.map +1 -1
- package/dist/core/ResponsePipeline.js +509 -137
- package/dist/core/ResponsePipeline.js.map +1 -1
- package/dist/core/SignalEvaluator.d.ts +86 -0
- package/dist/core/SignalEvaluator.d.ts.map +1 -0
- package/dist/core/SignalEvaluator.js +326 -0
- package/dist/core/SignalEvaluator.js.map +1 -0
- package/dist/core/SignalProcessor.d.ts +152 -0
- package/dist/core/SignalProcessor.d.ts.map +1 -0
- package/dist/core/SignalProcessor.js +555 -0
- package/dist/core/SignalProcessor.js.map +1 -0
- package/dist/core/Step.d.ts +43 -32
- package/dist/core/Step.d.ts.map +1 -1
- package/dist/core/Step.js +220 -126
- package/dist/core/Step.js.map +1 -1
- package/dist/core/StreamingToolExecutor.d.ts +2 -2
- package/dist/core/StreamingToolExecutor.d.ts.map +1 -1
- package/dist/core/StreamingToolExecutor.js.map +1 -1
- package/dist/core/ToolManager.d.ts +44 -13
- package/dist/core/ToolManager.d.ts.map +1 -1
- package/dist/core/ToolManager.js +174 -91
- package/dist/core/ToolManager.js.map +1 -1
- package/dist/core/createAgent.d.ts +35 -0
- package/dist/core/createAgent.d.ts.map +1 -0
- package/dist/core/createAgent.js +36 -0
- package/dist/core/createAgent.js.map +1 -0
- package/dist/core/flow-namespace.d.ts +49 -0
- package/dist/core/flow-namespace.d.ts.map +1 -0
- package/dist/core/flow-namespace.js +168 -0
- package/dist/core/flow-namespace.js.map +1 -0
- package/dist/index.d.ts +11 -14
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +9 -12
- package/dist/index.js.map +1 -1
- package/dist/providers/AnthropicProvider.d.ts +1 -1
- package/dist/providers/AnthropicProvider.js +1 -1
- package/dist/providers/GeminiProvider.d.ts +1 -1
- package/dist/providers/GeminiProvider.d.ts.map +1 -1
- package/dist/providers/GeminiProvider.js +1 -1
- package/dist/providers/GeminiProvider.js.map +1 -1
- package/dist/providers/OpenAIProvider.d.ts +1 -1
- package/dist/providers/OpenAIProvider.d.ts.map +1 -1
- package/dist/providers/OpenAIProvider.js +1 -1
- package/dist/providers/OpenAIProvider.js.map +1 -1
- package/dist/types/agent.d.ts +183 -54
- package/dist/types/agent.d.ts.map +1 -1
- package/dist/types/agent.js +0 -6
- package/dist/types/agent.js.map +1 -1
- package/dist/types/ai.d.ts +3 -3
- package/dist/types/ai.d.ts.map +1 -1
- package/dist/types/errors.d.ts +15 -0
- package/dist/types/errors.d.ts.map +1 -0
- package/dist/types/errors.js +18 -0
- package/dist/types/errors.js.map +1 -0
- package/dist/types/flow.d.ts +513 -0
- package/dist/types/flow.d.ts.map +1 -0
- package/dist/types/flow.js +5 -0
- package/dist/types/flow.js.map +1 -0
- package/dist/types/index.d.ts +7 -6
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js +4 -1
- package/dist/types/index.js.map +1 -1
- package/dist/types/persistence.d.ts +11 -7
- package/dist/types/persistence.d.ts.map +1 -1
- package/dist/types/routing.d.ts +1 -1
- package/dist/types/routing.d.ts.map +1 -1
- package/dist/types/session.d.ts +24 -23
- package/dist/types/session.d.ts.map +1 -1
- package/dist/types/signals.d.ts +248 -0
- package/dist/types/signals.d.ts.map +1 -0
- package/dist/types/signals.js +10 -0
- package/dist/types/signals.js.map +1 -0
- package/dist/types/template.d.ts +2 -8
- package/dist/types/template.d.ts.map +1 -1
- package/dist/types/tool.d.ts +36 -29
- package/dist/types/tool.d.ts.map +1 -1
- package/dist/types/tool.js +1 -1
- package/dist/types/tool.js.map +1 -1
- package/dist/utils/condition.d.ts +7 -1
- package/dist/utils/condition.d.ts.map +1 -1
- package/dist/utils/condition.js.map +1 -1
- package/dist/utils/id.d.ts +13 -5
- package/dist/utils/id.d.ts.map +1 -1
- package/dist/utils/id.js +22 -9
- package/dist/utils/id.js.map +1 -1
- package/dist/utils/index.d.ts +2 -2
- package/dist/utils/index.d.ts.map +1 -1
- package/dist/utils/index.js +2 -2
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/session.d.ts +44 -5
- package/dist/utils/session.d.ts.map +1 -1
- package/dist/utils/session.js +193 -37
- package/dist/utils/session.js.map +1 -1
- package/docs/README.md +22 -200
- package/docs/concepts/architecture.md +281 -0
- package/docs/concepts/directives.md +400 -0
- package/docs/concepts/pipeline.md +399 -0
- package/docs/guides/branching.md +263 -0
- package/docs/guides/compaction.md +163 -0
- package/docs/guides/conditions.md +167 -0
- package/docs/guides/error-handling.md +176 -0
- package/docs/guides/flow-control.md +409 -0
- package/docs/guides/instructions.md +210 -0
- package/docs/guides/persistence.md +182 -0
- package/docs/guides/streaming.md +137 -0
- package/docs/migration/README.md +14 -0
- package/docs/migration/route-to-flow.md +561 -0
- package/docs/migration/v1-to-v2.md +909 -0
- package/docs/reference/adapters.md +481 -0
- package/docs/reference/branches.md +241 -0
- package/docs/reference/create-agent.md +186 -0
- package/docs/reference/directive.md +243 -0
- package/docs/reference/errors.md +122 -0
- package/docs/reference/flow.md +238 -0
- package/docs/reference/instruction.md +177 -0
- package/docs/reference/pre-directive.md +131 -0
- package/docs/reference/providers.md +227 -0
- package/docs/reference/signals.md +356 -0
- package/docs/reference/step.md +339 -0
- package/docs/reference/tool.md +269 -0
- package/docs/start/01-install.md +81 -0
- package/docs/start/02-first-agent.md +196 -0
- package/docs/start/03-collect-data.md +222 -0
- package/docs/start/04-add-tools.md +276 -0
- package/docs/start/05-go-to-production.md +216 -0
- package/examples/01-quickstart.ts +20 -0
- package/examples/02-data-extraction.ts +90 -0
- package/examples/03-tools.ts +136 -0
- package/examples/04-instructions.ts +100 -0
- package/examples/05-branching.ts +140 -0
- package/examples/06-flow-control.ts +103 -0
- package/examples/07-streaming.ts +69 -0
- package/examples/08-persistence.ts +98 -0
- package/examples/09-signals.ts +144 -0
- package/examples/tsconfig.json +30 -0
- package/package.json +2 -1
- package/src/adapters/MemoryAdapter.ts +3 -3
- package/src/adapters/MongoAdapter.ts +3 -3
- package/src/adapters/OpenSearchAdapter.ts +10 -8
- package/src/adapters/PostgreSQLAdapter.ts +26 -10
- package/src/adapters/PrismaAdapter.ts +6 -6
- package/src/adapters/RedisAdapter.ts +3 -3
- package/src/adapters/SQLiteAdapter.ts +31 -12
- package/src/constants/index.ts +2 -10
- package/src/core/Agent.ts +585 -374
- package/src/core/AutoChainExecutor.ts +440 -0
- package/src/core/BranchEvaluator.ts +167 -0
- package/src/core/DirectiveBus.ts +248 -0
- package/src/core/DirectiveChainTracker.ts +144 -0
- package/src/core/Flow.ts +666 -0
- package/src/core/{RoutingEngine.ts → FlowRouter.ts} +385 -365
- package/src/core/PersistenceManager.ts +8 -8
- package/src/core/PromptComposer.ts +209 -140
- package/src/core/PromptSectionCache.ts +1 -1
- package/src/core/ResponseEngine.ts +61 -46
- package/src/core/ResponseModal.ts +1453 -1240
- package/src/core/ResponsePipeline.ts +655 -175
- package/src/core/SignalEvaluator.ts +420 -0
- package/src/core/SignalProcessor.ts +723 -0
- package/src/core/Step.ts +279 -176
- package/src/core/StreamingToolExecutor.ts +4 -4
- package/src/core/ToolManager.ts +200 -97
- package/src/core/createAgent.ts +40 -0
- package/src/core/flow-namespace.ts +219 -0
- package/src/index.ts +42 -36
- package/src/providers/AnthropicProvider.ts +2 -2
- package/src/providers/GeminiProvider.ts +2 -2
- package/src/providers/OpenAIProvider.ts +2 -2
- package/src/types/agent.ts +182 -53
- package/src/types/ai.ts +3 -3
- package/src/types/errors.ts +18 -0
- package/src/types/flow.ts +590 -0
- package/src/types/index.ts +43 -16
- package/src/types/persistence.ts +12 -8
- package/src/types/routing.ts +1 -1
- package/src/types/session.ts +26 -23
- package/src/types/signals.ts +321 -0
- package/src/types/template.ts +3 -11
- package/src/types/tool.ts +50 -42
- package/src/utils/condition.ts +13 -4
- package/src/utils/id.ts +27 -9
- package/src/utils/index.ts +6 -2
- package/src/utils/session.ts +238 -42
- package/dist/cjs/core/BatchExecutor.d.ts +0 -359
- package/dist/cjs/core/BatchExecutor.d.ts.map +0 -1
- package/dist/cjs/core/BatchExecutor.js +0 -861
- package/dist/cjs/core/BatchExecutor.js.map +0 -1
- package/dist/cjs/core/BatchPromptBuilder.d.ts +0 -89
- package/dist/cjs/core/BatchPromptBuilder.d.ts.map +0 -1
- package/dist/cjs/core/BatchPromptBuilder.js +0 -223
- package/dist/cjs/core/BatchPromptBuilder.js.map +0 -1
- package/dist/cjs/core/Route.d.ts +0 -180
- package/dist/cjs/core/Route.d.ts.map +0 -1
- package/dist/cjs/core/Route.js +0 -542
- package/dist/cjs/core/Route.js.map +0 -1
- package/dist/cjs/core/RoutingEngine.d.ts +0 -185
- package/dist/cjs/core/RoutingEngine.d.ts.map +0 -1
- package/dist/cjs/core/RoutingEngine.js.map +0 -1
- package/dist/cjs/types/route.d.ts +0 -336
- package/dist/cjs/types/route.d.ts.map +0 -1
- package/dist/cjs/types/route.js.map +0 -1
- package/dist/core/BatchExecutor.d.ts +0 -359
- package/dist/core/BatchExecutor.d.ts.map +0 -1
- package/dist/core/BatchExecutor.js +0 -856
- package/dist/core/BatchExecutor.js.map +0 -1
- package/dist/core/BatchPromptBuilder.d.ts +0 -89
- package/dist/core/BatchPromptBuilder.d.ts.map +0 -1
- package/dist/core/BatchPromptBuilder.js +0 -219
- package/dist/core/BatchPromptBuilder.js.map +0 -1
- package/dist/core/Route.d.ts +0 -180
- package/dist/core/Route.d.ts.map +0 -1
- package/dist/core/Route.js +0 -538
- package/dist/core/Route.js.map +0 -1
- package/dist/core/RoutingEngine.d.ts +0 -185
- package/dist/core/RoutingEngine.d.ts.map +0 -1
- package/dist/core/RoutingEngine.js.map +0 -1
- package/dist/types/route.d.ts +0 -336
- package/dist/types/route.d.ts.map +0 -1
- package/dist/types/route.js +0 -5
- package/dist/types/route.js.map +0 -1
- package/docs/CONTRIBUTING.md +0 -521
- package/docs/api/README.md +0 -3299
- package/docs/api/overview.md +0 -1410
- package/docs/architecture/data-extraction-flow.md +0 -360
- package/docs/architecture/multi-step-execution.md +0 -277
- package/docs/core/agent/README.md +0 -938
- package/docs/core/agent/context-management.md +0 -796
- package/docs/core/agent/rules-and-prohibitions.md +0 -113
- package/docs/core/agent/session-management.md +0 -693
- package/docs/core/ai-integration/prompt-composition.md +0 -355
- package/docs/core/ai-integration/providers.md +0 -515
- package/docs/core/ai-integration/response-processing.md +0 -433
- package/docs/core/conversation-flows/data-collection.md +0 -772
- package/docs/core/conversation-flows/route-dsl.md +0 -509
- package/docs/core/conversation-flows/routes.md +0 -249
- package/docs/core/conversation-flows/step-transitions.md +0 -731
- package/docs/core/conversation-flows/steps.md +0 -268
- package/docs/core/error-handling.md +0 -830
- package/docs/core/persistence/adapters.md +0 -255
- package/docs/core/persistence/session-storage.md +0 -656
- package/docs/core/routing/intelligent-routing.md +0 -470
- package/docs/core/tools/enhanced-tool.md +0 -186
- package/docs/core/tools/streaming-execution.md +0 -161
- package/docs/core/tools/tool-definition.md +0 -970
- package/docs/core/tools/tool-scoping.md +0 -819
- package/docs/guides/advanced-patterns/publishing.md +0 -186
- package/docs/guides/context-compaction.md +0 -96
- package/docs/guides/error-handling-patterns.md +0 -578
- package/docs/guides/getting-started/README.md +0 -795
- package/docs/guides/migration/README.md +0 -101
- package/docs/guides/migration/flexible-routing-conditions.md +0 -375
- package/docs/guides/migration/multi-step-execution.md +0 -393
- package/docs/guides/migration/response-modal-refactor.md +0 -518
- package/docs/guides/prompt-optimization.md +0 -164
- package/examples/advanced-patterns/context-compaction.ts +0 -223
- package/examples/advanced-patterns/knowledge-based-agent.ts +0 -735
- package/examples/advanced-patterns/persistent-onboarding.ts +0 -728
- package/examples/advanced-patterns/route-lifecycle-hooks.ts +0 -556
- package/examples/advanced-patterns/streaming-responses.ts +0 -656
- package/examples/ai-providers/anthropic-integration.ts +0 -388
- package/examples/ai-providers/openai-integration.ts +0 -228
- package/examples/condition-patterns/function-only-conditions.ts +0 -365
- package/examples/condition-patterns/mixed-array-conditions.ts +0 -477
- package/examples/condition-patterns/route-skipif-patterns.ts +0 -468
- package/examples/condition-patterns/step-skipif-patterns.ts +0 -0
- package/examples/condition-patterns/string-only-conditions.ts +0 -296
- package/examples/conversation-flows/completion-transitions.ts +0 -318
- package/examples/core-concepts/basic-agent.ts +0 -503
- package/examples/core-concepts/modern-streaming-api.ts +0 -309
- package/examples/core-concepts/schema-driven-extraction.ts +0 -332
- package/examples/core-concepts/session-management.ts +0 -494
- package/examples/integrations/database-integration.ts +0 -631
- package/examples/integrations/healthcare-integration.ts +0 -595
- package/examples/integrations/search-integration.ts +0 -530
- package/examples/integrations/server-session-management.ts +0 -307
- package/examples/persistence/custom-adapter.ts +0 -526
- package/examples/persistence/database-persistence.ts +0 -583
- package/examples/persistence/memory-sessions.ts +0 -495
- package/examples/persistence/prisma-schema.example.prisma +0 -74
- package/examples/persistence/redis-persistence.ts +0 -488
- package/examples/tools/basic-tools.ts +0 -765
- package/examples/tools/data-enrichment-tools.ts +0 -593
- package/examples/tools/enhanced-tool-metadata.ts +0 -268
- package/examples/tools/streaming-tool-execution.ts +0 -283
- package/src/core/BatchExecutor.ts +0 -1187
- package/src/core/BatchPromptBuilder.ts +0 -299
- package/src/core/Route.ts +0 -678
- package/src/types/route.ts +0 -392
|
@@ -1,970 +0,0 @@
|
|
|
1
|
-
# Tool Definition with Unified Interface
|
|
2
|
-
|
|
3
|
-
Tools in @falai/agent enable AI agents to execute custom logic, access external APIs, and perform actions during conversations. The unified Tool interface supports both simple return values and complex ToolResult patterns, providing maximum flexibility with minimal complexity.
|
|
4
|
-
|
|
5
|
-
## Overview
|
|
6
|
-
|
|
7
|
-
The unified Tool system provides:
|
|
8
|
-
|
|
9
|
-
- **Single Interface**: One Tool interface that handles both simple and advanced patterns
|
|
10
|
-
- **Flexible Returns**: Return simple values (`return 'result'`) or complex objects (`return { data: 'result', success: true }`)
|
|
11
|
-
- **Multiple Creation Methods**: Direct addition, registry system, pattern helpers, and manual creation
|
|
12
|
-
- **Type Safety**: Full TypeScript support with automatic type inference
|
|
13
|
-
- **Helper Methods**: Built-in context and data update utilities
|
|
14
|
-
- **Intelligent Scoping**: Hierarchical tool resolution with registry fallback
|
|
15
|
-
|
|
16
|
-
## Unified Tool Interface
|
|
17
|
-
|
|
18
|
-
All tools use the same interface regardless of complexity:
|
|
19
|
-
|
|
20
|
-
```typescript
|
|
21
|
-
interface Tool<TContext = unknown, TData = unknown, TResult = unknown> {
|
|
22
|
-
id: string;
|
|
23
|
-
name?: string;
|
|
24
|
-
description?: string;
|
|
25
|
-
parameters?: unknown;
|
|
26
|
-
handler: (
|
|
27
|
-
context: ToolContext<TContext, TData>,
|
|
28
|
-
args?: Record<string, unknown>
|
|
29
|
-
) => Promise<TResult | ToolResult<TResult, TContext, TData>> | TResult | ToolResult<TResult, TContext, TData>;
|
|
30
|
-
}
|
|
31
|
-
```
|
|
32
|
-
|
|
33
|
-
The handler can return either:
|
|
34
|
-
- **Simple values**: `return 'result'` or `return { status: 'complete' }`
|
|
35
|
-
- **ToolResult objects**: `return { data: 'result', success: true, contextUpdate: {...} }`
|
|
36
|
-
|
|
37
|
-
```typescript
|
|
38
|
-
import { Agent, GeminiProvider } from "@falai/agent";
|
|
39
|
-
|
|
40
|
-
const agent = new Agent({
|
|
41
|
-
name: "Assistant",
|
|
42
|
-
provider: new GeminiProvider({
|
|
43
|
-
apiKey: process.env.GEMINI_API_KEY!,
|
|
44
|
-
}),
|
|
45
|
-
});
|
|
46
|
-
|
|
47
|
-
// Access ToolManager for advanced operations
|
|
48
|
-
const toolManager = agent.tool;
|
|
49
|
-
```
|
|
50
|
-
|
|
51
|
-
## Tool Creation Methods
|
|
52
|
-
|
|
53
|
-
The unified Tool interface supports multiple creation approaches, each optimized for different use cases:
|
|
54
|
-
|
|
55
|
-
### 1. Simple Return Values (Recommended for Most Cases)
|
|
56
|
-
|
|
57
|
-
The most straightforward approach - just return the result directly:
|
|
58
|
-
|
|
59
|
-
```typescript
|
|
60
|
-
import { Agent, GeminiProvider } from "@falai/agent";
|
|
61
|
-
|
|
62
|
-
interface UserContext {
|
|
63
|
-
userId: string;
|
|
64
|
-
preferences: Record<string, any>;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
interface WeatherData {
|
|
68
|
-
location?: string;
|
|
69
|
-
temperature?: number;
|
|
70
|
-
condition?: string;
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
const agent = new Agent<UserContext, WeatherData>({
|
|
74
|
-
name: "Weather Assistant",
|
|
75
|
-
provider: new GeminiProvider({
|
|
76
|
-
apiKey: process.env.GEMINI_API_KEY!,
|
|
77
|
-
}),
|
|
78
|
-
});
|
|
79
|
-
|
|
80
|
-
// Simple return value - most common pattern
|
|
81
|
-
agent.addTool({
|
|
82
|
-
id: "get_weather",
|
|
83
|
-
name: "Weather Forecast",
|
|
84
|
-
description: "Get current weather and forecast for a location",
|
|
85
|
-
parameters: {
|
|
86
|
-
type: "object",
|
|
87
|
-
properties: {
|
|
88
|
-
location: { type: "string", description: "City or location name" },
|
|
89
|
-
date: { type: "string", description: "Date for forecast (YYYY-MM-DD)" },
|
|
90
|
-
},
|
|
91
|
-
required: ["location"],
|
|
92
|
-
},
|
|
93
|
-
handler: async ({ context, data, updateContext, updateData }, args) => {
|
|
94
|
-
const weather = await weatherAPI.getForecast(args.location, args.date);
|
|
95
|
-
|
|
96
|
-
// Use helper methods for updates
|
|
97
|
-
await updateContext({ lastWeatherCheck: new Date().toISOString() });
|
|
98
|
-
await updateData({
|
|
99
|
-
location: args.location,
|
|
100
|
-
temperature: weather.temperature,
|
|
101
|
-
condition: weather.condition,
|
|
102
|
-
});
|
|
103
|
-
|
|
104
|
-
// Return simple string - unified interface handles the rest
|
|
105
|
-
return `The weather in ${args.location} on ${args.date} is ${weather.condition}`;
|
|
106
|
-
},
|
|
107
|
-
});
|
|
108
|
-
```
|
|
109
|
-
|
|
110
|
-
### 2. Advanced ToolResult Pattern
|
|
111
|
-
|
|
112
|
-
For complex scenarios requiring detailed control:
|
|
113
|
-
|
|
114
|
-
```typescript
|
|
115
|
-
// Advanced ToolResult pattern for complex scenarios
|
|
116
|
-
agent.addTool({
|
|
117
|
-
id: "process_payment",
|
|
118
|
-
name: "Payment Processor",
|
|
119
|
-
description: "Process payment with detailed result tracking",
|
|
120
|
-
parameters: {
|
|
121
|
-
type: "object",
|
|
122
|
-
properties: {
|
|
123
|
-
amount: { type: "number", description: "Payment amount" },
|
|
124
|
-
currency: { type: "string", description: "Currency code" },
|
|
125
|
-
},
|
|
126
|
-
required: ["amount", "currency"],
|
|
127
|
-
},
|
|
128
|
-
handler: async ({ context, data }, args) => {
|
|
129
|
-
try {
|
|
130
|
-
const result = await paymentAPI.process(args.amount, args.currency);
|
|
131
|
-
|
|
132
|
-
// Return detailed ToolResult object
|
|
133
|
-
return {
|
|
134
|
-
data: `Payment of ${args.amount} ${args.currency} processed successfully`,
|
|
135
|
-
success: true,
|
|
136
|
-
contextUpdate: {
|
|
137
|
-
lastPaymentId: result.transactionId,
|
|
138
|
-
paymentHistory: [...(context.paymentHistory || []), result]
|
|
139
|
-
},
|
|
140
|
-
dataUpdate: {
|
|
141
|
-
paymentStatus: 'completed',
|
|
142
|
-
transactionId: result.transactionId
|
|
143
|
-
}
|
|
144
|
-
};
|
|
145
|
-
} catch (error) {
|
|
146
|
-
return {
|
|
147
|
-
data: `Payment failed: ${error.message}`,
|
|
148
|
-
success: false,
|
|
149
|
-
contextUpdate: {
|
|
150
|
-
lastPaymentError: error.message
|
|
151
|
-
}
|
|
152
|
-
};
|
|
153
|
-
}
|
|
154
|
-
},
|
|
155
|
-
});
|
|
156
|
-
```
|
|
157
|
-
|
|
158
|
-
## Multiple Creation Approaches
|
|
159
|
-
|
|
160
|
-
Choose the approach that best fits your use case:
|
|
161
|
-
|
|
162
|
-
### 3. Direct Addition (`agent.addTool`)
|
|
163
|
-
|
|
164
|
-
Add tools directly to agent scope - available to all routes and steps:
|
|
165
|
-
|
|
166
|
-
```typescript
|
|
167
|
-
// Creates and adds tool to agent scope in one operation
|
|
168
|
-
agent.addTool({
|
|
169
|
-
id: "math_calculator",
|
|
170
|
-
name: "Math Calculator",
|
|
171
|
-
description: "Perform mathematical calculations",
|
|
172
|
-
parameters: {
|
|
173
|
-
type: "object",
|
|
174
|
-
properties: {
|
|
175
|
-
expression: { type: "string", description: "Mathematical expression to evaluate" },
|
|
176
|
-
},
|
|
177
|
-
required: ["expression"],
|
|
178
|
-
},
|
|
179
|
-
handler: async ({ context, data, updateData }, args) => {
|
|
180
|
-
const result = performCalculation(args.expression);
|
|
181
|
-
|
|
182
|
-
// Update collected data with calculation result
|
|
183
|
-
await updateData({ lastCalculation: result });
|
|
184
|
-
|
|
185
|
-
// Simple return value
|
|
186
|
-
return `Result: ${result}`;
|
|
187
|
-
},
|
|
188
|
-
});
|
|
189
|
-
```
|
|
190
|
-
|
|
191
|
-
### 4. Registry System (`agent.tool.register`)
|
|
192
|
-
|
|
193
|
-
Register tools for reuse across multiple contexts:
|
|
194
|
-
|
|
195
|
-
```typescript
|
|
196
|
-
// Register tool without adding to any scope
|
|
197
|
-
agent.tool.register({
|
|
198
|
-
id: "reusable_search",
|
|
199
|
-
name: "Universal Search",
|
|
200
|
-
description: "Search across multiple data sources",
|
|
201
|
-
parameters: {
|
|
202
|
-
type: "object",
|
|
203
|
-
properties: {
|
|
204
|
-
query: { type: "string", description: "Search query" },
|
|
205
|
-
sources: { type: "array", items: { type: "string" }, description: "Data sources to search" },
|
|
206
|
-
},
|
|
207
|
-
required: ["query"],
|
|
208
|
-
},
|
|
209
|
-
handler: async ({ context, data }, args) => {
|
|
210
|
-
const results = await searchMultipleSources(args.query, args.sources);
|
|
211
|
-
return `Found ${results.length} results`; // Simple return
|
|
212
|
-
},
|
|
213
|
-
});
|
|
214
|
-
|
|
215
|
-
// Reference registered tool by ID in steps
|
|
216
|
-
route.initialStep.nextStep({
|
|
217
|
-
prompt: "What would you like to search for?",
|
|
218
|
-
tools: ['reusable_search'] // Reference by ID
|
|
219
|
-
});
|
|
220
|
-
|
|
221
|
-
// Or add registered tool to specific scopes
|
|
222
|
-
const searchTool = agent.tool.find('reusable_search');
|
|
223
|
-
route.addTool(searchTool);
|
|
224
|
-
```
|
|
225
|
-
|
|
226
|
-
### 5. Manual Creation (`agent.tool.create`)
|
|
227
|
-
|
|
228
|
-
Create tool instances without registering or adding to any scope:
|
|
229
|
-
|
|
230
|
-
```typescript
|
|
231
|
-
// Create tool instance for manual management
|
|
232
|
-
const customTool = agent.tool.create({
|
|
233
|
-
id: "standalone_processor",
|
|
234
|
-
description: "Process data independently",
|
|
235
|
-
handler: async ({ context, data }) => {
|
|
236
|
-
return "Processing complete"; // Simple return
|
|
237
|
-
},
|
|
238
|
-
});
|
|
239
|
-
|
|
240
|
-
// Manually add to specific contexts as needed
|
|
241
|
-
someStep.tools = [customTool];
|
|
242
|
-
```
|
|
243
|
-
|
|
244
|
-
### 6. Bulk Operations (`registerMany`)
|
|
245
|
-
|
|
246
|
-
Register multiple tools at once:
|
|
247
|
-
|
|
248
|
-
```typescript
|
|
249
|
-
agent.tool.registerMany([
|
|
250
|
-
{
|
|
251
|
-
id: "system_status",
|
|
252
|
-
description: "Check system health",
|
|
253
|
-
handler: async () => "System OK", // Simple return
|
|
254
|
-
},
|
|
255
|
-
{
|
|
256
|
-
id: "audit_log",
|
|
257
|
-
description: "Create audit log entry",
|
|
258
|
-
handler: async ({ context }) => `Audit logged for ${context.userId}`,
|
|
259
|
-
},
|
|
260
|
-
existingToolInstance, // Can mix definitions and instances
|
|
261
|
-
]);
|
|
262
|
-
```
|
|
263
|
-
|
|
264
|
-
### 7. Pattern Helpers
|
|
265
|
-
|
|
266
|
-
Use built-in helpers for common tool patterns - these return tool instances that can be registered or added as needed:
|
|
267
|
-
|
|
268
|
-
```typescript
|
|
269
|
-
// Data enrichment tool - returns Tool instance
|
|
270
|
-
const enrichmentTool = agent.tool.createDataEnrichment({
|
|
271
|
-
id: "enrich_user_profile",
|
|
272
|
-
fields: ['name', 'email'] as const, // Type-safe field selection
|
|
273
|
-
enricher: async (context, data) => ({
|
|
274
|
-
fullName: `${data.name} (${context.userRole})`,
|
|
275
|
-
emailDomain: data.email?.split('@')[1],
|
|
276
|
-
})
|
|
277
|
-
});
|
|
278
|
-
|
|
279
|
-
// Validation tool - returns Tool instance
|
|
280
|
-
const validationTool = agent.tool.createValidation({
|
|
281
|
-
id: "validate_booking",
|
|
282
|
-
fields: ['date', 'guests'] as const,
|
|
283
|
-
validator: async (context, data) => {
|
|
284
|
-
const errors = [];
|
|
285
|
-
if (!data.date) errors.push({ field: 'date', message: 'Date is required' });
|
|
286
|
-
if (!data.guests || data.guests < 1) errors.push({ field: 'guests', message: 'At least 1 guest required' });
|
|
287
|
-
|
|
288
|
-
return { valid: errors.length === 0, errors };
|
|
289
|
-
}
|
|
290
|
-
});
|
|
291
|
-
|
|
292
|
-
// API call tool - returns Tool instance
|
|
293
|
-
const apiTool = agent.tool.createApiCall({
|
|
294
|
-
id: "fetch_weather_data",
|
|
295
|
-
endpoint: "https://api.weather.com/v1/current",
|
|
296
|
-
method: "GET",
|
|
297
|
-
headers: { "API-Key": process.env.WEATHER_API_KEY! },
|
|
298
|
-
transform: (response: any) => response.data.current,
|
|
299
|
-
});
|
|
300
|
-
|
|
301
|
-
// Computation tool - returns Tool instance
|
|
302
|
-
const computeTool = agent.tool.createComputation({
|
|
303
|
-
id: "calculate_total_cost",
|
|
304
|
-
inputs: ['basePrice', 'taxRate', 'discountPercent'] as const,
|
|
305
|
-
compute: async (context, inputs) => {
|
|
306
|
-
const subtotal = inputs.basePrice * (1 - (inputs.discountPercent || 0) / 100);
|
|
307
|
-
return subtotal * (1 + (inputs.taxRate || 0));
|
|
308
|
-
}
|
|
309
|
-
});
|
|
310
|
-
|
|
311
|
-
// Register or add pattern helpers as needed
|
|
312
|
-
agent.tool.registerMany([enrichmentTool, validationTool, apiTool, computeTool]);
|
|
313
|
-
```
|
|
314
|
-
|
|
315
|
-
## When to Use Each Approach
|
|
316
|
-
|
|
317
|
-
- **Simple Return Values**: Most common cases, straightforward results
|
|
318
|
-
- **ToolResult Pattern**: Complex scenarios requiring context/data updates
|
|
319
|
-
- **Direct Addition**: Tools specific to one agent
|
|
320
|
-
- **Registry System**: Reusable tools across multiple contexts
|
|
321
|
-
- **Manual Creation**: Custom tool management scenarios
|
|
322
|
-
- **Bulk Operations**: Efficient registration of multiple tools
|
|
323
|
-
- **Pattern Helpers**: Common patterns with built-in logic
|
|
324
|
-
|
|
325
|
-
## Tool Parameters
|
|
326
|
-
|
|
327
|
-
Tool parameters are defined using JSON Schema:
|
|
328
|
-
|
|
329
|
-
```typescript
|
|
330
|
-
agent.addTool({
|
|
331
|
-
id: "web_search",
|
|
332
|
-
name: "Web Search Engine",
|
|
333
|
-
description: "Search the web for information",
|
|
334
|
-
parameters: {
|
|
335
|
-
type: "object",
|
|
336
|
-
properties: {
|
|
337
|
-
query: {
|
|
338
|
-
type: "string",
|
|
339
|
-
description: "Search query",
|
|
340
|
-
minLength: 1,
|
|
341
|
-
maxLength: 200,
|
|
342
|
-
},
|
|
343
|
-
limit: {
|
|
344
|
-
type: "number",
|
|
345
|
-
description: "Maximum number of results",
|
|
346
|
-
minimum: 1,
|
|
347
|
-
maximum: 50,
|
|
348
|
-
default: 10,
|
|
349
|
-
},
|
|
350
|
-
},
|
|
351
|
-
required: ["query"],
|
|
352
|
-
},
|
|
353
|
-
handler: async ({ context, data }, args) => {
|
|
354
|
-
const { query, limit = 10 } = args;
|
|
355
|
-
const results = await searchAPI.query(query, limit);
|
|
356
|
-
return {
|
|
357
|
-
data: `Found ${results.length} results for "${query}"`,
|
|
358
|
-
contextUpdate: { searchResults: results },
|
|
359
|
-
};
|
|
360
|
-
},
|
|
361
|
-
});
|
|
362
|
-
```
|
|
363
|
-
|
|
364
|
-
## Simplified Tool Context
|
|
365
|
-
|
|
366
|
-
Tools receive a simplified context with direct access to agent data and helper methods:
|
|
367
|
-
|
|
368
|
-
```typescript
|
|
369
|
-
agent.addTool({
|
|
370
|
-
id: "get_user_profile",
|
|
371
|
-
description: "Retrieve user profile information",
|
|
372
|
-
parameters: {
|
|
373
|
-
type: "object",
|
|
374
|
-
properties: {
|
|
375
|
-
userId: {
|
|
376
|
-
type: "string",
|
|
377
|
-
description: "User ID (optional, uses context if not provided)",
|
|
378
|
-
},
|
|
379
|
-
},
|
|
380
|
-
},
|
|
381
|
-
handler: async ({ context, data, updateContext, updateData }, args) => {
|
|
382
|
-
// Direct access to current context and data
|
|
383
|
-
const currentUserId = context.userId || args.userId;
|
|
384
|
-
const preferences = data.userPreferences;
|
|
385
|
-
|
|
386
|
-
const profile = await userAPI.getProfile(currentUserId);
|
|
387
|
-
|
|
388
|
-
// Use helper methods for updates
|
|
389
|
-
await updateData({ userProfile: profile });
|
|
390
|
-
|
|
391
|
-
return {
|
|
392
|
-
data: `Retrieved profile for ${profile.name}`,
|
|
393
|
-
};
|
|
394
|
-
},
|
|
395
|
-
});
|
|
396
|
-
```
|
|
397
|
-
|
|
398
|
-
### Context Helper Methods
|
|
399
|
-
|
|
400
|
-
The simplified context provides convenient helper methods:
|
|
401
|
-
|
|
402
|
-
```typescript
|
|
403
|
-
agent.addTool({
|
|
404
|
-
id: "user_preferences",
|
|
405
|
-
handler: async ({ context, data, getField, setField, hasField }) => {
|
|
406
|
-
// Check if field exists
|
|
407
|
-
if (hasField('preferences')) {
|
|
408
|
-
const prefs = getField('preferences');
|
|
409
|
-
console.log('Current preferences:', prefs);
|
|
410
|
-
}
|
|
411
|
-
|
|
412
|
-
// Set field value
|
|
413
|
-
await setField('lastLogin', new Date().toISOString());
|
|
414
|
-
|
|
415
|
-
return { data: "Preferences updated" };
|
|
416
|
-
},
|
|
417
|
-
});
|
|
418
|
-
```
|
|
419
|
-
|
|
420
|
-
## Tool Response Format
|
|
421
|
-
|
|
422
|
-
Tools return structured responses with multiple components:
|
|
423
|
-
|
|
424
|
-
```typescript
|
|
425
|
-
interface ToolResult {
|
|
426
|
-
success: boolean;
|
|
427
|
-
result?: {
|
|
428
|
-
data: unknown; // User-visible result
|
|
429
|
-
contextUpdate?: Partial<TContext>; // Context modifications
|
|
430
|
-
dataUpdate?: Partial<TData>; // Session data updates
|
|
431
|
-
};
|
|
432
|
-
error?: string; // Error message if failed
|
|
433
|
-
}
|
|
434
|
-
```
|
|
435
|
-
|
|
436
|
-
## Context Updates
|
|
437
|
-
|
|
438
|
-
Tools can modify conversation context:
|
|
439
|
-
|
|
440
|
-
```typescript
|
|
441
|
-
const locationTool: Tool<unknown, LocationData, [], string> = {
|
|
442
|
-
id: "set_location",
|
|
443
|
-
description: "Update the user's location in context",
|
|
444
|
-
parameters: {
|
|
445
|
-
type: "object",
|
|
446
|
-
properties: {
|
|
447
|
-
location: { type: "string", description: "New location" },
|
|
448
|
-
},
|
|
449
|
-
required: ["location"],
|
|
450
|
-
},
|
|
451
|
-
handler: async (toolContext, args) => {
|
|
452
|
-
return {
|
|
453
|
-
data: `Location set to ${args.location}`,
|
|
454
|
-
contextUpdate: {
|
|
455
|
-
currentLocation: args.location,
|
|
456
|
-
locationSetAt: new Date().toISOString(),
|
|
457
|
-
locationHistory: (prev: string[]) => [...(prev || []), args.location],
|
|
458
|
-
},
|
|
459
|
-
};
|
|
460
|
-
},
|
|
461
|
-
};
|
|
462
|
-
```
|
|
463
|
-
|
|
464
|
-
## Data Collection Updates
|
|
465
|
-
|
|
466
|
-
Tools can update session data collected during conversation:
|
|
467
|
-
|
|
468
|
-
```typescript
|
|
469
|
-
const validationTool: Tool<unknown, BookingData, [], string> = {
|
|
470
|
-
id: "validate_booking",
|
|
471
|
-
description: "Validate booking information and update session data",
|
|
472
|
-
parameters: {
|
|
473
|
-
type: "object",
|
|
474
|
-
properties: {},
|
|
475
|
-
},
|
|
476
|
-
handler: async (toolContext) => {
|
|
477
|
-
const validation = await bookingAPI.validate(toolContext.data.bookingInfo);
|
|
478
|
-
|
|
479
|
-
if (!validation.valid) {
|
|
480
|
-
return {
|
|
481
|
-
data: `Booking validation failed: ${validation.errors.join(", ")}`,
|
|
482
|
-
dataUpdate: {
|
|
483
|
-
bookingErrors: validation.errors,
|
|
484
|
-
bookingValid: false,
|
|
485
|
-
},
|
|
486
|
-
};
|
|
487
|
-
}
|
|
488
|
-
|
|
489
|
-
return {
|
|
490
|
-
data: "Booking validated successfully",
|
|
491
|
-
dataUpdate: {
|
|
492
|
-
bookingValid: true,
|
|
493
|
-
validatedAt: new Date().toISOString(),
|
|
494
|
-
},
|
|
495
|
-
};
|
|
496
|
-
},
|
|
497
|
-
};
|
|
498
|
-
```
|
|
499
|
-
|
|
500
|
-
## Error Handling
|
|
501
|
-
|
|
502
|
-
Tools should handle errors gracefully:
|
|
503
|
-
|
|
504
|
-
```typescript
|
|
505
|
-
const apiTool: Tool<unknown, ApiData, [], string> = {
|
|
506
|
-
id: "call_external_api",
|
|
507
|
-
description: "Call an external API endpoint",
|
|
508
|
-
parameters: {
|
|
509
|
-
type: "object",
|
|
510
|
-
properties: {
|
|
511
|
-
endpoint: { type: "string", description: "API endpoint to call" },
|
|
512
|
-
},
|
|
513
|
-
required: ["endpoint"],
|
|
514
|
-
},
|
|
515
|
-
handler: async (toolContext, args) => {
|
|
516
|
-
try {
|
|
517
|
-
const result = await externalAPI.call(args.endpoint);
|
|
518
|
-
return {
|
|
519
|
-
data: `API call successful: ${result}`,
|
|
520
|
-
};
|
|
521
|
-
} catch (error) {
|
|
522
|
-
const errorMessage =
|
|
523
|
-
error instanceof Error ? error.message : "Unknown error";
|
|
524
|
-
return {
|
|
525
|
-
data: `API call failed: ${errorMessage}`,
|
|
526
|
-
contextUpdate: { lastApiError: errorMessage },
|
|
527
|
-
};
|
|
528
|
-
}
|
|
529
|
-
},
|
|
530
|
-
};
|
|
531
|
-
```
|
|
532
|
-
|
|
533
|
-
## Tool Scoping
|
|
534
|
-
|
|
535
|
-
Tools can be added at different scopes using the new ToolManager API:
|
|
536
|
-
|
|
537
|
-
### Agent-Level Tools
|
|
538
|
-
|
|
539
|
-
Available to all routes and steps:
|
|
540
|
-
|
|
541
|
-
```typescript
|
|
542
|
-
// Add tools directly to agent scope
|
|
543
|
-
agent.addTool({
|
|
544
|
-
id: "global_search",
|
|
545
|
-
description: "Search across all data sources",
|
|
546
|
-
handler: async ({ context, data }) => {
|
|
547
|
-
// Tool logic here
|
|
548
|
-
return { data: "Search completed" };
|
|
549
|
-
},
|
|
550
|
-
});
|
|
551
|
-
|
|
552
|
-
// Or register for later use
|
|
553
|
-
agent.tool.register({
|
|
554
|
-
id: "user_management",
|
|
555
|
-
description: "Manage user accounts",
|
|
556
|
-
handler: async ({ context, data }) => {
|
|
557
|
-
return { data: "User managed" };
|
|
558
|
-
},
|
|
559
|
-
});
|
|
560
|
-
```
|
|
561
|
-
|
|
562
|
-
### Route-Level Tools
|
|
563
|
-
|
|
564
|
-
Available only within specific routes:
|
|
565
|
-
|
|
566
|
-
```typescript
|
|
567
|
-
const supportRoute = agent.createRoute({
|
|
568
|
-
title: "Customer Support",
|
|
569
|
-
});
|
|
570
|
-
|
|
571
|
-
// Add tools to route scope
|
|
572
|
-
supportRoute.addTool({
|
|
573
|
-
id: "create_ticket",
|
|
574
|
-
description: "Create support ticket",
|
|
575
|
-
handler: async ({ context, data }) => {
|
|
576
|
-
return { data: "Ticket created" };
|
|
577
|
-
},
|
|
578
|
-
});
|
|
579
|
-
```
|
|
580
|
-
|
|
581
|
-
### Step-Level Tools
|
|
582
|
-
|
|
583
|
-
Available only in specific steps:
|
|
584
|
-
|
|
585
|
-
```typescript
|
|
586
|
-
// Add tool directly to step
|
|
587
|
-
const bookingStep = route.initialStep.nextStep({
|
|
588
|
-
prompt: "Ready to book?",
|
|
589
|
-
requires: ["bookingDetails"],
|
|
590
|
-
}).addTool({
|
|
591
|
-
id: "process_payment",
|
|
592
|
-
description: "Process payment for booking",
|
|
593
|
-
handler: async ({ context, data }) => {
|
|
594
|
-
return { data: "Payment processed" };
|
|
595
|
-
},
|
|
596
|
-
});
|
|
597
|
-
|
|
598
|
-
// Or reference registered tools by ID
|
|
599
|
-
const step = route.initialStep.nextStep({
|
|
600
|
-
prompt: "Processing...",
|
|
601
|
-
tools: ['registered_tool_id'], // Reference by ID
|
|
602
|
-
});
|
|
603
|
-
```
|
|
604
|
-
|
|
605
|
-
## Tool Resolution Priority
|
|
606
|
-
|
|
607
|
-
When multiple tools with the same name exist, priority is:
|
|
608
|
-
|
|
609
|
-
1. **Step-level tools** (highest priority)
|
|
610
|
-
2. **Route-level tools**
|
|
611
|
-
3. **Agent-level tools** (lowest priority)
|
|
612
|
-
|
|
613
|
-
## Async Tools
|
|
614
|
-
|
|
615
|
-
Tools support async operations and Promises:
|
|
616
|
-
|
|
617
|
-
```typescript
|
|
618
|
-
const asyncTool: Tool<unknown, ProcessingData, [], string> = {
|
|
619
|
-
id: "process_data",
|
|
620
|
-
description: "Process data asynchronously with heavy computation",
|
|
621
|
-
parameters: {
|
|
622
|
-
type: "object",
|
|
623
|
-
properties: {
|
|
624
|
-
data: { type: "object", description: "Data to process" },
|
|
625
|
-
},
|
|
626
|
-
required: ["data"],
|
|
627
|
-
},
|
|
628
|
-
handler: async (toolContext, args) => {
|
|
629
|
-
// Simulate async processing
|
|
630
|
-
await new Promise((resolve) => setTimeout(resolve, 1000));
|
|
631
|
-
|
|
632
|
-
const processed = await heavyComputation(args.data);
|
|
633
|
-
|
|
634
|
-
return {
|
|
635
|
-
data: "Data processed successfully",
|
|
636
|
-
dataUpdate: { processedData: processed },
|
|
637
|
-
};
|
|
638
|
-
},
|
|
639
|
-
};
|
|
640
|
-
```
|
|
641
|
-
|
|
642
|
-
## Tool Validation
|
|
643
|
-
|
|
644
|
-
Tools are validated at registration time:
|
|
645
|
-
|
|
646
|
-
- **Schema validation** - Parameter schemas must be valid JSON Schema
|
|
647
|
-
- **Type checking** - TypeScript types must match schemas
|
|
648
|
-
- **Name uniqueness** - Tool names must be unique within scope
|
|
649
|
-
|
|
650
|
-
## Pattern Helpers
|
|
651
|
-
|
|
652
|
-
ToolManager provides built-in helpers for common tool patterns:
|
|
653
|
-
|
|
654
|
-
### Data Enrichment Tools
|
|
655
|
-
|
|
656
|
-
For tools that modify collected data:
|
|
657
|
-
|
|
658
|
-
```typescript
|
|
659
|
-
const enrichmentTool = agent.tool.createDataEnrichment({
|
|
660
|
-
id: "enrich_user_data",
|
|
661
|
-
fields: ['name', 'email'],
|
|
662
|
-
enricher: async (context, data) => ({
|
|
663
|
-
fullName: `${data.name} (${context.userRole})`,
|
|
664
|
-
emailDomain: data.email.split('@')[1]
|
|
665
|
-
})
|
|
666
|
-
});
|
|
667
|
-
|
|
668
|
-
// Register or add to scope
|
|
669
|
-
agent.tool.register(enrichmentTool);
|
|
670
|
-
```
|
|
671
|
-
|
|
672
|
-
### Validation Tools
|
|
673
|
-
|
|
674
|
-
For tools that validate data fields:
|
|
675
|
-
|
|
676
|
-
```typescript
|
|
677
|
-
const validationTool = agent.tool.createValidation({
|
|
678
|
-
id: "validate_booking",
|
|
679
|
-
fields: ['bookingDate', 'guestCount'],
|
|
680
|
-
validator: async (context, data) => {
|
|
681
|
-
const errors = [];
|
|
682
|
-
if (!data.bookingDate) errors.push({ field: 'bookingDate', message: 'Required' });
|
|
683
|
-
if (data.guestCount < 1) errors.push({ field: 'guestCount', message: 'Must be positive' });
|
|
684
|
-
|
|
685
|
-
return {
|
|
686
|
-
valid: errors.length === 0,
|
|
687
|
-
errors
|
|
688
|
-
};
|
|
689
|
-
}
|
|
690
|
-
});
|
|
691
|
-
|
|
692
|
-
agent.addTool(validationTool);
|
|
693
|
-
```
|
|
694
|
-
|
|
695
|
-
### API Call Tools
|
|
696
|
-
|
|
697
|
-
For tools that make external API calls:
|
|
698
|
-
|
|
699
|
-
```typescript
|
|
700
|
-
const apiTool = agent.tool.createApiCall({
|
|
701
|
-
id: "fetch_weather",
|
|
702
|
-
endpoint: "https://api.weather.com/forecast",
|
|
703
|
-
method: "GET",
|
|
704
|
-
headers: { "API-Key": process.env.WEATHER_API_KEY },
|
|
705
|
-
transform: (response) => response.data.forecast
|
|
706
|
-
});
|
|
707
|
-
|
|
708
|
-
agent.tool.register(apiTool);
|
|
709
|
-
```
|
|
710
|
-
|
|
711
|
-
### Computation Tools
|
|
712
|
-
|
|
713
|
-
For tools that perform calculations:
|
|
714
|
-
|
|
715
|
-
```typescript
|
|
716
|
-
const computeTool = agent.tool.createComputation({
|
|
717
|
-
id: "calculate_total",
|
|
718
|
-
inputs: ['price', 'quantity', 'taxRate'],
|
|
719
|
-
compute: async (context, inputs) => {
|
|
720
|
-
const subtotal = inputs.price * inputs.quantity;
|
|
721
|
-
const tax = subtotal * inputs.taxRate;
|
|
722
|
-
return subtotal + tax;
|
|
723
|
-
}
|
|
724
|
-
});
|
|
725
|
-
|
|
726
|
-
agent.addTool(computeTool);
|
|
727
|
-
```
|
|
728
|
-
|
|
729
|
-
## Tool Registry and Resolution
|
|
730
|
-
|
|
731
|
-
### Registry Management
|
|
732
|
-
|
|
733
|
-
```typescript
|
|
734
|
-
// Register multiple tools at once
|
|
735
|
-
agent.tool.registerMany([
|
|
736
|
-
{ id: 'tool1', handler: () => {} },
|
|
737
|
-
{ id: 'tool2', handler: () => {} },
|
|
738
|
-
existingToolInstance
|
|
739
|
-
]);
|
|
740
|
-
|
|
741
|
-
// Check if tool is registered
|
|
742
|
-
if (agent.tool.isRegistered('my_tool')) {
|
|
743
|
-
console.log('Tool is available');
|
|
744
|
-
}
|
|
745
|
-
|
|
746
|
-
// Get all registered tools
|
|
747
|
-
const registeredTools = agent.tool.getRegistered();
|
|
748
|
-
```
|
|
749
|
-
|
|
750
|
-
### Tool Resolution
|
|
751
|
-
|
|
752
|
-
Tools are resolved with the following priority:
|
|
753
|
-
|
|
754
|
-
1. **Step-level inline tools** (highest priority)
|
|
755
|
-
2. **Step-level tool references** (by ID) → Registry lookup
|
|
756
|
-
3. **Route-level tools**
|
|
757
|
-
4. **Agent-level tools**
|
|
758
|
-
5. **Registered tools** (fallback for unresolved IDs)
|
|
759
|
-
|
|
760
|
-
```typescript
|
|
761
|
-
// Find tool across all scopes
|
|
762
|
-
const tool = agent.tool.find('my_tool');
|
|
763
|
-
|
|
764
|
-
// Get available tools for current context
|
|
765
|
-
const availableTools = agent.tool.getAvailable();
|
|
766
|
-
```
|
|
767
|
-
|
|
768
|
-
## Tools as Step Lifecycle Hooks
|
|
769
|
-
|
|
770
|
-
Tools can be used as `prepare` and `finalize` functions in step lifecycle, enabling powerful data processing and side effects before and after AI responses:
|
|
771
|
-
|
|
772
|
-
### Using Tools for Step Preparation
|
|
773
|
-
|
|
774
|
-
```typescript
|
|
775
|
-
// Create a preparation tool
|
|
776
|
-
agent.addTool({
|
|
777
|
-
id: "validate_user_data",
|
|
778
|
-
name: "User Data Validator",
|
|
779
|
-
description: "Validate user data before processing",
|
|
780
|
-
parameters: { type: "object", properties: {} },
|
|
781
|
-
handler: async ({ context, data, updateData }) => {
|
|
782
|
-
// Validation logic with helper methods
|
|
783
|
-
if (!data.email?.includes("@")) {
|
|
784
|
-
throw new Error("Invalid email address");
|
|
785
|
-
}
|
|
786
|
-
|
|
787
|
-
// Mark as validated using helper method
|
|
788
|
-
await updateData({ emailValidated: true });
|
|
789
|
-
|
|
790
|
-
return "User validation completed successfully";
|
|
791
|
-
},
|
|
792
|
-
});
|
|
793
|
-
|
|
794
|
-
// Use tool as prepare hook
|
|
795
|
-
const step = route.initialStep.nextStep({
|
|
796
|
-
id: "collect_info",
|
|
797
|
-
description: "Collect user information",
|
|
798
|
-
collect: ["name", "email"],
|
|
799
|
-
prompt: "Please provide your name and email.",
|
|
800
|
-
prepare: "validate_user_data", // Tool ID string - executes before AI response
|
|
801
|
-
});
|
|
802
|
-
```
|
|
803
|
-
|
|
804
|
-
### Using Tools for Step Finalization
|
|
805
|
-
|
|
806
|
-
```typescript
|
|
807
|
-
// Create a finalization tool with ToolResult pattern
|
|
808
|
-
agent.addTool({
|
|
809
|
-
id: "send_welcome_email",
|
|
810
|
-
name: "Welcome Email Sender",
|
|
811
|
-
description: "Send welcome email after data collection",
|
|
812
|
-
parameters: { type: "object", properties: {} },
|
|
813
|
-
handler: async ({ context, data }) => {
|
|
814
|
-
const emailResult = await emailService.sendWelcome(data.email, data.name);
|
|
815
|
-
|
|
816
|
-
return {
|
|
817
|
-
data: `Welcome email sent to ${data.email}`,
|
|
818
|
-
success: emailResult.success,
|
|
819
|
-
contextUpdate: {
|
|
820
|
-
lastEmailSent: new Date().toISOString(),
|
|
821
|
-
emailsSent: (context.emailsSent || 0) + 1
|
|
822
|
-
}
|
|
823
|
-
};
|
|
824
|
-
},
|
|
825
|
-
});
|
|
826
|
-
|
|
827
|
-
// Use tool as finalize hook
|
|
828
|
-
const welcomeStep = route.initialStep.nextStep({
|
|
829
|
-
id: "send_welcome",
|
|
830
|
-
description: "Send welcome email",
|
|
831
|
-
prompt: "Welcome! Check your email for confirmation.",
|
|
832
|
-
finalize: "send_welcome_email", // Tool ID string - executes after AI response
|
|
833
|
-
});
|
|
834
|
-
```
|
|
835
|
-
|
|
836
|
-
### Multiple Lifecycle Approaches
|
|
837
|
-
|
|
838
|
-
Tools can be used in step lifecycle in several ways:
|
|
839
|
-
|
|
840
|
-
```typescript
|
|
841
|
-
// Method 1: Tool ID reference (most common)
|
|
842
|
-
const step1 = route.initialStep.nextStep({
|
|
843
|
-
prompt: "Processing your request...",
|
|
844
|
-
prepare: "setup_processing", // References registered tool by ID
|
|
845
|
-
finalize: "cleanup_processing", // References registered tool by ID
|
|
846
|
-
});
|
|
847
|
-
|
|
848
|
-
// Method 2: Inline tool definition
|
|
849
|
-
const step2 = route.initialStep.nextStep({
|
|
850
|
-
prompt: "Validating your information...",
|
|
851
|
-
prepare: {
|
|
852
|
-
id: "inline_validator",
|
|
853
|
-
description: "Validate data inline",
|
|
854
|
-
handler: async ({ context, data }) => {
|
|
855
|
-
// Inline validation logic
|
|
856
|
-
return data.isValid ? "Validation passed" : "Validation failed";
|
|
857
|
-
}
|
|
858
|
-
}
|
|
859
|
-
});
|
|
860
|
-
|
|
861
|
-
// Method 3: Function reference (traditional approach)
|
|
862
|
-
const step3 = route.initialStep.nextStep({
|
|
863
|
-
prompt: "Setting up your account...",
|
|
864
|
-
prepare: async (context, data) => {
|
|
865
|
-
// Traditional function approach
|
|
866
|
-
console.log("Preparing account setup...");
|
|
867
|
-
},
|
|
868
|
-
finalize: async (context, data) => {
|
|
869
|
-
// Traditional function approach
|
|
870
|
-
console.log("Account setup complete");
|
|
871
|
-
}
|
|
872
|
-
});
|
|
873
|
-
```
|
|
874
|
-
|
|
875
|
-
### Advanced Lifecycle Tool Patterns
|
|
876
|
-
|
|
877
|
-
```typescript
|
|
878
|
-
// Data enrichment during preparation
|
|
879
|
-
agent.addTool({
|
|
880
|
-
id: "enrich_user_context",
|
|
881
|
-
description: "Enrich user context before processing",
|
|
882
|
-
handler: async ({ context, data, updateContext, updateData }) => {
|
|
883
|
-
// Fetch additional user data
|
|
884
|
-
const userProfile = await userService.getProfile(context.userId);
|
|
885
|
-
const preferences = await userService.getPreferences(context.userId);
|
|
886
|
-
|
|
887
|
-
// Update context with enriched data
|
|
888
|
-
await updateContext({
|
|
889
|
-
userProfile,
|
|
890
|
-
preferences,
|
|
891
|
-
lastEnrichment: new Date().toISOString()
|
|
892
|
-
});
|
|
893
|
-
|
|
894
|
-
// Update collected data
|
|
895
|
-
await updateData({
|
|
896
|
-
userTier: userProfile.tier,
|
|
897
|
-
preferredLanguage: preferences.language
|
|
898
|
-
});
|
|
899
|
-
|
|
900
|
-
return {
|
|
901
|
-
data: "User context enriched successfully",
|
|
902
|
-
contextUpdate: { enrichmentComplete: true }
|
|
903
|
-
};
|
|
904
|
-
}
|
|
905
|
-
});
|
|
906
|
-
|
|
907
|
-
// Audit logging during finalization
|
|
908
|
-
agent.addTool({
|
|
909
|
-
id: "audit_step_completion",
|
|
910
|
-
description: "Log step completion for audit trail",
|
|
911
|
-
handler: async ({ context, data }) => {
|
|
912
|
-
await auditService.logStepCompletion({
|
|
913
|
-
userId: context.userId,
|
|
914
|
-
stepId: context.currentStep,
|
|
915
|
-
timestamp: new Date(),
|
|
916
|
-
collectedData: data
|
|
917
|
-
});
|
|
918
|
-
|
|
919
|
-
return "Step completion logged";
|
|
920
|
-
}
|
|
921
|
-
});
|
|
922
|
-
|
|
923
|
-
// Use in step with both prepare and finalize
|
|
924
|
-
const auditedStep = route.initialStep.nextStep({
|
|
925
|
-
prompt: "Processing your secure transaction...",
|
|
926
|
-
prepare: "enrich_user_context",
|
|
927
|
-
finalize: "audit_step_completion",
|
|
928
|
-
collect: ["transactionAmount", "recipientAccount"]
|
|
929
|
-
});
|
|
930
|
-
```
|
|
931
|
-
|
|
932
|
-
### Benefits of Tool-Based Lifecycle Hooks
|
|
933
|
-
|
|
934
|
-
- ✅ **Reusable Logic** - Tools can be shared across steps and routes
|
|
935
|
-
- ✅ **Error Handling** - Tool execution includes automatic error handling
|
|
936
|
-
- ✅ **Context Access** - Tools receive full context and collected data
|
|
937
|
-
- ✅ **Data Updates** - Tools can modify collected data or agent context
|
|
938
|
-
- ✅ **Flexible Returns** - Support both simple returns and complex ToolResult objects
|
|
939
|
-
- ✅ **Type Safety** - Full TypeScript support with automatic inference
|
|
940
|
-
- ✅ **Registry Integration** - Reference tools by ID for consistency
|
|
941
|
-
|
|
942
|
-
### Lifecycle Execution Order
|
|
943
|
-
|
|
944
|
-
When using tools in step lifecycle:
|
|
945
|
-
|
|
946
|
-
1. **Prepare Phase**: Tool executes before AI response generation
|
|
947
|
-
2. **AI Response**: Agent generates response based on enriched context/data
|
|
948
|
-
3. **Finalize Phase**: Tool executes after AI response, can process results
|
|
949
|
-
|
|
950
|
-
```typescript
|
|
951
|
-
const lifecycleStep = route.initialStep.nextStep({
|
|
952
|
-
prompt: "Let me process your request...",
|
|
953
|
-
prepare: "setup_processing", // 1. Executes first
|
|
954
|
-
// 2. AI generates response using enriched context
|
|
955
|
-
finalize: "complete_processing", // 3. Executes last
|
|
956
|
-
});
|
|
957
|
-
```
|
|
958
|
-
|
|
959
|
-
## Best Practices
|
|
960
|
-
|
|
961
|
-
- **Use pattern helpers** - Leverage built-in helpers for common patterns
|
|
962
|
-
- **Register reusable tools** - Use registry for tools referenced across multiple steps
|
|
963
|
-
- **Keep tools focused** - Each tool should do one thing well
|
|
964
|
-
- **Use descriptive names** - Tool names should be clear and specific
|
|
965
|
-
- **Handle errors gracefully** - Provide meaningful error messages
|
|
966
|
-
- **Leverage helper methods** - Use `updateContext`, `updateData`, `getField`, etc.
|
|
967
|
-
- **Validate parameters** - Use JSON Schema constraints effectively
|
|
968
|
-
- **Consider performance** - Avoid long-running operations when possible
|
|
969
|
-
- **Document thoroughly** - Provide clear descriptions for AI usage
|
|
970
|
-
- **Use lifecycle hooks** - Leverage prepare/finalize for setup and cleanup logic
|