@falai/agent 1.2.7 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (508) hide show
  1. package/README.md +40 -886
  2. package/dist/adapters/MemoryAdapter.js +2 -2
  3. package/dist/adapters/MemoryAdapter.js.map +1 -1
  4. package/dist/adapters/MongoAdapter.js +2 -2
  5. package/dist/adapters/MongoAdapter.js.map +1 -1
  6. package/dist/adapters/OpenSearchAdapter.d.ts.map +1 -1
  7. package/dist/adapters/OpenSearchAdapter.js +9 -7
  8. package/dist/adapters/OpenSearchAdapter.js.map +1 -1
  9. package/dist/adapters/PostgreSQLAdapter.d.ts +14 -0
  10. package/dist/adapters/PostgreSQLAdapter.d.ts.map +1 -1
  11. package/dist/adapters/PostgreSQLAdapter.js +25 -9
  12. package/dist/adapters/PostgreSQLAdapter.js.map +1 -1
  13. package/dist/adapters/PrismaAdapter.js +5 -5
  14. package/dist/adapters/PrismaAdapter.js.map +1 -1
  15. package/dist/adapters/RedisAdapter.js +2 -2
  16. package/dist/adapters/RedisAdapter.js.map +1 -1
  17. package/dist/adapters/SQLiteAdapter.d.ts +17 -0
  18. package/dist/adapters/SQLiteAdapter.d.ts.map +1 -1
  19. package/dist/adapters/SQLiteAdapter.js +30 -11
  20. package/dist/adapters/SQLiteAdapter.js.map +1 -1
  21. package/dist/cjs/adapters/MemoryAdapter.js +2 -2
  22. package/dist/cjs/adapters/MemoryAdapter.js.map +1 -1
  23. package/dist/cjs/adapters/MongoAdapter.js +2 -2
  24. package/dist/cjs/adapters/MongoAdapter.js.map +1 -1
  25. package/dist/cjs/adapters/OpenSearchAdapter.d.ts.map +1 -1
  26. package/dist/cjs/adapters/OpenSearchAdapter.js +9 -7
  27. package/dist/cjs/adapters/OpenSearchAdapter.js.map +1 -1
  28. package/dist/cjs/adapters/PostgreSQLAdapter.d.ts +14 -0
  29. package/dist/cjs/adapters/PostgreSQLAdapter.d.ts.map +1 -1
  30. package/dist/cjs/adapters/PostgreSQLAdapter.js +25 -9
  31. package/dist/cjs/adapters/PostgreSQLAdapter.js.map +1 -1
  32. package/dist/cjs/adapters/PrismaAdapter.js +5 -5
  33. package/dist/cjs/adapters/PrismaAdapter.js.map +1 -1
  34. package/dist/cjs/adapters/RedisAdapter.js +2 -2
  35. package/dist/cjs/adapters/RedisAdapter.js.map +1 -1
  36. package/dist/cjs/adapters/SQLiteAdapter.d.ts +17 -0
  37. package/dist/cjs/adapters/SQLiteAdapter.d.ts.map +1 -1
  38. package/dist/cjs/adapters/SQLiteAdapter.js +30 -11
  39. package/dist/cjs/adapters/SQLiteAdapter.js.map +1 -1
  40. package/dist/cjs/constants/index.d.ts +0 -9
  41. package/dist/cjs/constants/index.d.ts.map +1 -1
  42. package/dist/cjs/constants/index.js +2 -11
  43. package/dist/cjs/constants/index.js.map +1 -1
  44. package/dist/cjs/core/Agent.d.ts +119 -153
  45. package/dist/cjs/core/Agent.d.ts.map +1 -1
  46. package/dist/cjs/core/Agent.js +471 -324
  47. package/dist/cjs/core/Agent.js.map +1 -1
  48. package/dist/cjs/core/AutoChainExecutor.d.ts +107 -0
  49. package/dist/cjs/core/AutoChainExecutor.d.ts.map +1 -0
  50. package/dist/cjs/core/AutoChainExecutor.js +297 -0
  51. package/dist/cjs/core/AutoChainExecutor.js.map +1 -0
  52. package/dist/cjs/core/BranchEvaluator.d.ts +54 -0
  53. package/dist/cjs/core/BranchEvaluator.d.ts.map +1 -0
  54. package/dist/cjs/core/BranchEvaluator.js +130 -0
  55. package/dist/cjs/core/BranchEvaluator.js.map +1 -0
  56. package/dist/cjs/core/DirectiveBus.d.ts +88 -0
  57. package/dist/cjs/core/DirectiveBus.d.ts.map +1 -0
  58. package/dist/cjs/core/DirectiveBus.js +196 -0
  59. package/dist/cjs/core/DirectiveBus.js.map +1 -0
  60. package/dist/cjs/core/DirectiveChainTracker.d.ts +49 -0
  61. package/dist/cjs/core/DirectiveChainTracker.d.ts.map +1 -0
  62. package/dist/cjs/core/DirectiveChainTracker.js +121 -0
  63. package/dist/cjs/core/DirectiveChainTracker.js.map +1 -0
  64. package/dist/cjs/core/Flow.d.ts +186 -0
  65. package/dist/cjs/core/Flow.d.ts.map +1 -0
  66. package/dist/cjs/core/Flow.js +550 -0
  67. package/dist/cjs/core/Flow.js.map +1 -0
  68. package/dist/cjs/core/FlowRouter.d.ts +182 -0
  69. package/dist/cjs/core/FlowRouter.d.ts.map +1 -0
  70. package/dist/cjs/core/{RoutingEngine.js → FlowRouter.js} +323 -306
  71. package/dist/cjs/core/FlowRouter.js.map +1 -0
  72. package/dist/cjs/core/PersistenceManager.d.ts +2 -2
  73. package/dist/cjs/core/PersistenceManager.d.ts.map +1 -1
  74. package/dist/cjs/core/PersistenceManager.js +7 -7
  75. package/dist/cjs/core/PersistenceManager.js.map +1 -1
  76. package/dist/cjs/core/PromptComposer.d.ts +21 -8
  77. package/dist/cjs/core/PromptComposer.d.ts.map +1 -1
  78. package/dist/cjs/core/PromptComposer.js +182 -105
  79. package/dist/cjs/core/PromptComposer.js.map +1 -1
  80. package/dist/cjs/core/PromptSectionCache.d.ts +1 -1
  81. package/dist/cjs/core/PromptSectionCache.js +1 -1
  82. package/dist/cjs/core/ResponseEngine.d.ts +18 -8
  83. package/dist/cjs/core/ResponseEngine.d.ts.map +1 -1
  84. package/dist/cjs/core/ResponseEngine.js +38 -36
  85. package/dist/cjs/core/ResponseEngine.js.map +1 -1
  86. package/dist/cjs/core/ResponseModal.d.ts +73 -56
  87. package/dist/cjs/core/ResponseModal.d.ts.map +1 -1
  88. package/dist/cjs/core/ResponseModal.js +1196 -1015
  89. package/dist/cjs/core/ResponseModal.js.map +1 -1
  90. package/dist/cjs/core/ResponsePipeline.d.ts +124 -26
  91. package/dist/cjs/core/ResponsePipeline.d.ts.map +1 -1
  92. package/dist/cjs/core/ResponsePipeline.js +524 -134
  93. package/dist/cjs/core/ResponsePipeline.js.map +1 -1
  94. package/dist/cjs/core/SignalEvaluator.d.ts +86 -0
  95. package/dist/cjs/core/SignalEvaluator.d.ts.map +1 -0
  96. package/dist/cjs/core/SignalEvaluator.js +333 -0
  97. package/dist/cjs/core/SignalEvaluator.js.map +1 -0
  98. package/dist/cjs/core/SignalProcessor.d.ts +152 -0
  99. package/dist/cjs/core/SignalProcessor.d.ts.map +1 -0
  100. package/dist/cjs/core/SignalProcessor.js +562 -0
  101. package/dist/cjs/core/SignalProcessor.js.map +1 -0
  102. package/dist/cjs/core/Step.d.ts +43 -32
  103. package/dist/cjs/core/Step.d.ts.map +1 -1
  104. package/dist/cjs/core/Step.js +221 -126
  105. package/dist/cjs/core/Step.js.map +1 -1
  106. package/dist/cjs/core/StreamingToolExecutor.d.ts +2 -2
  107. package/dist/cjs/core/StreamingToolExecutor.d.ts.map +1 -1
  108. package/dist/cjs/core/StreamingToolExecutor.js.map +1 -1
  109. package/dist/cjs/core/ToolManager.d.ts +44 -13
  110. package/dist/cjs/core/ToolManager.d.ts.map +1 -1
  111. package/dist/cjs/core/ToolManager.js +174 -91
  112. package/dist/cjs/core/ToolManager.js.map +1 -1
  113. package/dist/cjs/core/createAgent.d.ts +35 -0
  114. package/dist/cjs/core/createAgent.d.ts.map +1 -0
  115. package/dist/cjs/core/createAgent.js +39 -0
  116. package/dist/cjs/core/createAgent.js.map +1 -0
  117. package/dist/cjs/core/flow-namespace.d.ts +49 -0
  118. package/dist/cjs/core/flow-namespace.d.ts.map +1 -0
  119. package/dist/cjs/core/flow-namespace.js +171 -0
  120. package/dist/cjs/core/flow-namespace.js.map +1 -0
  121. package/dist/cjs/index.d.ts +11 -14
  122. package/dist/cjs/index.d.ts.map +1 -1
  123. package/dist/cjs/index.js +18 -22
  124. package/dist/cjs/index.js.map +1 -1
  125. package/dist/cjs/providers/GeminiProvider.d.ts +3 -3
  126. package/dist/cjs/providers/GeminiProvider.d.ts.map +1 -1
  127. package/dist/cjs/providers/GeminiProvider.js +16 -14
  128. package/dist/cjs/providers/GeminiProvider.js.map +1 -1
  129. package/dist/cjs/types/agent.d.ts +183 -54
  130. package/dist/cjs/types/agent.d.ts.map +1 -1
  131. package/dist/cjs/types/agent.js +0 -6
  132. package/dist/cjs/types/agent.js.map +1 -1
  133. package/dist/cjs/types/ai.d.ts +3 -3
  134. package/dist/cjs/types/ai.d.ts.map +1 -1
  135. package/dist/cjs/types/errors.d.ts +15 -0
  136. package/dist/cjs/types/errors.d.ts.map +1 -0
  137. package/dist/cjs/types/errors.js +22 -0
  138. package/dist/cjs/types/errors.js.map +1 -0
  139. package/dist/cjs/types/flow.d.ts +513 -0
  140. package/dist/cjs/types/flow.d.ts.map +1 -0
  141. package/dist/cjs/types/{route.js → flow.js} +2 -2
  142. package/dist/cjs/types/flow.js.map +1 -0
  143. package/dist/cjs/types/index.d.ts +7 -6
  144. package/dist/cjs/types/index.d.ts.map +1 -1
  145. package/dist/cjs/types/index.js +6 -2
  146. package/dist/cjs/types/index.js.map +1 -1
  147. package/dist/cjs/types/persistence.d.ts +11 -7
  148. package/dist/cjs/types/persistence.d.ts.map +1 -1
  149. package/dist/cjs/types/routing.d.ts +1 -1
  150. package/dist/cjs/types/routing.d.ts.map +1 -1
  151. package/dist/cjs/types/session.d.ts +24 -23
  152. package/dist/cjs/types/session.d.ts.map +1 -1
  153. package/dist/cjs/types/signals.d.ts +248 -0
  154. package/dist/cjs/types/signals.d.ts.map +1 -0
  155. package/dist/cjs/types/signals.js +11 -0
  156. package/dist/cjs/types/signals.js.map +1 -0
  157. package/dist/cjs/types/template.d.ts +2 -8
  158. package/dist/cjs/types/template.d.ts.map +1 -1
  159. package/dist/cjs/types/tool.d.ts +36 -29
  160. package/dist/cjs/types/tool.d.ts.map +1 -1
  161. package/dist/cjs/types/tool.js +1 -1
  162. package/dist/cjs/types/tool.js.map +1 -1
  163. package/dist/cjs/utils/condition.d.ts +7 -1
  164. package/dist/cjs/utils/condition.d.ts.map +1 -1
  165. package/dist/cjs/utils/condition.js.map +1 -1
  166. package/dist/cjs/utils/id.d.ts +13 -5
  167. package/dist/cjs/utils/id.d.ts.map +1 -1
  168. package/dist/cjs/utils/id.js +24 -10
  169. package/dist/cjs/utils/id.js.map +1 -1
  170. package/dist/cjs/utils/index.d.ts +2 -2
  171. package/dist/cjs/utils/index.d.ts.map +1 -1
  172. package/dist/cjs/utils/index.js +7 -3
  173. package/dist/cjs/utils/index.js.map +1 -1
  174. package/dist/cjs/utils/session.d.ts +44 -5
  175. package/dist/cjs/utils/session.d.ts.map +1 -1
  176. package/dist/cjs/utils/session.js +197 -38
  177. package/dist/cjs/utils/session.js.map +1 -1
  178. package/dist/constants/index.d.ts +0 -9
  179. package/dist/constants/index.d.ts.map +1 -1
  180. package/dist/constants/index.js +3 -9
  181. package/dist/constants/index.js.map +1 -1
  182. package/dist/core/Agent.d.ts +119 -153
  183. package/dist/core/Agent.d.ts.map +1 -1
  184. package/dist/core/Agent.js +472 -325
  185. package/dist/core/Agent.js.map +1 -1
  186. package/dist/core/AutoChainExecutor.d.ts +107 -0
  187. package/dist/core/AutoChainExecutor.d.ts.map +1 -0
  188. package/dist/core/AutoChainExecutor.js +293 -0
  189. package/dist/core/AutoChainExecutor.js.map +1 -0
  190. package/dist/core/BranchEvaluator.d.ts +54 -0
  191. package/dist/core/BranchEvaluator.d.ts.map +1 -0
  192. package/dist/core/BranchEvaluator.js +126 -0
  193. package/dist/core/BranchEvaluator.js.map +1 -0
  194. package/dist/core/DirectiveBus.d.ts +88 -0
  195. package/dist/core/DirectiveBus.d.ts.map +1 -0
  196. package/dist/core/DirectiveBus.js +192 -0
  197. package/dist/core/DirectiveBus.js.map +1 -0
  198. package/dist/core/DirectiveChainTracker.d.ts +49 -0
  199. package/dist/core/DirectiveChainTracker.d.ts.map +1 -0
  200. package/dist/core/DirectiveChainTracker.js +117 -0
  201. package/dist/core/DirectiveChainTracker.js.map +1 -0
  202. package/dist/core/Flow.d.ts +186 -0
  203. package/dist/core/Flow.d.ts.map +1 -0
  204. package/dist/core/Flow.js +546 -0
  205. package/dist/core/Flow.js.map +1 -0
  206. package/dist/core/FlowRouter.d.ts +182 -0
  207. package/dist/core/FlowRouter.d.ts.map +1 -0
  208. package/dist/core/{RoutingEngine.js → FlowRouter.js} +322 -305
  209. package/dist/core/FlowRouter.js.map +1 -0
  210. package/dist/core/PersistenceManager.d.ts +2 -2
  211. package/dist/core/PersistenceManager.d.ts.map +1 -1
  212. package/dist/core/PersistenceManager.js +7 -7
  213. package/dist/core/PersistenceManager.js.map +1 -1
  214. package/dist/core/PromptComposer.d.ts +21 -8
  215. package/dist/core/PromptComposer.d.ts.map +1 -1
  216. package/dist/core/PromptComposer.js +183 -106
  217. package/dist/core/PromptComposer.js.map +1 -1
  218. package/dist/core/PromptSectionCache.d.ts +1 -1
  219. package/dist/core/PromptSectionCache.js +1 -1
  220. package/dist/core/ResponseEngine.d.ts +18 -8
  221. package/dist/core/ResponseEngine.d.ts.map +1 -1
  222. package/dist/core/ResponseEngine.js +38 -36
  223. package/dist/core/ResponseEngine.js.map +1 -1
  224. package/dist/core/ResponseModal.d.ts +73 -56
  225. package/dist/core/ResponseModal.d.ts.map +1 -1
  226. package/dist/core/ResponseModal.js +1198 -1017
  227. package/dist/core/ResponseModal.js.map +1 -1
  228. package/dist/core/ResponsePipeline.d.ts +124 -26
  229. package/dist/core/ResponsePipeline.d.ts.map +1 -1
  230. package/dist/core/ResponsePipeline.js +524 -135
  231. package/dist/core/ResponsePipeline.js.map +1 -1
  232. package/dist/core/SignalEvaluator.d.ts +86 -0
  233. package/dist/core/SignalEvaluator.d.ts.map +1 -0
  234. package/dist/core/SignalEvaluator.js +326 -0
  235. package/dist/core/SignalEvaluator.js.map +1 -0
  236. package/dist/core/SignalProcessor.d.ts +152 -0
  237. package/dist/core/SignalProcessor.d.ts.map +1 -0
  238. package/dist/core/SignalProcessor.js +555 -0
  239. package/dist/core/SignalProcessor.js.map +1 -0
  240. package/dist/core/Step.d.ts +43 -32
  241. package/dist/core/Step.d.ts.map +1 -1
  242. package/dist/core/Step.js +220 -126
  243. package/dist/core/Step.js.map +1 -1
  244. package/dist/core/StreamingToolExecutor.d.ts +2 -2
  245. package/dist/core/StreamingToolExecutor.d.ts.map +1 -1
  246. package/dist/core/StreamingToolExecutor.js.map +1 -1
  247. package/dist/core/ToolManager.d.ts +44 -13
  248. package/dist/core/ToolManager.d.ts.map +1 -1
  249. package/dist/core/ToolManager.js +174 -91
  250. package/dist/core/ToolManager.js.map +1 -1
  251. package/dist/core/createAgent.d.ts +35 -0
  252. package/dist/core/createAgent.d.ts.map +1 -0
  253. package/dist/core/createAgent.js +36 -0
  254. package/dist/core/createAgent.js.map +1 -0
  255. package/dist/core/flow-namespace.d.ts +49 -0
  256. package/dist/core/flow-namespace.d.ts.map +1 -0
  257. package/dist/core/flow-namespace.js +168 -0
  258. package/dist/core/flow-namespace.js.map +1 -0
  259. package/dist/index.d.ts +11 -14
  260. package/dist/index.d.ts.map +1 -1
  261. package/dist/index.js +9 -12
  262. package/dist/index.js.map +1 -1
  263. package/dist/providers/GeminiProvider.d.ts +3 -3
  264. package/dist/providers/GeminiProvider.d.ts.map +1 -1
  265. package/dist/providers/GeminiProvider.js +16 -14
  266. package/dist/providers/GeminiProvider.js.map +1 -1
  267. package/dist/types/agent.d.ts +183 -54
  268. package/dist/types/agent.d.ts.map +1 -1
  269. package/dist/types/agent.js +0 -6
  270. package/dist/types/agent.js.map +1 -1
  271. package/dist/types/ai.d.ts +3 -3
  272. package/dist/types/ai.d.ts.map +1 -1
  273. package/dist/types/errors.d.ts +15 -0
  274. package/dist/types/errors.d.ts.map +1 -0
  275. package/dist/types/errors.js +18 -0
  276. package/dist/types/errors.js.map +1 -0
  277. package/dist/types/flow.d.ts +513 -0
  278. package/dist/types/flow.d.ts.map +1 -0
  279. package/dist/types/flow.js +5 -0
  280. package/dist/types/flow.js.map +1 -0
  281. package/dist/types/index.d.ts +7 -6
  282. package/dist/types/index.d.ts.map +1 -1
  283. package/dist/types/index.js +4 -1
  284. package/dist/types/index.js.map +1 -1
  285. package/dist/types/persistence.d.ts +11 -7
  286. package/dist/types/persistence.d.ts.map +1 -1
  287. package/dist/types/routing.d.ts +1 -1
  288. package/dist/types/routing.d.ts.map +1 -1
  289. package/dist/types/session.d.ts +24 -23
  290. package/dist/types/session.d.ts.map +1 -1
  291. package/dist/types/signals.d.ts +248 -0
  292. package/dist/types/signals.d.ts.map +1 -0
  293. package/dist/types/signals.js +10 -0
  294. package/dist/types/signals.js.map +1 -0
  295. package/dist/types/template.d.ts +2 -8
  296. package/dist/types/template.d.ts.map +1 -1
  297. package/dist/types/tool.d.ts +36 -29
  298. package/dist/types/tool.d.ts.map +1 -1
  299. package/dist/types/tool.js +1 -1
  300. package/dist/types/tool.js.map +1 -1
  301. package/dist/utils/condition.d.ts +7 -1
  302. package/dist/utils/condition.d.ts.map +1 -1
  303. package/dist/utils/condition.js.map +1 -1
  304. package/dist/utils/id.d.ts +13 -5
  305. package/dist/utils/id.d.ts.map +1 -1
  306. package/dist/utils/id.js +22 -9
  307. package/dist/utils/id.js.map +1 -1
  308. package/dist/utils/index.d.ts +2 -2
  309. package/dist/utils/index.d.ts.map +1 -1
  310. package/dist/utils/index.js +2 -2
  311. package/dist/utils/index.js.map +1 -1
  312. package/dist/utils/session.d.ts +44 -5
  313. package/dist/utils/session.d.ts.map +1 -1
  314. package/dist/utils/session.js +193 -37
  315. package/dist/utils/session.js.map +1 -1
  316. package/docs/README.md +15 -202
  317. package/docs/concepts/architecture.md +281 -0
  318. package/docs/concepts/directives.md +400 -0
  319. package/docs/concepts/pipeline.md +399 -0
  320. package/docs/guides/branching.md +263 -0
  321. package/docs/guides/compaction.md +163 -0
  322. package/docs/guides/conditions.md +167 -0
  323. package/docs/guides/error-handling.md +176 -0
  324. package/docs/guides/flow-control.md +409 -0
  325. package/docs/guides/instructions.md +210 -0
  326. package/docs/guides/persistence.md +182 -0
  327. package/docs/guides/streaming.md +137 -0
  328. package/docs/migration/README.md +15 -0
  329. package/docs/migration/route-to-flow.md +560 -0
  330. package/docs/migration/v1-to-v2.md +909 -0
  331. package/docs/reference/adapters.md +481 -0
  332. package/docs/reference/branches.md +241 -0
  333. package/docs/reference/create-agent.md +186 -0
  334. package/docs/reference/directive.md +243 -0
  335. package/docs/reference/errors.md +122 -0
  336. package/docs/reference/flow.md +238 -0
  337. package/docs/reference/instruction.md +177 -0
  338. package/docs/reference/pre-directive.md +131 -0
  339. package/docs/reference/providers.md +227 -0
  340. package/docs/reference/signals.md +356 -0
  341. package/docs/reference/step.md +339 -0
  342. package/docs/reference/tool.md +269 -0
  343. package/docs/start/01-install.md +81 -0
  344. package/docs/start/02-first-agent.md +196 -0
  345. package/docs/start/03-collect-data.md +222 -0
  346. package/docs/start/04-add-tools.md +276 -0
  347. package/docs/start/05-go-to-production.md +216 -0
  348. package/examples/01-quickstart.ts +20 -0
  349. package/examples/02-data-extraction.ts +90 -0
  350. package/examples/03-tools.ts +136 -0
  351. package/examples/04-instructions.ts +100 -0
  352. package/examples/05-branching.ts +140 -0
  353. package/examples/06-flow-control.ts +103 -0
  354. package/examples/07-streaming.ts +69 -0
  355. package/examples/08-persistence.ts +98 -0
  356. package/examples/09-signals.ts +144 -0
  357. package/examples/tsconfig.json +30 -0
  358. package/package.json +2 -1
  359. package/src/adapters/MemoryAdapter.ts +3 -3
  360. package/src/adapters/MongoAdapter.ts +3 -3
  361. package/src/adapters/OpenSearchAdapter.ts +10 -8
  362. package/src/adapters/PostgreSQLAdapter.ts +26 -10
  363. package/src/adapters/PrismaAdapter.ts +6 -6
  364. package/src/adapters/RedisAdapter.ts +3 -3
  365. package/src/adapters/SQLiteAdapter.ts +31 -12
  366. package/src/constants/index.ts +2 -10
  367. package/src/core/Agent.ts +585 -374
  368. package/src/core/AutoChainExecutor.ts +440 -0
  369. package/src/core/BranchEvaluator.ts +167 -0
  370. package/src/core/DirectiveBus.ts +248 -0
  371. package/src/core/DirectiveChainTracker.ts +144 -0
  372. package/src/core/Flow.ts +666 -0
  373. package/src/core/{RoutingEngine.ts → FlowRouter.ts} +385 -365
  374. package/src/core/PersistenceManager.ts +8 -8
  375. package/src/core/PromptComposer.ts +209 -140
  376. package/src/core/PromptSectionCache.ts +1 -1
  377. package/src/core/ResponseEngine.ts +61 -46
  378. package/src/core/ResponseModal.ts +1458 -1241
  379. package/src/core/ResponsePipeline.ts +675 -173
  380. package/src/core/SignalEvaluator.ts +420 -0
  381. package/src/core/SignalProcessor.ts +723 -0
  382. package/src/core/Step.ts +279 -176
  383. package/src/core/StreamingToolExecutor.ts +4 -4
  384. package/src/core/ToolManager.ts +200 -97
  385. package/src/core/createAgent.ts +40 -0
  386. package/src/core/flow-namespace.ts +219 -0
  387. package/src/index.ts +42 -36
  388. package/src/providers/GeminiProvider.ts +17 -15
  389. package/src/types/agent.ts +182 -53
  390. package/src/types/ai.ts +3 -3
  391. package/src/types/errors.ts +18 -0
  392. package/src/types/flow.ts +590 -0
  393. package/src/types/index.ts +43 -16
  394. package/src/types/persistence.ts +12 -8
  395. package/src/types/routing.ts +1 -1
  396. package/src/types/session.ts +26 -23
  397. package/src/types/signals.ts +321 -0
  398. package/src/types/template.ts +3 -11
  399. package/src/types/tool.ts +50 -42
  400. package/src/utils/condition.ts +13 -4
  401. package/src/utils/id.ts +27 -9
  402. package/src/utils/index.ts +6 -2
  403. package/src/utils/session.ts +238 -42
  404. package/dist/cjs/core/BatchExecutor.d.ts +0 -359
  405. package/dist/cjs/core/BatchExecutor.d.ts.map +0 -1
  406. package/dist/cjs/core/BatchExecutor.js +0 -861
  407. package/dist/cjs/core/BatchExecutor.js.map +0 -1
  408. package/dist/cjs/core/BatchPromptBuilder.d.ts +0 -89
  409. package/dist/cjs/core/BatchPromptBuilder.d.ts.map +0 -1
  410. package/dist/cjs/core/BatchPromptBuilder.js +0 -223
  411. package/dist/cjs/core/BatchPromptBuilder.js.map +0 -1
  412. package/dist/cjs/core/Route.d.ts +0 -180
  413. package/dist/cjs/core/Route.d.ts.map +0 -1
  414. package/dist/cjs/core/Route.js +0 -542
  415. package/dist/cjs/core/Route.js.map +0 -1
  416. package/dist/cjs/core/RoutingEngine.d.ts +0 -185
  417. package/dist/cjs/core/RoutingEngine.d.ts.map +0 -1
  418. package/dist/cjs/core/RoutingEngine.js.map +0 -1
  419. package/dist/cjs/types/route.d.ts +0 -336
  420. package/dist/cjs/types/route.d.ts.map +0 -1
  421. package/dist/cjs/types/route.js.map +0 -1
  422. package/dist/core/BatchExecutor.d.ts +0 -359
  423. package/dist/core/BatchExecutor.d.ts.map +0 -1
  424. package/dist/core/BatchExecutor.js +0 -856
  425. package/dist/core/BatchExecutor.js.map +0 -1
  426. package/dist/core/BatchPromptBuilder.d.ts +0 -89
  427. package/dist/core/BatchPromptBuilder.d.ts.map +0 -1
  428. package/dist/core/BatchPromptBuilder.js +0 -219
  429. package/dist/core/BatchPromptBuilder.js.map +0 -1
  430. package/dist/core/Route.d.ts +0 -180
  431. package/dist/core/Route.d.ts.map +0 -1
  432. package/dist/core/Route.js +0 -538
  433. package/dist/core/Route.js.map +0 -1
  434. package/dist/core/RoutingEngine.d.ts +0 -185
  435. package/dist/core/RoutingEngine.d.ts.map +0 -1
  436. package/dist/core/RoutingEngine.js.map +0 -1
  437. package/dist/types/route.d.ts +0 -336
  438. package/dist/types/route.d.ts.map +0 -1
  439. package/dist/types/route.js +0 -5
  440. package/dist/types/route.js.map +0 -1
  441. package/docs/CONTRIBUTING.md +0 -521
  442. package/docs/api/README.md +0 -3299
  443. package/docs/api/overview.md +0 -1410
  444. package/docs/architecture/data-extraction-flow.md +0 -360
  445. package/docs/architecture/multi-step-execution.md +0 -277
  446. package/docs/core/agent/README.md +0 -938
  447. package/docs/core/agent/context-management.md +0 -796
  448. package/docs/core/agent/rules-and-prohibitions.md +0 -113
  449. package/docs/core/agent/session-management.md +0 -693
  450. package/docs/core/ai-integration/prompt-composition.md +0 -355
  451. package/docs/core/ai-integration/providers.md +0 -515
  452. package/docs/core/ai-integration/response-processing.md +0 -433
  453. package/docs/core/conversation-flows/data-collection.md +0 -772
  454. package/docs/core/conversation-flows/route-dsl.md +0 -509
  455. package/docs/core/conversation-flows/routes.md +0 -249
  456. package/docs/core/conversation-flows/step-transitions.md +0 -731
  457. package/docs/core/conversation-flows/steps.md +0 -268
  458. package/docs/core/error-handling.md +0 -830
  459. package/docs/core/persistence/adapters.md +0 -255
  460. package/docs/core/persistence/session-storage.md +0 -656
  461. package/docs/core/routing/intelligent-routing.md +0 -470
  462. package/docs/core/tools/enhanced-tool.md +0 -186
  463. package/docs/core/tools/streaming-execution.md +0 -161
  464. package/docs/core/tools/tool-definition.md +0 -970
  465. package/docs/core/tools/tool-scoping.md +0 -819
  466. package/docs/guides/advanced-patterns/publishing.md +0 -186
  467. package/docs/guides/context-compaction.md +0 -96
  468. package/docs/guides/error-handling-patterns.md +0 -578
  469. package/docs/guides/getting-started/README.md +0 -795
  470. package/docs/guides/migration/README.md +0 -101
  471. package/docs/guides/migration/flexible-routing-conditions.md +0 -375
  472. package/docs/guides/migration/multi-step-execution.md +0 -393
  473. package/docs/guides/migration/response-modal-refactor.md +0 -518
  474. package/docs/guides/prompt-optimization.md +0 -164
  475. package/examples/advanced-patterns/context-compaction.ts +0 -223
  476. package/examples/advanced-patterns/knowledge-based-agent.ts +0 -735
  477. package/examples/advanced-patterns/persistent-onboarding.ts +0 -728
  478. package/examples/advanced-patterns/route-lifecycle-hooks.ts +0 -556
  479. package/examples/advanced-patterns/streaming-responses.ts +0 -656
  480. package/examples/ai-providers/anthropic-integration.ts +0 -388
  481. package/examples/ai-providers/openai-integration.ts +0 -228
  482. package/examples/condition-patterns/function-only-conditions.ts +0 -365
  483. package/examples/condition-patterns/mixed-array-conditions.ts +0 -477
  484. package/examples/condition-patterns/route-skipif-patterns.ts +0 -468
  485. package/examples/condition-patterns/step-skipif-patterns.ts +0 -0
  486. package/examples/condition-patterns/string-only-conditions.ts +0 -296
  487. package/examples/conversation-flows/completion-transitions.ts +0 -318
  488. package/examples/core-concepts/basic-agent.ts +0 -503
  489. package/examples/core-concepts/modern-streaming-api.ts +0 -309
  490. package/examples/core-concepts/schema-driven-extraction.ts +0 -332
  491. package/examples/core-concepts/session-management.ts +0 -494
  492. package/examples/integrations/database-integration.ts +0 -631
  493. package/examples/integrations/healthcare-integration.ts +0 -595
  494. package/examples/integrations/search-integration.ts +0 -530
  495. package/examples/integrations/server-session-management.ts +0 -307
  496. package/examples/persistence/custom-adapter.ts +0 -526
  497. package/examples/persistence/database-persistence.ts +0 -583
  498. package/examples/persistence/memory-sessions.ts +0 -495
  499. package/examples/persistence/prisma-schema.example.prisma +0 -74
  500. package/examples/persistence/redis-persistence.ts +0 -488
  501. package/examples/tools/basic-tools.ts +0 -765
  502. package/examples/tools/data-enrichment-tools.ts +0 -593
  503. package/examples/tools/enhanced-tool-metadata.ts +0 -268
  504. package/examples/tools/streaming-tool-execution.ts +0 -283
  505. package/src/core/BatchExecutor.ts +0 -1187
  506. package/src/core/BatchPromptBuilder.ts +0 -299
  507. package/src/core/Route.ts +0 -678
  508. package/src/types/route.ts +0 -392
