@falai/agent 1.2.8 → 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 (499) 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 +1191 -1014
  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 +509 -136
  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/types/agent.d.ts +183 -54
  126. package/dist/cjs/types/agent.d.ts.map +1 -1
  127. package/dist/cjs/types/agent.js +0 -6
  128. package/dist/cjs/types/agent.js.map +1 -1
  129. package/dist/cjs/types/ai.d.ts +3 -3
  130. package/dist/cjs/types/ai.d.ts.map +1 -1
  131. package/dist/cjs/types/errors.d.ts +15 -0
  132. package/dist/cjs/types/errors.d.ts.map +1 -0
  133. package/dist/cjs/types/errors.js +22 -0
  134. package/dist/cjs/types/errors.js.map +1 -0
  135. package/dist/cjs/types/flow.d.ts +513 -0
  136. package/dist/cjs/types/flow.d.ts.map +1 -0
  137. package/dist/cjs/types/{route.js → flow.js} +2 -2
  138. package/dist/cjs/types/flow.js.map +1 -0
  139. package/dist/cjs/types/index.d.ts +7 -6
  140. package/dist/cjs/types/index.d.ts.map +1 -1
  141. package/dist/cjs/types/index.js +6 -2
  142. package/dist/cjs/types/index.js.map +1 -1
  143. package/dist/cjs/types/persistence.d.ts +11 -7
  144. package/dist/cjs/types/persistence.d.ts.map +1 -1
  145. package/dist/cjs/types/routing.d.ts +1 -1
  146. package/dist/cjs/types/routing.d.ts.map +1 -1
  147. package/dist/cjs/types/session.d.ts +24 -23
  148. package/dist/cjs/types/session.d.ts.map +1 -1
  149. package/dist/cjs/types/signals.d.ts +248 -0
  150. package/dist/cjs/types/signals.d.ts.map +1 -0
  151. package/dist/cjs/types/signals.js +11 -0
  152. package/dist/cjs/types/signals.js.map +1 -0
  153. package/dist/cjs/types/template.d.ts +2 -8
  154. package/dist/cjs/types/template.d.ts.map +1 -1
  155. package/dist/cjs/types/tool.d.ts +36 -29
  156. package/dist/cjs/types/tool.d.ts.map +1 -1
  157. package/dist/cjs/types/tool.js +1 -1
  158. package/dist/cjs/types/tool.js.map +1 -1
  159. package/dist/cjs/utils/condition.d.ts +7 -1
  160. package/dist/cjs/utils/condition.d.ts.map +1 -1
  161. package/dist/cjs/utils/condition.js.map +1 -1
  162. package/dist/cjs/utils/id.d.ts +13 -5
  163. package/dist/cjs/utils/id.d.ts.map +1 -1
  164. package/dist/cjs/utils/id.js +24 -10
  165. package/dist/cjs/utils/id.js.map +1 -1
  166. package/dist/cjs/utils/index.d.ts +2 -2
  167. package/dist/cjs/utils/index.d.ts.map +1 -1
  168. package/dist/cjs/utils/index.js +7 -3
  169. package/dist/cjs/utils/index.js.map +1 -1
  170. package/dist/cjs/utils/session.d.ts +44 -5
  171. package/dist/cjs/utils/session.d.ts.map +1 -1
  172. package/dist/cjs/utils/session.js +197 -38
  173. package/dist/cjs/utils/session.js.map +1 -1
  174. package/dist/constants/index.d.ts +0 -9
  175. package/dist/constants/index.d.ts.map +1 -1
  176. package/dist/constants/index.js +3 -9
  177. package/dist/constants/index.js.map +1 -1
  178. package/dist/core/Agent.d.ts +119 -153
  179. package/dist/core/Agent.d.ts.map +1 -1
  180. package/dist/core/Agent.js +472 -325
  181. package/dist/core/Agent.js.map +1 -1
  182. package/dist/core/AutoChainExecutor.d.ts +107 -0
  183. package/dist/core/AutoChainExecutor.d.ts.map +1 -0
  184. package/dist/core/AutoChainExecutor.js +293 -0
  185. package/dist/core/AutoChainExecutor.js.map +1 -0
  186. package/dist/core/BranchEvaluator.d.ts +54 -0
  187. package/dist/core/BranchEvaluator.d.ts.map +1 -0
  188. package/dist/core/BranchEvaluator.js +126 -0
  189. package/dist/core/BranchEvaluator.js.map +1 -0
  190. package/dist/core/DirectiveBus.d.ts +88 -0
  191. package/dist/core/DirectiveBus.d.ts.map +1 -0
  192. package/dist/core/DirectiveBus.js +192 -0
  193. package/dist/core/DirectiveBus.js.map +1 -0
  194. package/dist/core/DirectiveChainTracker.d.ts +49 -0
  195. package/dist/core/DirectiveChainTracker.d.ts.map +1 -0
  196. package/dist/core/DirectiveChainTracker.js +117 -0
  197. package/dist/core/DirectiveChainTracker.js.map +1 -0
  198. package/dist/core/Flow.d.ts +186 -0
  199. package/dist/core/Flow.d.ts.map +1 -0
  200. package/dist/core/Flow.js +546 -0
  201. package/dist/core/Flow.js.map +1 -0
  202. package/dist/core/FlowRouter.d.ts +182 -0
  203. package/dist/core/FlowRouter.d.ts.map +1 -0
  204. package/dist/core/{RoutingEngine.js → FlowRouter.js} +322 -305
  205. package/dist/core/FlowRouter.js.map +1 -0
  206. package/dist/core/PersistenceManager.d.ts +2 -2
  207. package/dist/core/PersistenceManager.d.ts.map +1 -1
  208. package/dist/core/PersistenceManager.js +7 -7
  209. package/dist/core/PersistenceManager.js.map +1 -1
  210. package/dist/core/PromptComposer.d.ts +21 -8
  211. package/dist/core/PromptComposer.d.ts.map +1 -1
  212. package/dist/core/PromptComposer.js +183 -106
  213. package/dist/core/PromptComposer.js.map +1 -1
  214. package/dist/core/PromptSectionCache.d.ts +1 -1
  215. package/dist/core/PromptSectionCache.js +1 -1
  216. package/dist/core/ResponseEngine.d.ts +18 -8
  217. package/dist/core/ResponseEngine.d.ts.map +1 -1
  218. package/dist/core/ResponseEngine.js +38 -36
  219. package/dist/core/ResponseEngine.js.map +1 -1
  220. package/dist/core/ResponseModal.d.ts +73 -56
  221. package/dist/core/ResponseModal.d.ts.map +1 -1
  222. package/dist/core/ResponseModal.js +1193 -1016
  223. package/dist/core/ResponseModal.js.map +1 -1
  224. package/dist/core/ResponsePipeline.d.ts +124 -26
  225. package/dist/core/ResponsePipeline.d.ts.map +1 -1
  226. package/dist/core/ResponsePipeline.js +509 -137
  227. package/dist/core/ResponsePipeline.js.map +1 -1
  228. package/dist/core/SignalEvaluator.d.ts +86 -0
  229. package/dist/core/SignalEvaluator.d.ts.map +1 -0
  230. package/dist/core/SignalEvaluator.js +326 -0
  231. package/dist/core/SignalEvaluator.js.map +1 -0
  232. package/dist/core/SignalProcessor.d.ts +152 -0
  233. package/dist/core/SignalProcessor.d.ts.map +1 -0
  234. package/dist/core/SignalProcessor.js +555 -0
  235. package/dist/core/SignalProcessor.js.map +1 -0
  236. package/dist/core/Step.d.ts +43 -32
  237. package/dist/core/Step.d.ts.map +1 -1
  238. package/dist/core/Step.js +220 -126
  239. package/dist/core/Step.js.map +1 -1
  240. package/dist/core/StreamingToolExecutor.d.ts +2 -2
  241. package/dist/core/StreamingToolExecutor.d.ts.map +1 -1
  242. package/dist/core/StreamingToolExecutor.js.map +1 -1
  243. package/dist/core/ToolManager.d.ts +44 -13
  244. package/dist/core/ToolManager.d.ts.map +1 -1
  245. package/dist/core/ToolManager.js +174 -91
  246. package/dist/core/ToolManager.js.map +1 -1
  247. package/dist/core/createAgent.d.ts +35 -0
  248. package/dist/core/createAgent.d.ts.map +1 -0
  249. package/dist/core/createAgent.js +36 -0
  250. package/dist/core/createAgent.js.map +1 -0
  251. package/dist/core/flow-namespace.d.ts +49 -0
  252. package/dist/core/flow-namespace.d.ts.map +1 -0
  253. package/dist/core/flow-namespace.js +168 -0
  254. package/dist/core/flow-namespace.js.map +1 -0
  255. package/dist/index.d.ts +11 -14
  256. package/dist/index.d.ts.map +1 -1
  257. package/dist/index.js +9 -12
  258. package/dist/index.js.map +1 -1
  259. package/dist/types/agent.d.ts +183 -54
  260. package/dist/types/agent.d.ts.map +1 -1
  261. package/dist/types/agent.js +0 -6
  262. package/dist/types/agent.js.map +1 -1
  263. package/dist/types/ai.d.ts +3 -3
  264. package/dist/types/ai.d.ts.map +1 -1
  265. package/dist/types/errors.d.ts +15 -0
  266. package/dist/types/errors.d.ts.map +1 -0
  267. package/dist/types/errors.js +18 -0
  268. package/dist/types/errors.js.map +1 -0
  269. package/dist/types/flow.d.ts +513 -0
  270. package/dist/types/flow.d.ts.map +1 -0
  271. package/dist/types/flow.js +5 -0
  272. package/dist/types/flow.js.map +1 -0
  273. package/dist/types/index.d.ts +7 -6
  274. package/dist/types/index.d.ts.map +1 -1
  275. package/dist/types/index.js +4 -1
  276. package/dist/types/index.js.map +1 -1
  277. package/dist/types/persistence.d.ts +11 -7
  278. package/dist/types/persistence.d.ts.map +1 -1
  279. package/dist/types/routing.d.ts +1 -1
  280. package/dist/types/routing.d.ts.map +1 -1
  281. package/dist/types/session.d.ts +24 -23
  282. package/dist/types/session.d.ts.map +1 -1
  283. package/dist/types/signals.d.ts +248 -0
  284. package/dist/types/signals.d.ts.map +1 -0
  285. package/dist/types/signals.js +10 -0
  286. package/dist/types/signals.js.map +1 -0
  287. package/dist/types/template.d.ts +2 -8
  288. package/dist/types/template.d.ts.map +1 -1
  289. package/dist/types/tool.d.ts +36 -29
  290. package/dist/types/tool.d.ts.map +1 -1
  291. package/dist/types/tool.js +1 -1
  292. package/dist/types/tool.js.map +1 -1
  293. package/dist/utils/condition.d.ts +7 -1
  294. package/dist/utils/condition.d.ts.map +1 -1
  295. package/dist/utils/condition.js.map +1 -1
  296. package/dist/utils/id.d.ts +13 -5
  297. package/dist/utils/id.d.ts.map +1 -1
  298. package/dist/utils/id.js +22 -9
  299. package/dist/utils/id.js.map +1 -1
  300. package/dist/utils/index.d.ts +2 -2
  301. package/dist/utils/index.d.ts.map +1 -1
  302. package/dist/utils/index.js +2 -2
  303. package/dist/utils/index.js.map +1 -1
  304. package/dist/utils/session.d.ts +44 -5
  305. package/dist/utils/session.d.ts.map +1 -1
  306. package/dist/utils/session.js +193 -37
  307. package/dist/utils/session.js.map +1 -1
  308. package/docs/README.md +15 -202
  309. package/docs/concepts/architecture.md +281 -0
  310. package/docs/concepts/directives.md +400 -0
  311. package/docs/concepts/pipeline.md +399 -0
  312. package/docs/guides/branching.md +263 -0
  313. package/docs/guides/compaction.md +163 -0
  314. package/docs/guides/conditions.md +167 -0
  315. package/docs/guides/error-handling.md +176 -0
  316. package/docs/guides/flow-control.md +409 -0
  317. package/docs/guides/instructions.md +210 -0
  318. package/docs/guides/persistence.md +182 -0
  319. package/docs/guides/streaming.md +137 -0
  320. package/docs/migration/README.md +15 -0
  321. package/docs/migration/route-to-flow.md +560 -0
  322. package/docs/migration/v1-to-v2.md +909 -0
  323. package/docs/reference/adapters.md +481 -0
  324. package/docs/reference/branches.md +241 -0
  325. package/docs/reference/create-agent.md +186 -0
  326. package/docs/reference/directive.md +243 -0
  327. package/docs/reference/errors.md +122 -0
  328. package/docs/reference/flow.md +238 -0
  329. package/docs/reference/instruction.md +177 -0
  330. package/docs/reference/pre-directive.md +131 -0
  331. package/docs/reference/providers.md +227 -0
  332. package/docs/reference/signals.md +356 -0
  333. package/docs/reference/step.md +339 -0
  334. package/docs/reference/tool.md +269 -0
  335. package/docs/start/01-install.md +81 -0
  336. package/docs/start/02-first-agent.md +196 -0
  337. package/docs/start/03-collect-data.md +222 -0
  338. package/docs/start/04-add-tools.md +276 -0
  339. package/docs/start/05-go-to-production.md +216 -0
  340. package/examples/01-quickstart.ts +20 -0
  341. package/examples/02-data-extraction.ts +90 -0
  342. package/examples/03-tools.ts +136 -0
  343. package/examples/04-instructions.ts +100 -0
  344. package/examples/05-branching.ts +140 -0
  345. package/examples/06-flow-control.ts +103 -0
  346. package/examples/07-streaming.ts +69 -0
  347. package/examples/08-persistence.ts +98 -0
  348. package/examples/09-signals.ts +144 -0
  349. package/examples/tsconfig.json +30 -0
  350. package/package.json +2 -1
  351. package/src/adapters/MemoryAdapter.ts +3 -3
  352. package/src/adapters/MongoAdapter.ts +3 -3
  353. package/src/adapters/OpenSearchAdapter.ts +10 -8
  354. package/src/adapters/PostgreSQLAdapter.ts +26 -10
  355. package/src/adapters/PrismaAdapter.ts +6 -6
  356. package/src/adapters/RedisAdapter.ts +3 -3
  357. package/src/adapters/SQLiteAdapter.ts +31 -12
  358. package/src/constants/index.ts +2 -10
  359. package/src/core/Agent.ts +585 -374
  360. package/src/core/AutoChainExecutor.ts +440 -0
  361. package/src/core/BranchEvaluator.ts +167 -0
  362. package/src/core/DirectiveBus.ts +248 -0
  363. package/src/core/DirectiveChainTracker.ts +144 -0
  364. package/src/core/Flow.ts +666 -0
  365. package/src/core/{RoutingEngine.ts → FlowRouter.ts} +385 -365
  366. package/src/core/PersistenceManager.ts +8 -8
  367. package/src/core/PromptComposer.ts +209 -140
  368. package/src/core/PromptSectionCache.ts +1 -1
  369. package/src/core/ResponseEngine.ts +61 -46
  370. package/src/core/ResponseModal.ts +1453 -1240
  371. package/src/core/ResponsePipeline.ts +655 -175
  372. package/src/core/SignalEvaluator.ts +420 -0
  373. package/src/core/SignalProcessor.ts +723 -0
  374. package/src/core/Step.ts +279 -176
  375. package/src/core/StreamingToolExecutor.ts +4 -4
  376. package/src/core/ToolManager.ts +200 -97
  377. package/src/core/createAgent.ts +40 -0
  378. package/src/core/flow-namespace.ts +219 -0
  379. package/src/index.ts +42 -36
  380. package/src/types/agent.ts +182 -53
  381. package/src/types/ai.ts +3 -3
  382. package/src/types/errors.ts +18 -0
  383. package/src/types/flow.ts +590 -0
  384. package/src/types/index.ts +43 -16
  385. package/src/types/persistence.ts +12 -8
  386. package/src/types/routing.ts +1 -1
  387. package/src/types/session.ts +26 -23
  388. package/src/types/signals.ts +321 -0
  389. package/src/types/template.ts +3 -11
  390. package/src/types/tool.ts +50 -42
  391. package/src/utils/condition.ts +13 -4
  392. package/src/utils/id.ts +27 -9
  393. package/src/utils/index.ts +6 -2
  394. package/src/utils/session.ts +238 -42
  395. package/dist/cjs/core/BatchExecutor.d.ts +0 -359
  396. package/dist/cjs/core/BatchExecutor.d.ts.map +0 -1
  397. package/dist/cjs/core/BatchExecutor.js +0 -861
  398. package/dist/cjs/core/BatchExecutor.js.map +0 -1
  399. package/dist/cjs/core/BatchPromptBuilder.d.ts +0 -89
  400. package/dist/cjs/core/BatchPromptBuilder.d.ts.map +0 -1
  401. package/dist/cjs/core/BatchPromptBuilder.js +0 -223
  402. package/dist/cjs/core/BatchPromptBuilder.js.map +0 -1
  403. package/dist/cjs/core/Route.d.ts +0 -180
  404. package/dist/cjs/core/Route.d.ts.map +0 -1
  405. package/dist/cjs/core/Route.js +0 -542
  406. package/dist/cjs/core/Route.js.map +0 -1
  407. package/dist/cjs/core/RoutingEngine.d.ts +0 -185
  408. package/dist/cjs/core/RoutingEngine.d.ts.map +0 -1
  409. package/dist/cjs/core/RoutingEngine.js.map +0 -1
  410. package/dist/cjs/types/route.d.ts +0 -336
  411. package/dist/cjs/types/route.d.ts.map +0 -1
  412. package/dist/cjs/types/route.js.map +0 -1
  413. package/dist/core/BatchExecutor.d.ts +0 -359
  414. package/dist/core/BatchExecutor.d.ts.map +0 -1
  415. package/dist/core/BatchExecutor.js +0 -856
  416. package/dist/core/BatchExecutor.js.map +0 -1
  417. package/dist/core/BatchPromptBuilder.d.ts +0 -89
  418. package/dist/core/BatchPromptBuilder.d.ts.map +0 -1
  419. package/dist/core/BatchPromptBuilder.js +0 -219
  420. package/dist/core/BatchPromptBuilder.js.map +0 -1
  421. package/dist/core/Route.d.ts +0 -180
  422. package/dist/core/Route.d.ts.map +0 -1
  423. package/dist/core/Route.js +0 -538
  424. package/dist/core/Route.js.map +0 -1
  425. package/dist/core/RoutingEngine.d.ts +0 -185
  426. package/dist/core/RoutingEngine.d.ts.map +0 -1
  427. package/dist/core/RoutingEngine.js.map +0 -1
  428. package/dist/types/route.d.ts +0 -336
  429. package/dist/types/route.d.ts.map +0 -1
  430. package/dist/types/route.js +0 -5
  431. package/dist/types/route.js.map +0 -1
  432. package/docs/CONTRIBUTING.md +0 -521
  433. package/docs/api/README.md +0 -3299
  434. package/docs/api/overview.md +0 -1410
  435. package/docs/architecture/data-extraction-flow.md +0 -360
  436. package/docs/architecture/multi-step-execution.md +0 -277
  437. package/docs/core/agent/README.md +0 -938
  438. package/docs/core/agent/context-management.md +0 -796
  439. package/docs/core/agent/rules-and-prohibitions.md +0 -113
  440. package/docs/core/agent/session-management.md +0 -693
  441. package/docs/core/ai-integration/prompt-composition.md +0 -355
  442. package/docs/core/ai-integration/providers.md +0 -515
  443. package/docs/core/ai-integration/response-processing.md +0 -433
  444. package/docs/core/conversation-flows/data-collection.md +0 -772
  445. package/docs/core/conversation-flows/route-dsl.md +0 -509
  446. package/docs/core/conversation-flows/routes.md +0 -249
  447. package/docs/core/conversation-flows/step-transitions.md +0 -731
  448. package/docs/core/conversation-flows/steps.md +0 -268
  449. package/docs/core/error-handling.md +0 -830
  450. package/docs/core/persistence/adapters.md +0 -255
  451. package/docs/core/persistence/session-storage.md +0 -656
  452. package/docs/core/routing/intelligent-routing.md +0 -470
  453. package/docs/core/tools/enhanced-tool.md +0 -186
  454. package/docs/core/tools/streaming-execution.md +0 -161
  455. package/docs/core/tools/tool-definition.md +0 -970
  456. package/docs/core/tools/tool-scoping.md +0 -819
  457. package/docs/guides/advanced-patterns/publishing.md +0 -186
  458. package/docs/guides/context-compaction.md +0 -96
  459. package/docs/guides/error-handling-patterns.md +0 -578
  460. package/docs/guides/getting-started/README.md +0 -795
  461. package/docs/guides/migration/README.md +0 -101
  462. package/docs/guides/migration/flexible-routing-conditions.md +0 -375
  463. package/docs/guides/migration/multi-step-execution.md +0 -393
  464. package/docs/guides/migration/response-modal-refactor.md +0 -518
  465. package/docs/guides/prompt-optimization.md +0 -164
  466. package/examples/advanced-patterns/context-compaction.ts +0 -223
  467. package/examples/advanced-patterns/knowledge-based-agent.ts +0 -735
  468. package/examples/advanced-patterns/persistent-onboarding.ts +0 -728
  469. package/examples/advanced-patterns/route-lifecycle-hooks.ts +0 -556
  470. package/examples/advanced-patterns/streaming-responses.ts +0 -656
  471. package/examples/ai-providers/anthropic-integration.ts +0 -388
  472. package/examples/ai-providers/openai-integration.ts +0 -228
  473. package/examples/condition-patterns/function-only-conditions.ts +0 -365
  474. package/examples/condition-patterns/mixed-array-conditions.ts +0 -477
  475. package/examples/condition-patterns/route-skipif-patterns.ts +0 -468
  476. package/examples/condition-patterns/step-skipif-patterns.ts +0 -0
  477. package/examples/condition-patterns/string-only-conditions.ts +0 -296
  478. package/examples/conversation-flows/completion-transitions.ts +0 -318
  479. package/examples/core-concepts/basic-agent.ts +0 -503
  480. package/examples/core-concepts/modern-streaming-api.ts +0 -309
  481. package/examples/core-concepts/schema-driven-extraction.ts +0 -332
  482. package/examples/core-concepts/session-management.ts +0 -494
  483. package/examples/integrations/database-integration.ts +0 -631
  484. package/examples/integrations/healthcare-integration.ts +0 -595
  485. package/examples/integrations/search-integration.ts +0 -530
  486. package/examples/integrations/server-session-management.ts +0 -307
  487. package/examples/persistence/custom-adapter.ts +0 -526
  488. package/examples/persistence/database-persistence.ts +0 -583
  489. package/examples/persistence/memory-sessions.ts +0 -495
  490. package/examples/persistence/prisma-schema.example.prisma +0 -74
  491. package/examples/persistence/redis-persistence.ts +0 -488
  492. package/examples/tools/basic-tools.ts +0 -765
  493. package/examples/tools/data-enrichment-tools.ts +0 -593
  494. package/examples/tools/enhanced-tool-metadata.ts +0 -268
  495. package/examples/tools/streaming-tool-execution.ts +0 -283
  496. package/src/core/BatchExecutor.ts +0 -1187
  497. package/src/core/BatchPromptBuilder.ts +0 -299
  498. package/src/core/Route.ts +0 -678
  499. package/src/types/route.ts +0 -392