@@ -1,765 +0,0 @@
1
- /**
2
- * Basic Tools Example
3
- *
4
- * This example demonstrates the fundamentals of creating and using tools
5
- * with the unified Tool interface. Shows different patterns for tool creation,
6
- * execution, error handling, and integration with conversation flows.
7
- *
8
- * Key concepts:
9
- * - Multiple ways to create and use tools with unified interface
10
- * - Different tool handler patterns and return types
11
- * - Tool registration and scoping approaches
12
- * - Error handling in tools
13
- * - Tool results and data flow
14
- */
15
-
16
- import { Agent, GeminiProvider, Tool, ToolContext } from "../../src/index";
17
-
18
- // Define data types for our examples
19
- interface CalculatorData {
20
- expression: string;
21
- result?: number;
22
- operation?: string;
23
- }
24
-
25
- interface WeatherData {
26
- location: string;
27
- temperature?: number;
28
- condition?: string;
29
- forecast?: string;
30
- }
31
-
32
- interface SearchData {
33
- query: string;
34
- results?: string[];
35
- source?: string;
36
- }
37
-
38
- // Example 1: Inline Tool Definition (most common pattern)
39
- // This shows creating a tool object directly without explicit typing
40
- const calculatorTool = {
41
- id: "calculator",
42
- name: "Math Calculator",
43
- description: "Evaluate mathematical expressions and return results",
44
- parameters: {
45
- type: "object",
46
- properties: {
47
- expression: {
48
- type: "string",
49
- description: "Mathematical expression to evaluate",
50
- },
51
- },
52
- required: ["expression"],
53
- },
54
- handler: async (context: ToolContext<{ preferences?: { theme: string; language: string } }, UnifiedToolData>, args?: Record<string, unknown>) => {
55
- const expression = args?.expression as string;
56
- if (!expression) {
57
- throw new Error("No expression provided");
58
- }
59
-
60
- try {
61
- // Simple expression evaluation (in production, use a safe math library)
62
- // WARNING: eval is unsafe - use a proper math evaluation library in production
63
- const result = eval(expression);
64
-
65
- if (typeof result !== "number" || isNaN(result)) {
66
- throw new Error("Invalid calculation result");
67
- }
68
-
69
- return {
70
- data: `The result of ${expression} is ${result}`,
71
- dataUpdate: {
72
- expression,
73
- result,
74
- operation: expression,
75
- },
76
- };
77
- } catch (error) {
78
- throw new Error(
79
- `Error calculating ${expression}: ${error instanceof Error ? error.message : "Unknown error"
80
- }`
81
- );
82
- }
83
- },
84
- };
85
-
86
- // Example 2: Explicitly Typed Tool (for better IDE support and type safety)
87
- const weatherTool: Tool<{ preferences?: { theme: string; language: string } }, UnifiedToolData> = {
88
- id: "get_weather",
89
- name: "Weather Lookup",
90
- description: "Get current weather and forecast for a location",
91
- parameters: {
92
- type: "object",
93
- properties: {
94
- location: { type: "string", description: "City name for weather lookup" },
95
- },
96
- required: ["location"],
97
- },
98
- handler: async (context, args) => {
99
- const location = args?.location as string;
100
- if (!location) {
101
- throw new Error("No location provided");
102
- }
103
-
104
- // Simulate API call delay
105
- await new Promise((resolve) => setTimeout(resolve, 500));
106
-
107
- // Mock weather data based on location
108
- const mockWeather: Record<
109
- string,
110
- { temp: number; condition: string; forecast: string }
111
- > = {
112
- "New York": {
113
- temp: 72,
114
- condition: "Sunny",
115
- forecast: "Clear skies all week",
116
- },
117
- London: { temp: 55, condition: "Rainy", forecast: "Showers expected" },
118
- Tokyo: {
119
- temp: 78,
120
- condition: "Cloudy",
121
- forecast: "Partly cloudy with showers",
122
- },
123
- Sydney: {
124
- temp: 68,
125
- condition: "Clear",
126
- forecast: "Beautiful weather ahead",
127
- },
128
- };
129
-
130
- const weather = mockWeather[location] || {
131
- temp: 70,
132
- condition: "Unknown",
133
- forecast: "Weather data unavailable",
134
- };
135
-
136
- return {
137
- data: `Weather in ${location}: ${weather.temp}°F and ${weather.condition}. ${weather.forecast}`,
138
- dataUpdate: {
139
- location,
140
- temperature: weather.temp,
141
- condition: weather.condition,
142
- forecast: weather.forecast,
143
- },
144
- };
145
- },
146
- };
147
-
148
- // Example 3: Simple Return Value (just return a string for simple tools)
149
- const searchTool = {
150
- id: "web_search",
151
- name: "Web Search",
152
- description: "Search the web for information on a given query",
153
- parameters: {
154
- type: "object",
155
- properties: {
156
- query: { type: "string", description: "Search query to look up" },
157
- },
158
- required: ["query"],
159
- },
160
- handler: async (context: ToolContext<any, any>, args?: Record<string, unknown>) => {
161
- const query = args?.query as string;
162
- if (!query) {
163
- throw new Error("No search query provided");
164
- }
165
-
166
- // Simulate search API call
167
- await new Promise((resolve) => setTimeout(resolve, 800));
168
-
169
- // Mock search results
170
- const mockResults: Record<string, string[]> = {
171
- "artificial intelligence": [
172
- "AI is transforming industries worldwide",
173
- "Machine learning algorithms power modern AI",
174
- "Neural networks are the foundation of deep learning",
175
- "AI ethics and responsible development are crucial",
176
- ],
177
- "climate change": [
178
- "Global temperatures are rising at an unprecedented rate",
179
- "Renewable energy adoption is accelerating",
180
- "Biodiversity loss is a major concern",
181
- "International cooperation is essential for climate action",
182
- ],
183
- "space exploration": [
184
- "Mars missions are advancing rapidly",
185
- "Private companies are leading space innovation",
186
- "International Space Station continues operations",
187
- "Lunar exploration plans are being developed",
188
- ],
189
- };
190
-
191
- const results = mockResults[query.toLowerCase()] || [
192
- `Search results for "${query}"`,
193
- "This is a simulated search result",
194
- "In a real implementation, this would connect to a search API",
195
- "Such as Google Custom Search, Bing Web Search, or Elasticsearch",
196
- ];
197
-
198
- // Simple return - just the message (no dataUpdate needed for this example)
199
- return `Search results for "${query}":\n${results
200
- .map((r, i) => `${i + 1}. ${r}`)
201
- .join("\n")}`;
202
- },
203
- };
204
-
205
- // Example 4: ToolResult Return Type (for complex tools that need context/data updates)
206
- const updatePreferencesTool = {
207
- id: "update_preferences",
208
- name: "Update Preferences",
209
- description: "Update user preferences and settings",
210
- parameters: {
211
- type: "object",
212
- properties: {
213
- theme: { type: "string", enum: ["light", "dark"] },
214
- language: { type: "string", enum: ["en", "es", "fr"] },
215
- },
216
- },
217
- handler: async (toolContext: ToolContext<{ preferences?: { theme: string; language: string } }, UnifiedToolData>, args?: Record<string, unknown>) => {
218
- if (!toolContext.context) {
219
- throw new Error("No context available");
220
- }
221
-
222
- const newPreferences = {
223
- theme: (args?.theme as string) || toolContext.context.preferences?.theme || "light",
224
- language: (args?.language as string) || toolContext.context.preferences?.language || "en",
225
- };
226
-
227
- // Return ToolResult for complex updates
228
- return {
229
- data: `Preferences updated: Theme is now ${newPreferences.theme}, Language is ${newPreferences.language}`,
230
- contextUpdate: {
231
- preferences: newPreferences,
232
- },
233
- dataUpdate: {
234
- theme: newPreferences.theme,
235
- language: newPreferences.language,
236
- },
237
- };
238
- },
239
- };
240
-
241
- // Example 5: Function-style Tool Creation (for dynamic tools)
242
- function createValidationTool(fieldName: string) {
243
- return {
244
- id: `validate_${fieldName}`,
245
- name: `${fieldName} Validator`,
246
- description: `Validate the ${fieldName} field`,
247
- parameters: {
248
- type: "object",
249
- properties: {
250
- value: { type: "string", description: `Value to validate for ${fieldName}` },
251
- },
252
- required: ["value"],
253
- },
254
- handler: (context: ToolContext<any, any>, args?: Record<string, unknown>) => {
255
- const value = args?.value as string;
256
- const isValid = value && value.length > 0;
257
-
258
- if (isValid) {
259
- return `${fieldName} validation passed: ${value}`;
260
- } else {
261
- throw new Error(`${fieldName} validation failed: empty or invalid value`);
262
- }
263
- },
264
- };
265
- }
266
-
267
- // Example 6: Class-based Tool (for complex stateful tools)
268
- class ApiCallTool {
269
- constructor(private baseUrl: string, private apiKey: string) { }
270
-
271
- createTool() {
272
- return {
273
- id: "api_call",
274
- name: "API Call Tool",
275
- description: "Make API calls to external services",
276
- parameters: {
277
- type: "object",
278
- properties: {
279
- endpoint: { type: "string", description: "API endpoint to call" },
280
- method: { type: "string", enum: ["GET", "POST", "PUT", "DELETE"], default: "GET" },
281
- },
282
- required: ["endpoint"],
283
- },
284
- handler: async (_context: ToolContext<any, any>, args?: Record<string, unknown>) => {
285
- const endpoint = args?.endpoint as string;
286
- const method = (args?.method as string) || "GET";
287
-
288
- // Simulate API call
289
- console.log(`Making ${method} request to ${this.baseUrl}${endpoint}`);
290
-
291
- return {
292
- data: `API call successful: ${method} ${this.baseUrl}${endpoint}`,
293
- dataUpdate: {
294
- source: `API: ${this.baseUrl}${endpoint}`,
295
- },
296
- };
297
- },
298
- };
299
- }
300
- }
301
-
302
- // Define unified data schema for all tool interactions
303
- interface UnifiedToolData extends CalculatorData, WeatherData, SearchData {
304
- theme?: string;
305
- language?: string;
306
- }
307
-
308
- const unifiedToolSchema = {
309
- type: "object",
310
- properties: {
311
- // Calculator fields
312
- expression: { type: "string" },
313
- result: { type: "number" },
314
- operation: { type: "string" },
315
- // Weather fields
316
- location: { type: "string" },
317
- temperature: { type: "number" },
318
- condition: { type: "string" },
319
- forecast: { type: "string" },
320
- // Search fields
321
- query: { type: "string" },
322
- results: { type: "array", items: { type: "string" } },
323
- source: { type: "string" },
324
- // Preferences fields
325
- theme: { type: "string", enum: ["light", "dark"] },
326
- language: { type: "string", enum: ["en", "es", "fr"] },
327
- },
328
- };
329
-
330
- // Create agent with tools using new ToolManager API
331
- const agent = new Agent<{ preferences?: { theme: string; language: string } }, UnifiedToolData>({
332
- name: "ToolBot",
333
- description: "An agent demonstrating various tool capabilities",
334
- provider: new GeminiProvider({
335
- apiKey: process.env.GEMINI_API_KEY!,
336
- model: "models/gemini-2.5-flash",
337
- }),
338
- // NEW: Agent-level schema
339
- schema: unifiedToolSchema,
340
- });
341
-
342
- // Demonstrate ALL the different ways to add tools with the unified interface
343
-
344
- // Method 1: Direct addTool() - most common for individual tools
345
- agent.addTool(calculatorTool);
346
- agent.addTool(weatherTool);
347
-
348
- // Method 2: tool.register() - register for later reference by ID
349
- agent.tool.register(searchTool);
350
- agent.tool.register(updatePreferencesTool);
351
-
352
- // Method 3: tool.registerMany() - register multiple tools at once
353
- agent.tool.registerMany([
354
- createValidationTool("email"),
355
- createValidationTool("phone"),
356
- ]);
357
-
358
- // Method 4: tool.create() - create and register in one step
359
- const greetingTool = agent.tool.create({
360
- id: "greeting_tool",
361
- description: "Generate personalized greetings",
362
- handler: (context) => {
363
- const name = context.context?.preferences?.language === "es" ? "Hola" : "Hello";
364
- return `${name}! How can I help you today?`;
365
- },
366
- });
367
-
368
- // Method 5: tool.createDataEnrichment() - specialized for data enrichment
369
- const dataEnrichmentTool = agent.tool.createDataEnrichment({
370
- id: "enrich_user_data",
371
- fields: ["expression", "location"] as const,
372
- enricher: async (context, data) => {
373
- // Enrich the data with additional information that matches UnifiedToolData
374
- return {
375
- source: "basic-tools-example", // This matches the 'source' field in UnifiedToolData
376
- };
377
- },
378
- });
379
-
380
- // Method 6: tool.createValidation() - specialized for validation
381
- const validationTool = agent.tool.createValidation({
382
- id: "validate_input",
383
- fields: ["expression"] as const,
384
- validator: async (context, data) => {
385
- if (!data.expression || data.expression.length < 1) {
386
- return {
387
- valid: false,
388
- errors: [{
389
- field: "expression",
390
- value: data.expression,
391
- message: "Expression cannot be empty",
392
- schemaPath: "expression"
393
- }],
394
- warnings: [],
395
- };
396
- }
397
- return {
398
- valid: true,
399
- errors: [],
400
- warnings: [],
401
- };
402
- },
403
- });
404
-
405
- // Method 7: Class-based tools with addTool
406
- const apiTool = new ApiCallTool("https://api.example.com", "your-api-key");
407
- agent.addTool(apiTool.createTool());
408
-
409
- // Create routes that use different tools (now referencing registered tools by ID)
410
- agent.createRoute({
411
- title: "Calculator",
412
- description: "Mathematical calculations",
413
- // NEW: Required fields for route completion
414
- requiredFields: ["expression"],
415
- // NEW: Optional fields that enhance the experience
416
- optionalFields: ["result", "operation"],
417
- steps: [
418
- {
419
- id: "get_expression",
420
- description: "Ask for mathematical expression",
421
- prompt:
422
- "I can help you with calculations. What would you like to calculate?",
423
- collect: ["expression"],
424
- },
425
- {
426
- id: "calculate",
427
- description: "Perform the calculation",
428
- prompt: "Let me calculate that for you.",
429
- tools: ["calculator"], // Reference registered tool by ID
430
- requires: ["expression"],
431
- },
432
- ],
433
- });
434
-
435
- agent.createRoute({
436
- title: "Weather",
437
- description: "Weather information",
438
- // NEW: Required fields for route completion
439
- requiredFields: ["location"],
440
- // NEW: Optional fields that enhance the experience
441
- optionalFields: ["temperature", "condition", "forecast"],
442
- steps: [
443
- {
444
- id: "get_location",
445
- description: "Ask for location",
446
- prompt:
447
- "I can check the weather for you. Which city are you interested in?",
448
- collect: ["location"],
449
- },
450
- {
451
- id: "get_weather",
452
- description: "Fetch weather data",
453
- prompt: "Let me check the weather for you.",
454
- tools: ["get_weather"], // Reference registered tool by ID
455
- requires: ["location"],
456
- },
457
- ],
458
- });
459
-
460
- agent.createRoute({
461
- title: "Web Search",
462
- description: "Information search",
463
- // NEW: Required fields for route completion
464
- requiredFields: ["query"],
465
- // NEW: Optional fields that enhance the experience
466
- optionalFields: ["results", "source"],
467
- steps: [
468
- {
469
- id: "get_query",
470
- description: "Ask for search query",
471
- prompt:
472
- "I can search for information on the web. What would you like to search for?",
473
- collect: ["query"],
474
- },
475
- {
476
- id: "perform_search",
477
- description: "Execute the search",
478
- prompt: "Let me search for that information.",
479
- tools: ["web_search"], // Reference registered tool by ID
480
- requires: ["query"],
481
- },
482
- ],
483
- });
484
-
485
- // Create a route for preferences management
486
- agent.createRoute({
487
- title: "Preferences",
488
- description: "Update user preferences",
489
- steps: [
490
- {
491
- id: "update_prefs",
492
- description: "Update user preferences",
493
- prompt: "I can help you update your preferences.",
494
- tools: ["update_preferences"], // Reference registered tool by ID
495
- },
496
- ],
497
- });
498
-
499
- // Demonstrate basic tool usage
500
- async function demonstrateBasicTools() {
501
- console.log("=== Basic Tools Demo ===\n");
502
-
503
- // Calculator tool
504
- console.log("1. Calculator Tool:");
505
- console.log("User: Calculate 15 * 23 + 7");
506
- const calcResponse = await agent.respond({
507
- history: [],
508
- });
509
- console.log("Bot:", calcResponse.message);
510
- console.log(
511
- "Calculated result:",
512
- calcResponse.session?.data?.result
513
- );
514
- console.log();
515
-
516
- // Weather tool
517
- console.log("2. Weather Tool:");
518
- console.log("User: What's the weather like in Tokyo?");
519
- const weatherResponse = await agent.respond({
520
- history: [{ role: "user", content: "What's the weather like in Tokyo?" }],
521
- });
522
- console.log("Bot:", weatherResponse.message);
523
- console.log("Weather data:", {
524
- temperature: (weatherResponse.session?.data as Partial<UnifiedToolData>)
525
- ?.temperature,
526
- condition: (weatherResponse.session?.data as Partial<UnifiedToolData>)
527
- ?.condition,
528
- });
529
- console.log();
530
-
531
- // Search tool
532
- console.log("3. Search Tool:");
533
- console.log("User: Search for information about artificial intelligence");
534
- const searchResponse = await agent.respond({
535
- history: [
536
- {
537
- role: "user",
538
- content: "Search for information about artificial intelligence",
539
- },
540
- ],
541
- });
542
- console.log("Bot:", searchResponse.message);
543
- console.log(
544
- "Search results count:",
545
- (searchResponse.session?.data as Partial<UnifiedToolData>)?.results?.length
546
- );
547
- }
548
-
549
- // Demonstrate tool error handling
550
- async function demonstrateToolErrors() {
551
- console.log("\n=== Tool Error Handling Demo ===\n");
552
-
553
- // Invalid calculation
554
- console.log("1. Invalid Calculation:");
555
- console.log("User: Calculate xyz + 123");
556
- const errorResponse1 = await agent.respond({
557
- history: [],
558
- });
559
- console.log("Bot:", errorResponse1.message);
560
- console.log();
561
-
562
- // Missing location for weather
563
- console.log("2. Missing Parameters:");
564
- console.log("User: What's the weather?"); // No location specified
565
- const errorResponse2 = await agent.respond({
566
- history: [],
567
- });
568
- console.log("Bot:", errorResponse2.message);
569
- console.log();
570
-
571
- // Empty search query
572
- console.log("3. Empty Search Query:");
573
- console.log("User: Search for"); // Empty query
574
- const errorResponse3 = await agent.respond({
575
- history: [{ role: "user", content: "Search for" }],
576
- });
577
- console.log("Bot:", errorResponse3.message);
578
- }
579
-
580
- // Demonstrate tool data flow
581
- async function demonstrateToolDataFlow() {
582
- console.log("\n=== Tool Data Flow Demo ===\n");
583
-
584
- console.log("Showing how tool results flow through the conversation...");
585
-
586
- // Start with calculation
587
- const response1 = await agent.respond({
588
- history: [],
589
- });
590
-
591
- console.log("1. Initial calculation:");
592
- console.log(
593
- " User input collected:",
594
- (response1.session?.data as Partial<UnifiedToolData>)?.expression
595
- );
596
- console.log(
597
- " Tool result:",
598
- (response1.session?.data as Partial<UnifiedToolData>)?.result
599
- );
600
- console.log(
601
- " Operation stored:",
602
- (response1.session?.data as Partial<UnifiedToolData>)?.operation
603
- );
604
-
605
- // Follow up question using previous result
606
- const response2 = await agent.respond({
607
- history: [
608
- { role: "user", content: "Now add 100 to that result", name: "Alice" },
609
- ],
610
- session: response1.session,
611
- });
612
-
613
- console.log("\n2. Follow-up calculation:");
614
- console.log(
615
- " Previous result available:",
616
- (response2.session?.data as Partial<UnifiedToolData>)?.result
617
- );
618
- console.log(" Bot response:", response2.message);
619
- }
620
-
621
- // Show tool definition patterns
622
- function demonstrateToolPatterns() {
623
- console.log("\n=== Tool Definition Patterns ===\n");
624
-
625
- console.log("1. Multiple Tool Creation Patterns:");
626
- console.log(`
627
- // Pattern A: Inline tool definition (most common)
628
- const myTool = {
629
- id: "tool_name",
630
- description: "What this tool does",
631
- handler: (context, args) => "Simple result"
632
- };
633
-
634
- // Pattern B: Explicitly typed tool (better IDE support)
635
- const typedTool: Tool<MyContext, MyData> = {
636
- id: "typed_tool",
637
- description: "Typed tool with full IntelliSense",
638
- handler: (context, args) => ({
639
- data: "Result with updates",
640
- dataUpdate: { field: "value" },
641
- contextUpdate: { setting: "new" }
642
- })
643
- };
644
-
645
- // Pattern C: Function factory for dynamic tools
646
- function createTool(name: string) {
647
- return {
648
- id: name,
649
- handler: () => \`Tool \${name} executed\`
650
- };
651
- }
652
-
653
- // Pattern D: Class-based tools for complex logic
654
- class MyToolClass {
655
- createTool() {
656
- return {
657
- id: "class_tool",
658
- handler: (context, args) => this.processData(args)
659
- };
660
- }
661
-
662
- private processData(args: any) {
663
- return "Processed data from class method";
664
- }
665
- }
666
- `);
667
-
668
- console.log("2. Multiple Return Types Supported:");
669
- console.log(`
670
- // Return Type A: Simple string (for basic tools)
671
- handler: () => "Simple result message"
672
-
673
- // Return Type B: ToolResult object (for complex tools)
674
- handler: (context, args) => ({
675
- data: "User message",
676
- dataUpdate: { field: "value" },
677
- contextUpdate: { setting: "new" }
678
- })
679
-
680
- // Return Type C: Promise for async operations
681
- handler: async (context, args) => {
682
- const result = await apiCall();
683
- return \`Got: \${result}\`;
684
- }
685
-
686
- // Return Type D: Mixed - can return string OR ToolResult
687
- handler: (context, args) => {
688
- if (simple) return "Quick result";
689
- return { data: "Complex result", dataUpdate: {...} };
690
- }
691
- `);
692
-
693
- console.log("3. All Available Tool Registration Methods:");
694
- console.log(`
695
- // Method 1: Direct addition (most common)
696
- agent.addTool(myTool);
697
-
698
- // Method 2: Register for ID-based reference
699
- agent.tool.register(myTool);
700
-
701
- // Method 3: Register multiple tools at once
702
- agent.tool.registerMany([tool1, tool2, tool3]);
703
-
704
- // Method 4: Create and register in one step
705
- const tool = agent.tool.create({
706
- id: "my_tool",
707
- handler: () => "result"
708
- });
709
-
710
- // Method 5: Specialized data enrichment tools
711
- const enricher = agent.tool.createDataEnrichment({
712
- id: "enrich_data",
713
- fields: ["field1", "field2"],
714
- enricher: async (context, data) => ({ enriched: true })
715
- });
716
-
717
- // Method 6: Specialized validation tools
718
- const validator = agent.tool.createValidation({
719
- id: "validate_data",
720
- fields: ["field1"],
721
- validator: async (context, data) => data.field1 !== undefined
722
- });
723
-
724
- // Method 7: Route-scoped tools
725
- route.addTool(routeSpecificTool);
726
-
727
- // Method 8: Step-level tools
728
- step.addTool(stepSpecificTool);
729
-
730
- // Usage in steps - multiple patterns
731
- route.step({
732
- tools: ["tool_id"], // By ID (from register)
733
- tools: [toolObject], // Direct object
734
- tools: ["id1", obj2, "id3"] // Mixed approaches
735
- });
736
- `);
737
-
738
- console.log("4. Unified Interface Benefits & Flexibility:");
739
- console.log(" • Single Tool interface supports ALL patterns");
740
- console.log(" • Choose the right pattern for your use case:");
741
- console.log(" - Inline objects for simple tools");
742
- console.log(" - Typed interfaces for complex tools");
743
- console.log(" - Functions for dynamic tool generation");
744
- console.log(" - Classes for stateful/complex logic");
745
- console.log(" • Flexible return types (string OR ToolResult)");
746
- console.log(" • Optional typing - use as much or as little as needed");
747
- console.log(" • Consistent handler signature across all patterns");
748
- console.log(" • Tool resolution across scopes (step → route → agent)");
749
- }
750
-
751
- // Run demonstrations
752
- async function main() {
753
- try {
754
- demonstrateToolPatterns();
755
- await demonstrateBasicTools();
756
- await demonstrateToolErrors();
757
- await demonstrateToolDataFlow();
758
- } catch (error) {
759
- console.error("Error:", error);
760
- }
761
- }
762
-
763
- if (import.meta.url === `file://${process.argv[1]}`) {
764
- main().catch(console.error);
765
- }