@@ -1,938 +0,0 @@
1
- # Agent Architecture
2
-
3
- ## Overview
4
-
5
- The `Agent<TContext, TData>` class is the central orchestrator of @falai/agent, providing a strongly-typed, context-aware AI agent framework with intelligent routing and agent-level schema-driven data collection.
6
-
7
- ## Core Responsibilities
8
-
9
- - **AI Provider Management**: Unified interface to multiple AI providers (OpenAI, Gemini, Anthropic, etc.)
10
- - **Intelligent Routing**: AI-powered route and step selection based on conversation context
11
- - **Context Lifecycle**: Dynamic context management with provider functions and lifecycle hooks
12
- - **Session Management**: Conversation state persistence and multi-turn dialogue support
13
- - **Tool Orchestration**: Hierarchical tool execution (agent → route → step level)
14
- - **Agent-Level Data Collection**: Centralized schema-driven information extraction shared across all routes
15
-
16
- ## Agent Configuration
17
-
18
- ### Basic Agent Setup
19
-
20
- ```typescript
21
- import { Agent, OpenAIProvider } from "@falai/agent";
22
-
23
- const agent = new Agent({
24
- name: "Customer Support Bot",
25
- description: "AI assistant for customer inquiries",
26
- provider: new OpenAIProvider({
27
- apiKey: process.env.OPENAI_API_KEY,
28
- model: "gpt-4",
29
- }),
30
- });
31
- ```
32
-
33
- ### Advanced Configuration
34
-
35
- ```typescript
36
- interface CustomerContext {
37
- userId: string;
38
- accountTier: "free" | "premium" | "enterprise";
39
- lastLogin: Date;
40
- preferences: {
41
- language: string;
42
- notifications: boolean;
43
- };
44
- }
45
-
46
- interface CustomerData {
47
- customerName?: string;
48
- email?: string;
49
- phone?: string;
50
- issueType?: 'booking' | 'billing' | 'technical' | 'other';
51
- issueDescription?: string;
52
- priority?: 'low' | 'medium' | 'high';
53
- rating?: number;
54
- comments?: string;
55
- }
56
-
57
- const agent = new Agent<CustomerContext, CustomerData>({
58
- // Identity
59
- name: "Premium Support Assistant",
60
- description: "24/7 AI support for premium customers",
61
- goal: "Resolve customer issues efficiently while maintaining satisfaction",
62
-
63
- // AI Provider with backup models
64
- provider: new OpenAIProvider({
65
- apiKey: process.env.OPENAI_API_KEY,
66
- model: "gpt-5",
67
- backupModels: ["gpt-4"],
68
- }),
69
-
70
- // Agent-level data schema (NEW)
71
- schema: {
72
- type: "object",
73
- properties: {
74
- customerName: { type: "string" },
75
- email: { type: "string", format: "email" },
76
- phone: { type: "string" },
77
- issueType: { type: "string", enum: ["booking", "billing", "technical", "other"] },
78
- issueDescription: { type: "string" },
79
- priority: { type: "string", enum: ["low", "medium", "high"] },
80
- rating: { type: "number", minimum: 1, maximum: 5 },
81
- comments: { type: "string" }
82
- }
83
- },
84
-
85
- // Static context (can be overridden by contextProvider)
86
- context: {
87
- userId: "anonymous",
88
- accountTier: "free",
89
- lastLogin: new Date(),
90
- preferences: {
91
- language: "en",
92
- notifications: true,
93
- },
94
- },
95
-
96
- // Dynamic context provider (takes precedence over static context)
97
- contextProvider: async () => {
98
- const user = await authenticateUser(request);
99
- return {
100
- userId: user.id,
101
- accountTier: user.tier,
102
- lastLogin: user.lastLogin,
103
- preferences: user.preferences,
104
- };
105
- },
106
-
107
- // Lifecycle hooks for context and data management
108
- hooks: {
109
- // Refresh context before each response
110
- beforeRespond: async (currentContext) => {
111
- const freshUser = await db.getUser(currentContext.userId);
112
- return {
113
- ...currentContext,
114
- accountTier: freshUser.tier,
115
- lastLogin: freshUser.lastLogin,
116
- };
117
- },
118
-
119
- // Handle context updates from tools or responses
120
- onContextUpdate: async (newContext, previousContext) => {
121
- if (newContext.accountTier !== previousContext.accountTier) {
122
- await auditLog.log({
123
- type: "tier_change",
124
- userId: newContext.userId,
125
- from: previousContext.accountTier,
126
- to: newContext.accountTier,
127
- });
128
- }
129
- },
130
-
131
- // Validate and enrich collected data (NEW: Agent-level data hooks)
132
- onDataUpdate: async (data, previousData) => {
133
- // Data validation against agent schema
134
- if (data.email && !isValidEmail(data.email)) {
135
- throw new Error("Invalid email format");
136
- }
137
-
138
- // Data enrichment using agent-level data
139
- if (data.customerName && !data.customerId) {
140
- data.customerId = await lookupCustomerId(data.customerName);
141
- }
142
-
143
- // Auto-set priority based on issue type
144
- if (data.issueType === 'billing' && !data.priority) {
145
- data.priority = 'high';
146
- }
147
-
148
- return data;
149
- },
150
- },
151
-
152
- // Optional sessionId for automatic session loading/creation
153
- sessionId: "user-123", // Agent will automatically load or create this session
154
-
155
- // Optional persistence configuration
156
- persistence: {
157
- adapter: new RedisAdapter(redisClient),
158
- autoSave: true, // Auto-save after each response
159
- userId: "global", // Or dynamic based on context
160
- },
161
-
162
- // Domain knowledge
163
- terms: [
164
- {
165
- name: "Premium Support",
166
- description: "24/7 priority assistance with 1-hour response guarantee",
167
- synonyms: ["priority support", "vip assistance"],
168
- },
169
- ],
170
-
171
- // Enhanced behavioral guidelines with ConditionTemplate
172
- guidelines: [
173
- {
174
- condition: [
175
- "Customer seems frustrated or upset", // AI context
176
- (ctx) => ctx.data?.priority === 'high' // Programmatic check
177
- ],
178
- action: "Apologize sincerely and offer to escalate to human agent",
179
- enabled: true,
180
- },
181
- {
182
- condition: (ctx) => ctx.accountTier === 'premium', // Function-only condition
183
- action: "Provide expedited service and additional options",
184
- enabled: true,
185
- },
186
- {
187
- condition: "User is asking for help with billing", // String-only condition
188
- action: "Be extra careful with financial information and offer phone support",
189
- enabled: true,
190
- },
191
- ],
192
-
193
- // Global tools available to all routes
194
- tools: [searchTool, userLookupTool],
195
-
196
- // Agent-wide rules (enforced in every route)
197
- rules: [
198
- "Always respond in the customer's language",
199
- "Confirm before taking any account action",
200
- ],
201
-
202
- // Agent-wide prohibitions (enforced in every route)
203
- prohibitions: [
204
- "Never share internal system details or error stack traces",
205
- "Never make up information — say you don't know instead",
206
- ],
207
-
208
- // Knowledge base for AI context
209
- knowledgeBase: {
210
- company: {
211
- name: "Acme Corp",
212
- supportHours: "24/7 for premium, 9-5 for free",
213
- refundPolicy: "30 days for all purchases",
214
- },
215
- products: {
216
- basic: {
217
- price: "$9.99/month",
218
- features: ["Email support", "5GB storage"],
219
- },
220
- premium: {
221
- price: "$29.99/month",
222
- features: ["24/7 support", "100GB storage", "Priority queue"],
223
- },
224
- },
225
- },
226
- });
227
- ```
228
-
229
- ## Context Management
230
-
231
- ### Static Context
232
-
233
- Fixed context available throughout the conversation:
234
-
235
- ```typescript
236
- const agent = new Agent({
237
- context: {
238
- companyName: "Acme Corp",
239
- supportEmail: "support@acme.com",
240
- currentDate: new Date().toISOString(),
241
- },
242
- });
243
- ```
244
-
245
- ### Dynamic Context Provider
246
-
247
- Fresh context fetched before each response:
248
-
249
- ```typescript
250
- const agent = new Agent({
251
- contextProvider: async () => {
252
- // Fetch real-time data
253
- const weather = await weatherAPI.getCurrentWeather();
254
- const user = await auth.getCurrentUser();
255
-
256
- return {
257
- currentWeather: weather,
258
- userProfile: user,
259
- serverTime: new Date(),
260
- };
261
- },
262
- });
263
- ```
264
-
265
- ### Context Updates
266
-
267
- Context can be modified during conversation:
268
-
269
- ```typescript
270
- // From tool execution
271
- const updateLocationTool: Tool<
272
- { currentLocation?: string; lastLocationUpdate?: Date },
273
- [],
274
- string,
275
- { location: string }
276
- > = {
277
- id: "update_location",
278
- description: "Update user's current location",
279
- parameters: {
280
- type: "object",
281
- properties: {
282
- location: { type: "string", description: "New location to set" },
283
- },
284
- required: ["location"],
285
- },
286
- handler: async ({ context }, { location }) => {
287
- return {
288
- data: `Location updated to ${location}`,
289
- contextUpdate: {
290
- currentLocation: location,
291
- lastLocationUpdate: new Date(),
292
- },
293
- };
294
- },
295
- };
296
-
297
- // Programmatically
298
- await agent.updateContext({
299
- userStatus: "premium",
300
- lastActivity: new Date(),
301
- });
302
- ```
303
-
304
- ## Session Management
305
-
306
- ### Automatic Session Management
307
-
308
- Sessions are automatically managed through the integrated `SessionManager`:
309
-
310
- ```typescript
311
- // Agent with automatic session management
312
- const agent = new Agent({
313
- name: "Assistant",
314
- provider: new OpenAIProvider({ apiKey: process.env.OPENAI_API_KEY }),
315
- persistence: { adapter: new PrismaAdapter({ prisma }) },
316
- sessionId: "user-123" // Automatically loads or creates this session
317
- });
318
-
319
- // Access session manager
320
- const sessionManager = agent.session;
321
-
322
- // Get or create session (handles existing, new, or auto-generated IDs)
323
- await sessionManager.getOrCreate("user-456");
324
- await sessionManager.getOrCreate(); // Auto-generates ID
325
-
326
- // Session data access
327
- const data = sessionManager.getData<MyDataType>();
328
- await sessionManager.setData({ field: "value" });
329
-
330
- // History management
331
- await sessionManager.addMessage("user", "Hello");
332
- const history = sessionManager.getHistory();
333
- sessionManager.clearHistory();
334
- ```
335
-
336
- ### Session Persistence
337
-
338
- Sessions are automatically persisted when using persistence adapters:
339
-
340
- ```typescript
341
- const agent = new Agent({
342
- persistence: {
343
- adapter: new RedisAdapter(redisClient),
344
- autoSave: true, // Auto-save after each response (default)
345
- },
346
- sessionId: "user-123" // Automatically loads from persistence
347
- });
348
-
349
- // Sessions are automatically saved after each message
350
- const response = await agent.respond("Hello");
351
- // Session state automatically persisted
352
-
353
- // Manual session operations (if needed)
354
- await agent.session.save(); // Manual save
355
- await agent.session.delete(); // Delete session
356
- const newSession = await agent.session.reset(true); // Reset with history preserved
357
- ```
358
-
359
- ### Session Access Methods
360
-
361
- ```typescript
362
- // Access current session data
363
- const data = agent.session.getData<MyDataType>();
364
- await agent.session.setData({ field: "value" });
365
-
366
- // Session information
367
- console.log(agent.session.id); // Current session ID
368
- console.log(agent.session.current); // Full session state
369
-
370
- // History management
371
- const history = agent.session.getHistory();
372
- await agent.session.addMessage("user", "New message");
373
- agent.session.clearHistory();
374
- ```
375
-
376
- ## Route Management
377
-
378
- ### Declarative Route Creation
379
-
380
- ```typescript
381
- const agent = new Agent<CustomerContext, CustomerData>({
382
- // Agent-level schema defines all possible data fields
383
- schema: { /* comprehensive schema */ },
384
-
385
- routes: [
386
- {
387
- title: "Technical Support",
388
- description: "Help with technical issues",
389
- when: ["user reports technical problem"],
390
- // NEW: Routes specify required fields instead of schemas
391
- requiredFields: ["customerName", "email", "issueType", "issueDescription"],
392
- optionalFields: ["phone", "priority"],
393
- initialStep: {
394
- prompt:
395
- "I understand you're having a technical issue. Can you describe what's happening?",
396
- collect: ["issueType", "issueDescription"], // Collects into agent-level data
397
- },
398
- },
399
- {
400
- title: "Billing Inquiry",
401
- description: "Handle billing and payment questions",
402
- when: ["user asks about billing or payment"],
403
- requiredFields: ["customerName", "email", "issueType"],
404
- initialStep: {
405
- prompt:
406
- "I'd be happy to help with your billing question. What can I assist with?",
407
- collect: ["issueType"], // Maps to agent schema field
408
- },
409
- },
410
- ],
411
- });
412
- ```
413
-
414
- ### Programmatic Route Creation
415
-
416
- ```typescript
417
- // Create routes dynamically with required fields
418
- const supportRoute = agent
419
- .createRoute({
420
- title: "Customer Support",
421
- requiredFields: ["customerName", "email", "issueType"], // NEW: Required fields
422
- optionalFields: ["phone"], // NEW: Optional fields
423
- initialStep: {
424
- prompt: "How can I help you today?",
425
- collect: ["customerName", "email"], // Collects into agent-level data
426
- },
427
- })
428
- .nextStep({
429
- prompt: "I understand you need help, {{customerName}}. What type of issue are you experiencing?",
430
- collect: ["issueType"],
431
- requires: ["customerName", "email"], // Prerequisites from agent data
432
- });
433
-
434
- // Access created routes
435
- const routes = agent.getRoutes();
436
- console.log(routes.map((r) => r.title)); // ["Customer Support", ...]
437
- ```
438
-
439
- ## Enhanced Guideline System
440
-
441
- ### Flexible Guideline Conditions
442
-
443
- Guidelines now support the powerful `ConditionTemplate` system, allowing for more sophisticated behavioral control:
444
-
445
- ```typescript
446
- // String-only condition (AI context)
447
- agent.addGuideline({
448
- condition: "User is asking for technical help",
449
- action: "Provide detailed technical explanations with examples"
450
- });
451
-
452
- // Function-only condition (programmatic)
453
- agent.addGuideline({
454
- condition: (ctx) => ctx.data?.userType === 'premium',
455
- action: "Offer priority support and additional features"
456
- });
457
-
458
- // Mixed array condition (hybrid approach)
459
- agent.addGuideline({
460
- condition: [
461
- "User seems confused or needs clarification", // AI context
462
- (ctx) => ctx.data?.attemptCount > 2 // Programmatic check
463
- ],
464
- action: "Slow down, use simpler language, and offer to connect with human support"
465
- });
466
-
467
- // Complex conditional guidelines
468
- agent.addGuideline({
469
- condition: [
470
- "User is reporting a critical issue", // AI context
471
- (ctx) => ctx.data?.accountTier === 'enterprise', // Account check
472
- (ctx) => new Date().getHours() >= 9 && new Date().getHours() <= 17 // Business hours
473
- ],
474
- action: "Immediately escalate to senior technical support and provide direct contact information"
475
- });
476
- ```
477
-
478
- ### Guideline Evaluation Logic
479
-
480
- Guidelines use **AND logic** for arrays - all conditions must be met:
481
-
482
- - **String conditions**: Provide context to AI for guideline matching
483
- - **Function conditions**: Must return `true` for guideline to activate
484
- - **Arrays**: All functions must return `true`, strings provide AI context
485
-
486
- ### Context-Aware Guidelines
487
-
488
- Guidelines can access both agent context and collected data:
489
-
490
- ```typescript
491
- interface SupportContext {
492
- userTier: 'free' | 'premium' | 'enterprise';
493
- supportTicketCount: number;
494
- lastContactDate?: Date;
495
- }
496
-
497
- interface SupportData {
498
- issueType?: string;
499
- severity?: 'low' | 'medium' | 'high' | 'critical';
500
- previousAttempts?: number;
501
- }
502
-
503
- agent.addGuideline({
504
- condition: [
505
- "User has contacted support multiple times recently", // AI context
506
- (ctx) => ctx.context?.supportTicketCount > 3, // Context check
507
- (ctx) => ctx.data?.severity === 'high' // Data check
508
- ],
509
- action: "Acknowledge their patience, apologize for the inconvenience, and prioritize their case"
510
- });
511
- ```
512
-
513
- ### Dynamic Guideline Activation
514
-
515
- Guidelines can be activated based on conversation state:
516
-
517
- ```typescript
518
- // Time-based guidelines
519
- agent.addGuideline({
520
- condition: (ctx) => {
521
- const hour = new Date().getHours();
522
- return hour < 9 || hour > 17; // Outside business hours
523
- },
524
- action: "Inform user that live support is available during business hours (9 AM - 5 PM)"
525
- });
526
-
527
- // Progress-based guidelines
528
- agent.addGuideline({
529
- condition: [
530
- "User is making good progress", // AI context
531
- (ctx) => Object.keys(ctx.data || {}).length > 3 // Has collected significant data
532
- ],
533
- action: "Acknowledge their cooperation and let them know we're almost done"
534
- });
535
-
536
- // Route-specific guidelines
537
- agent.addGuideline({
538
- condition: [
539
- "User is in the payment process", // AI context
540
- (ctx) => ctx.session?.currentRoute?.id === 'payment_flow' // Route check
541
- ],
542
- action: "Be extra careful with payment information and confirm all details before processing"
543
- });
544
- ```
545
-
546
- ## Tool Integration
547
-
548
- ### Agent-Level Tools
549
-
550
- Available to all routes and steps:
551
-
552
- ```typescript
553
- const agent = new Agent({
554
- tools: [searchTool, calculatorTool, translationTool],
555
- });
556
- ```
557
-
558
- ### Route-Level Tools
559
-
560
- Specific to a route:
561
-
562
- ```typescript
563
- const route = agent.createRoute({
564
- title: "Order Management",
565
- tools: [orderLookupTool, orderUpdateTool, refundTool],
566
- });
567
- ```
568
-
569
- ### Tool Resolution Priority
570
-
571
- 1. **Step-level tools** (highest priority)
572
- 2. **Route-level tools**
573
- 3. **Agent-level tools** (lowest priority)
574
-
575
- ## Agent-Level Data Collection
576
-
577
- ### Centralized Data Schema
578
-
579
- The new architecture centralizes data collection at the agent level, allowing all routes to work with the same data structure:
580
-
581
- ```typescript
582
- interface ComprehensiveData {
583
- // Customer identification
584
- customerId?: string;
585
- customerName?: string;
586
- email?: string;
587
- phone?: string;
588
-
589
- // Issue tracking
590
- issueType?: 'booking' | 'billing' | 'technical' | 'other';
591
- issueDescription?: string;
592
- priority?: 'low' | 'medium' | 'high';
593
-
594
- // Feedback
595
- rating?: number;
596
- comments?: string;
597
- recommendToFriend?: boolean;
598
- }
599
-
600
- const agent = new Agent<Context, ComprehensiveData>({
601
- name: "Customer Service Agent",
602
- schema: {
603
- type: "object",
604
- properties: {
605
- customerId: { type: "string" },
606
- customerName: { type: "string" },
607
- email: { type: "string", format: "email" },
608
- phone: { type: "string" },
609
- issueType: { type: "string", enum: ["booking", "billing", "technical", "other"] },
610
- issueDescription: { type: "string" },
611
- priority: { type: "string", enum: ["low", "medium", "high"] },
612
- rating: { type: "number", minimum: 1, maximum: 5 },
613
- comments: { type: "string" },
614
- recommendToFriend: { type: "boolean" }
615
- }
616
- }
617
- });
618
- ```
619
-
620
- ### Route Completion Based on Required Fields
621
-
622
- Routes now specify which fields they need to complete, enabling cross-route data sharing:
623
-
624
- ```typescript
625
- // Support route needs basic info + issue details
626
- const supportRoute = agent.createRoute({
627
- title: "Customer Support",
628
- requiredFields: ["customerName", "email", "issueType", "issueDescription"],
629
- optionalFields: ["phone", "priority"]
630
- });
631
-
632
- // Feedback route needs basic info + rating
633
- const feedbackRoute = agent.createRoute({
634
- title: "Feedback Collection",
635
- requiredFields: ["customerName", "email", "rating"],
636
- optionalFields: ["comments", "recommendToFriend"]
637
- });
638
-
639
- // Routes can complete when their required data is available,
640
- // regardless of which route collected it
641
- ```
642
-
643
- ### Cross-Route Data Sharing
644
-
645
- Data collected by any route is available to all other routes:
646
-
647
- ```typescript
648
- // User starts with support, provides name and email
649
- const response1 = await agent.respond("I need help, my name is John Doe, email john@example.com");
650
- // Agent data now contains: { customerName: "John Doe", email: "john@example.com" }
651
-
652
- // User switches to feedback - already has 2/3 required fields
653
- const response2 = await agent.respond("Actually, I want to leave feedback. I'd rate you 5 stars.");
654
- // Feedback route completes immediately with: { customerName: "John Doe", email: "john@example.com", rating: 5 }
655
- ```
656
-
657
- ### Agent Data Management Methods
658
-
659
- Access and update agent-level data programmatically:
660
-
661
- ```typescript
662
- // Get current collected data
663
- const currentData = agent.getCollectedData();
664
- console.log(currentData); // { customerName: "John", email: "john@example.com" }
665
-
666
- // Update data programmatically
667
- await agent.updateCollectedData({
668
- customerId: "CUST-12345",
669
- priority: "high"
670
- });
671
-
672
- // Validate data against schema
673
- const validation = agent.validateData({ email: "invalid-email" });
674
- if (!validation.valid) {
675
- console.log(validation.errors); // Detailed validation errors
676
- }
677
- ```
678
-
679
- ## Response Generation
680
-
681
- ### Simple Response API
682
-
683
- ```typescript
684
- // Simple message-based API (recommended)
685
- const response = await agent.respond("How do I reset my password?");
686
- console.log(response.message);
687
- console.log(agent.session.getData<CustomerData>()); // Agent-level collected data
688
- console.log(response.toolCalls); // Any tool calls made
689
- console.log(response.isRouteComplete); // Whether route finished
690
-
691
- // Advanced usage with history override
692
- const response = await agent.respond("Hello", {
693
- history: [
694
- { role: "user", content: "Previous context" },
695
- { role: "assistant", content: "I understand" }
696
- ]
697
- });
698
- ```
699
-
700
- ### Streaming Response
701
-
702
- ```typescript
703
- const stream = agent.respondStream("Tell me about your services");
704
-
705
- for await (const chunk of stream) {
706
- if (chunk.delta) {
707
- process.stdout.write(chunk.delta); // Real-time output
708
- }
709
-
710
- if (chunk.done) {
711
- console.log("\nSession ID:", agent.session.id);
712
- console.log("Tool calls:", chunk.toolCalls);
713
- }
714
- }
715
- ```
716
-
717
- ### Response with Custom Context
718
-
719
- ```typescript
720
- const response = await agent.respond("Hola", {
721
- contextOverride: {
722
- language: "es", // Override context for this response
723
- debug: true,
724
- }
725
- });
726
- ```
727
-
728
- ## Advanced Features
729
-
730
- ### Route Transitions
731
-
732
- ```typescript
733
- // Manual route transition
734
- await agent.nextStepRoute("premium-support", session);
735
-
736
- // Route completion transitions
737
- const supportRoute = agent.createRoute({
738
- title: "Basic Support",
739
- onComplete: "feedback-survey", // Auto-transition when complete
740
- });
741
-
742
- // Dynamic transitions
743
- const dynamicRoute = agent.createRoute({
744
- title: "Workflow",
745
- onComplete: async (session, context) => {
746
- if (session.data.success) {
747
- return "success-route";
748
- }
749
- return "retry-route";
750
- },
751
- });
752
- ```
753
-
754
- ### Debugging
755
-
756
- ```typescript
757
- const debugAgent = new Agent({
758
- name: "Debug Agent",
759
- debug: true, // Enables detailed logging
760
- provider: openaiProvider,
761
- });
762
-
763
- // Logs will show:
764
- // [Agent] Selected route: Technical Support
765
- // [Agent] Entered step: initial_step
766
- // [Agent] Tool executed: search_kb (success: true)
767
- // [RoutingEngine] AI selected step: detailed_help
768
- ```
769
-
770
- ## Agent and Route Option Merging
771
-
772
- @fai/agent supports hierarchical configuration where route-level options can override or merge with agent-level options. Understanding this behavior is crucial for effective agent design.
773
-
774
- ### Rules and Prohibitions
775
-
776
- **Rules** and **prohibitions** are merged from both agent and route levels:
777
-
778
- - Agent-level rules/prohibitions apply to all routes
779
- - Route-level rules/prohibitions are appended after agent-level ones
780
- - Both are always included in every prompt (they are not conditional)
781
-
782
- ```typescript
783
- const agent = new Agent({
784
- rules: ["Always confirm before taking action"],
785
- prohibitions: ["Never delete data without confirmation"],
786
- });
787
-
788
- agent.createRoute({
789
- title: "Billing",
790
- rules: ["Always quote prices in the user's currency"],
791
- prohibitions: ["Never process refunds above $500 without escalation"],
792
- });
793
- // Result: Both agent and route rules/prohibitions are included in prompts
794
- ```
795
-
796
- See [Rules & Prohibitions](./rules-and-prohibitions.md) for full details.
797
-
798
- ### Guidelines and Terms
799
-
800
- **Guidelines** are combined from both agent and route levels:
801
-
802
- - Agent-level guidelines are applied first
803
- - Route-level guidelines are added after agent guidelines
804
- - All guidelines are evaluated together during response generation
805
-
806
- ```typescript
807
- const agent = new Agent({
808
- guidelines: [
809
- { id: "polite", action: "Always be polite and professional" },
810
- { id: "accurate", action: "Provide accurate information" },
811
- ],
812
- });
813
-
814
- const route = agent.createRoute({
815
- guidelines: [
816
- {
817
- id: "domain_specific",
818
- action: "Use technical terminology appropriately",
819
- },
820
- ],
821
- });
822
- // Result: All 3 guidelines (polite, accurate, domain_specific) are used
823
- ```
824
-
825
- **Terms** use route-level precedence:
826
-
827
- - Agent-level terms are loaded first
828
- - Route-level terms with the same name override agent-level terms
829
- - This allows routes to provide domain-specific definitions
830
-
831
- ```typescript
832
- const agent = new Agent({
833
- terms: [{ name: "API", description: "Application Programming Interface" }],
834
- });
835
-
836
- const route = agent.createRoute({
837
- terms: [
838
- {
839
- name: "API",
840
- description: "In this context, API refers to our REST API endpoints",
841
- },
842
- ],
843
- });
844
- // Result: Route's definition of "API" takes precedence
845
- ```
846
-
847
- ### Tools
848
-
849
- **Tools** follow a hierarchical priority system:
850
-
851
- 1. Step-level tools (highest priority)
852
- 2. Route-level tools
853
- 3. Agent-level tools (lowest priority)
854
-
855
- Tools with the same ID at different levels will be resolved by priority, with higher-level tools taking precedence.
856
-
857
- ### Lifecycle Hooks
858
-
859
- **Lifecycle hooks** are called at both agent and route levels:
860
-
861
- - Agent-level hooks are called for all routes
862
- - Route-level hooks are called only for that specific route
863
- - Both types of hooks can modify context and data
864
-
865
- ## Best Practices
866
-
867
- ### Context Design
868
-
869
- - **Keep context focused**: Only include data needed across conversations
870
- - **Use providers for freshness**: Prefer `contextProvider` over static context for dynamic data
871
- - **Handle updates gracefully**: Use lifecycle hooks for validation and side effects
872
-
873
- ### Session Management
874
-
875
- - **Set up persistence early**: Configure persistence for production use
876
- - **Use meaningful session IDs**: Include user/context identifiers
877
- - **Clean up old sessions**: Implement retention policies
878
-
879
- ### Route Organization
880
-
881
- - **Single responsibility**: Each route should serve one clear user intent
882
- - **Progressive disclosure**: Collect information in logical order
883
- - **Clear completion criteria**: Define when routes should end
884
-
885
- ### Tool Management
886
-
887
- - **Hierarchical scoping**: Use appropriate tool levels for security and performance
888
- - **Error handling**: Implement robust error recovery in tools
889
- - **Performance monitoring**: Track tool usage and response times
890
-
891
- ### Performance Optimization
892
-
893
- - **Limit concurrent sessions**: Implement session limits for high-traffic scenarios
894
- - **Cache context data**: Avoid redundant API calls in context providers
895
- - **Batch operations**: Group related tool calls when possible
896
-
897
- ## Migration from Legacy Agents
898
-
899
- ### From Domain-Based to Route-Based
900
-
901
- ```typescript
902
- // Legacy (domain-based)
903
- const legacyAgent = new Agent({
904
- domains: ["calendar", "email"],
905
- });
906
-
907
- // New (route-based)
908
- const newAgent = new Agent({
909
- routes: [
910
- {
911
- title: "Calendar Management",
912
- tools: [calendarTool], // Route-specific tools
913
- },
914
- {
915
- title: "Email Management",
916
- tools: [emailTool],
917
- },
918
- ],
919
- });
920
- ```
921
-
922
- ### From Static to Dynamic Context
923
-
924
- ```typescript
925
- // Legacy (static context)
926
- const staticAgent = new Agent({
927
- context: { userId: "123" },
928
- });
929
-
930
- // New (dynamic context)
931
- const dynamicAgent = new Agent({
932
- contextProvider: async () => {
933
- return { userId: await auth.getCurrentUserId() };
934
- },
935
- });
936
- ```
937
-
938
- The Agent class provides a comprehensive foundation for building intelligent, context-aware AI applications with robust conversation management and data collection capabilities.