ai 6.0.31 → 6.0.32

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 (250) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/index.js +1 -1
  3. package/dist/index.mjs +1 -1
  4. package/dist/internal/index.js +1 -1
  5. package/dist/internal/index.mjs +1 -1
  6. package/docs/00-introduction/index.mdx +76 -0
  7. package/docs/02-foundations/01-overview.mdx +43 -0
  8. package/docs/02-foundations/02-providers-and-models.mdx +163 -0
  9. package/docs/02-foundations/03-prompts.mdx +620 -0
  10. package/docs/02-foundations/04-tools.mdx +160 -0
  11. package/docs/02-foundations/05-streaming.mdx +62 -0
  12. package/docs/02-foundations/index.mdx +43 -0
  13. package/docs/02-getting-started/00-choosing-a-provider.mdx +110 -0
  14. package/docs/02-getting-started/01-navigating-the-library.mdx +85 -0
  15. package/docs/02-getting-started/02-nextjs-app-router.mdx +556 -0
  16. package/docs/02-getting-started/03-nextjs-pages-router.mdx +542 -0
  17. package/docs/02-getting-started/04-svelte.mdx +627 -0
  18. package/docs/02-getting-started/05-nuxt.mdx +566 -0
  19. package/docs/02-getting-started/06-nodejs.mdx +512 -0
  20. package/docs/02-getting-started/07-expo.mdx +766 -0
  21. package/docs/02-getting-started/08-tanstack-start.mdx +583 -0
  22. package/docs/02-getting-started/index.mdx +44 -0
  23. package/docs/03-agents/01-overview.mdx +96 -0
  24. package/docs/03-agents/02-building-agents.mdx +367 -0
  25. package/docs/03-agents/03-workflows.mdx +370 -0
  26. package/docs/03-agents/04-loop-control.mdx +350 -0
  27. package/docs/03-agents/05-configuring-call-options.mdx +286 -0
  28. package/docs/03-agents/index.mdx +40 -0
  29. package/docs/03-ai-sdk-core/01-overview.mdx +33 -0
  30. package/docs/03-ai-sdk-core/05-generating-text.mdx +600 -0
  31. package/docs/03-ai-sdk-core/10-generating-structured-data.mdx +662 -0
  32. package/docs/03-ai-sdk-core/15-tools-and-tool-calling.mdx +1102 -0
  33. package/docs/03-ai-sdk-core/16-mcp-tools.mdx +375 -0
  34. package/docs/03-ai-sdk-core/20-prompt-engineering.mdx +144 -0
  35. package/docs/03-ai-sdk-core/25-settings.mdx +198 -0
  36. package/docs/03-ai-sdk-core/30-embeddings.mdx +247 -0
  37. package/docs/03-ai-sdk-core/31-reranking.mdx +218 -0
  38. package/docs/03-ai-sdk-core/35-image-generation.mdx +341 -0
  39. package/docs/03-ai-sdk-core/36-transcription.mdx +173 -0
  40. package/docs/03-ai-sdk-core/37-speech.mdx +167 -0
  41. package/docs/03-ai-sdk-core/40-middleware.mdx +480 -0
  42. package/docs/03-ai-sdk-core/45-provider-management.mdx +349 -0
  43. package/docs/03-ai-sdk-core/50-error-handling.mdx +149 -0
  44. package/docs/03-ai-sdk-core/55-testing.mdx +218 -0
  45. package/docs/03-ai-sdk-core/60-telemetry.mdx +313 -0
  46. package/docs/03-ai-sdk-core/65-devtools.mdx +107 -0
  47. package/docs/03-ai-sdk-core/index.mdx +88 -0
  48. package/docs/04-ai-sdk-ui/01-overview.mdx +44 -0
  49. package/docs/04-ai-sdk-ui/02-chatbot.mdx +1313 -0
  50. package/docs/04-ai-sdk-ui/03-chatbot-message-persistence.mdx +535 -0
  51. package/docs/04-ai-sdk-ui/03-chatbot-resume-streams.mdx +263 -0
  52. package/docs/04-ai-sdk-ui/03-chatbot-tool-usage.mdx +682 -0
  53. package/docs/04-ai-sdk-ui/04-generative-user-interfaces.mdx +389 -0
  54. package/docs/04-ai-sdk-ui/05-completion.mdx +186 -0
  55. package/docs/04-ai-sdk-ui/08-object-generation.mdx +344 -0
  56. package/docs/04-ai-sdk-ui/20-streaming-data.mdx +397 -0
  57. package/docs/04-ai-sdk-ui/21-error-handling.mdx +190 -0
  58. package/docs/04-ai-sdk-ui/21-transport.mdx +174 -0
  59. package/docs/04-ai-sdk-ui/24-reading-ui-message-streams.mdx +104 -0
  60. package/docs/04-ai-sdk-ui/25-message-metadata.mdx +152 -0
  61. package/docs/04-ai-sdk-ui/50-stream-protocol.mdx +477 -0
  62. package/docs/04-ai-sdk-ui/index.mdx +64 -0
  63. package/docs/05-ai-sdk-rsc/01-overview.mdx +45 -0
  64. package/docs/05-ai-sdk-rsc/02-streaming-react-components.mdx +209 -0
  65. package/docs/05-ai-sdk-rsc/03-generative-ui-state.mdx +279 -0
  66. package/docs/05-ai-sdk-rsc/03-saving-and-restoring-states.mdx +105 -0
  67. package/docs/05-ai-sdk-rsc/04-multistep-interfaces.mdx +282 -0
  68. package/docs/05-ai-sdk-rsc/05-streaming-values.mdx +158 -0
  69. package/docs/05-ai-sdk-rsc/06-loading-state.mdx +273 -0
  70. package/docs/05-ai-sdk-rsc/08-error-handling.mdx +96 -0
  71. package/docs/05-ai-sdk-rsc/09-authentication.mdx +42 -0
  72. package/docs/05-ai-sdk-rsc/10-migrating-to-ui.mdx +722 -0
  73. package/docs/05-ai-sdk-rsc/index.mdx +58 -0
  74. package/docs/06-advanced/01-prompt-engineering.mdx +96 -0
  75. package/docs/06-advanced/02-stopping-streams.mdx +184 -0
  76. package/docs/06-advanced/03-backpressure.mdx +173 -0
  77. package/docs/06-advanced/04-caching.mdx +169 -0
  78. package/docs/06-advanced/05-multiple-streamables.mdx +68 -0
  79. package/docs/06-advanced/06-rate-limiting.mdx +60 -0
  80. package/docs/06-advanced/07-rendering-ui-with-language-models.mdx +213 -0
  81. package/docs/06-advanced/08-model-as-router.mdx +120 -0
  82. package/docs/06-advanced/09-multistep-interfaces.mdx +115 -0
  83. package/docs/06-advanced/09-sequential-generations.mdx +55 -0
  84. package/docs/06-advanced/10-vercel-deployment-guide.mdx +117 -0
  85. package/docs/06-advanced/index.mdx +11 -0
  86. package/docs/07-reference/01-ai-sdk-core/01-generate-text.mdx +2142 -0
  87. package/docs/07-reference/01-ai-sdk-core/02-stream-text.mdx +3215 -0
  88. package/docs/07-reference/01-ai-sdk-core/03-generate-object.mdx +780 -0
  89. package/docs/07-reference/01-ai-sdk-core/04-stream-object.mdx +1140 -0
  90. package/docs/07-reference/01-ai-sdk-core/05-embed.mdx +190 -0
  91. package/docs/07-reference/01-ai-sdk-core/06-embed-many.mdx +171 -0
  92. package/docs/07-reference/01-ai-sdk-core/06-rerank.mdx +309 -0
  93. package/docs/07-reference/01-ai-sdk-core/10-generate-image.mdx +227 -0
  94. package/docs/07-reference/01-ai-sdk-core/11-transcribe.mdx +138 -0
  95. package/docs/07-reference/01-ai-sdk-core/12-generate-speech.mdx +214 -0
  96. package/docs/07-reference/01-ai-sdk-core/15-agent.mdx +203 -0
  97. package/docs/07-reference/01-ai-sdk-core/16-tool-loop-agent.mdx +449 -0
  98. package/docs/07-reference/01-ai-sdk-core/17-create-agent-ui-stream.mdx +148 -0
  99. package/docs/07-reference/01-ai-sdk-core/18-create-agent-ui-stream-response.mdx +168 -0
  100. package/docs/07-reference/01-ai-sdk-core/18-pipe-agent-ui-stream-to-response.mdx +144 -0
  101. package/docs/07-reference/01-ai-sdk-core/20-tool.mdx +196 -0
  102. package/docs/07-reference/01-ai-sdk-core/22-dynamic-tool.mdx +175 -0
  103. package/docs/07-reference/01-ai-sdk-core/23-create-mcp-client.mdx +410 -0
  104. package/docs/07-reference/01-ai-sdk-core/24-mcp-stdio-transport.mdx +68 -0
  105. package/docs/07-reference/01-ai-sdk-core/25-json-schema.mdx +94 -0
  106. package/docs/07-reference/01-ai-sdk-core/26-zod-schema.mdx +109 -0
  107. package/docs/07-reference/01-ai-sdk-core/27-valibot-schema.mdx +55 -0
  108. package/docs/07-reference/01-ai-sdk-core/28-output.mdx +342 -0
  109. package/docs/07-reference/01-ai-sdk-core/30-model-message.mdx +415 -0
  110. package/docs/07-reference/01-ai-sdk-core/31-ui-message.mdx +246 -0
  111. package/docs/07-reference/01-ai-sdk-core/32-validate-ui-messages.mdx +101 -0
  112. package/docs/07-reference/01-ai-sdk-core/33-safe-validate-ui-messages.mdx +113 -0
  113. package/docs/07-reference/01-ai-sdk-core/40-provider-registry.mdx +182 -0
  114. package/docs/07-reference/01-ai-sdk-core/42-custom-provider.mdx +121 -0
  115. package/docs/07-reference/01-ai-sdk-core/50-cosine-similarity.mdx +52 -0
  116. package/docs/07-reference/01-ai-sdk-core/60-wrap-language-model.mdx +59 -0
  117. package/docs/07-reference/01-ai-sdk-core/61-wrap-image-model.mdx +64 -0
  118. package/docs/07-reference/01-ai-sdk-core/65-language-model-v2-middleware.mdx +46 -0
  119. package/docs/07-reference/01-ai-sdk-core/66-extract-reasoning-middleware.mdx +68 -0
  120. package/docs/07-reference/01-ai-sdk-core/67-simulate-streaming-middleware.mdx +71 -0
  121. package/docs/07-reference/01-ai-sdk-core/68-default-settings-middleware.mdx +80 -0
  122. package/docs/07-reference/01-ai-sdk-core/69-add-tool-input-examples-middleware.mdx +155 -0
  123. package/docs/07-reference/01-ai-sdk-core/70-extract-json-middleware.mdx +147 -0
  124. package/docs/07-reference/01-ai-sdk-core/70-step-count-is.mdx +84 -0
  125. package/docs/07-reference/01-ai-sdk-core/71-has-tool-call.mdx +120 -0
  126. package/docs/07-reference/01-ai-sdk-core/75-simulate-readable-stream.mdx +94 -0
  127. package/docs/07-reference/01-ai-sdk-core/80-smooth-stream.mdx +145 -0
  128. package/docs/07-reference/01-ai-sdk-core/90-generate-id.mdx +43 -0
  129. package/docs/07-reference/01-ai-sdk-core/91-create-id-generator.mdx +89 -0
  130. package/docs/07-reference/01-ai-sdk-core/index.mdx +159 -0
  131. package/docs/07-reference/02-ai-sdk-ui/01-use-chat.mdx +446 -0
  132. package/docs/07-reference/02-ai-sdk-ui/02-use-completion.mdx +179 -0
  133. package/docs/07-reference/02-ai-sdk-ui/03-use-object.mdx +178 -0
  134. package/docs/07-reference/02-ai-sdk-ui/31-convert-to-model-messages.mdx +230 -0
  135. package/docs/07-reference/02-ai-sdk-ui/32-prune-messages.mdx +108 -0
  136. package/docs/07-reference/02-ai-sdk-ui/40-create-ui-message-stream.mdx +151 -0
  137. package/docs/07-reference/02-ai-sdk-ui/41-create-ui-message-stream-response.mdx +113 -0
  138. package/docs/07-reference/02-ai-sdk-ui/42-pipe-ui-message-stream-to-response.mdx +73 -0
  139. package/docs/07-reference/02-ai-sdk-ui/43-read-ui-message-stream.mdx +57 -0
  140. package/docs/07-reference/02-ai-sdk-ui/46-infer-ui-tools.mdx +99 -0
  141. package/docs/07-reference/02-ai-sdk-ui/47-infer-ui-tool.mdx +75 -0
  142. package/docs/07-reference/02-ai-sdk-ui/50-direct-chat-transport.mdx +333 -0
  143. package/docs/07-reference/02-ai-sdk-ui/index.mdx +89 -0
  144. package/docs/07-reference/03-ai-sdk-rsc/01-stream-ui.mdx +767 -0
  145. package/docs/07-reference/03-ai-sdk-rsc/02-create-ai.mdx +90 -0
  146. package/docs/07-reference/03-ai-sdk-rsc/03-create-streamable-ui.mdx +91 -0
  147. package/docs/07-reference/03-ai-sdk-rsc/04-create-streamable-value.mdx +48 -0
  148. package/docs/07-reference/03-ai-sdk-rsc/05-read-streamable-value.mdx +78 -0
  149. package/docs/07-reference/03-ai-sdk-rsc/06-get-ai-state.mdx +50 -0
  150. package/docs/07-reference/03-ai-sdk-rsc/07-get-mutable-ai-state.mdx +70 -0
  151. package/docs/07-reference/03-ai-sdk-rsc/08-use-ai-state.mdx +26 -0
  152. package/docs/07-reference/03-ai-sdk-rsc/09-use-actions.mdx +42 -0
  153. package/docs/07-reference/03-ai-sdk-rsc/10-use-ui-state.mdx +35 -0
  154. package/docs/07-reference/03-ai-sdk-rsc/11-use-streamable-value.mdx +46 -0
  155. package/docs/07-reference/03-ai-sdk-rsc/20-render.mdx +262 -0
  156. package/docs/07-reference/03-ai-sdk-rsc/index.mdx +67 -0
  157. package/docs/07-reference/04-stream-helpers/01-ai-stream.mdx +89 -0
  158. package/docs/07-reference/04-stream-helpers/02-streaming-text-response.mdx +79 -0
  159. package/docs/07-reference/04-stream-helpers/05-stream-to-response.mdx +108 -0
  160. package/docs/07-reference/04-stream-helpers/07-openai-stream.mdx +77 -0
  161. package/docs/07-reference/04-stream-helpers/08-anthropic-stream.mdx +79 -0
  162. package/docs/07-reference/04-stream-helpers/09-aws-bedrock-stream.mdx +91 -0
  163. package/docs/07-reference/04-stream-helpers/10-aws-bedrock-anthropic-stream.mdx +96 -0
  164. package/docs/07-reference/04-stream-helpers/10-aws-bedrock-messages-stream.mdx +96 -0
  165. package/docs/07-reference/04-stream-helpers/11-aws-bedrock-cohere-stream.mdx +93 -0
  166. package/docs/07-reference/04-stream-helpers/12-aws-bedrock-llama-2-stream.mdx +93 -0
  167. package/docs/07-reference/04-stream-helpers/13-cohere-stream.mdx +78 -0
  168. package/docs/07-reference/04-stream-helpers/14-google-generative-ai-stream.mdx +85 -0
  169. package/docs/07-reference/04-stream-helpers/15-hugging-face-stream.mdx +84 -0
  170. package/docs/07-reference/04-stream-helpers/16-langchain-adapter.mdx +98 -0
  171. package/docs/07-reference/04-stream-helpers/16-llamaindex-adapter.mdx +70 -0
  172. package/docs/07-reference/04-stream-helpers/17-mistral-stream.mdx +81 -0
  173. package/docs/07-reference/04-stream-helpers/18-replicate-stream.mdx +83 -0
  174. package/docs/07-reference/04-stream-helpers/19-inkeep-stream.mdx +80 -0
  175. package/docs/07-reference/04-stream-helpers/index.mdx +103 -0
  176. package/docs/07-reference/05-ai-sdk-errors/ai-api-call-error.mdx +30 -0
  177. package/docs/07-reference/05-ai-sdk-errors/ai-download-error.mdx +27 -0
  178. package/docs/07-reference/05-ai-sdk-errors/ai-empty-response-body-error.mdx +24 -0
  179. package/docs/07-reference/05-ai-sdk-errors/ai-invalid-argument-error.mdx +26 -0
  180. package/docs/07-reference/05-ai-sdk-errors/ai-invalid-data-content-error.mdx +25 -0
  181. package/docs/07-reference/05-ai-sdk-errors/ai-invalid-data-content.mdx +26 -0
  182. package/docs/07-reference/05-ai-sdk-errors/ai-invalid-message-role-error.mdx +25 -0
  183. package/docs/07-reference/05-ai-sdk-errors/ai-invalid-prompt-error.mdx +47 -0
  184. package/docs/07-reference/05-ai-sdk-errors/ai-invalid-response-data-error.mdx +25 -0
  185. package/docs/07-reference/05-ai-sdk-errors/ai-invalid-tool-approval-error.mdx +25 -0
  186. package/docs/07-reference/05-ai-sdk-errors/ai-invalid-tool-input-error.mdx +27 -0
  187. package/docs/07-reference/05-ai-sdk-errors/ai-json-parse-error.mdx +25 -0
  188. package/docs/07-reference/05-ai-sdk-errors/ai-load-api-key-error.mdx +24 -0
  189. package/docs/07-reference/05-ai-sdk-errors/ai-load-setting-error.mdx +24 -0
  190. package/docs/07-reference/05-ai-sdk-errors/ai-message-conversion-error.mdx +25 -0
  191. package/docs/07-reference/05-ai-sdk-errors/ai-no-content-generated-error.mdx +24 -0
  192. package/docs/07-reference/05-ai-sdk-errors/ai-no-image-generated-error.mdx +36 -0
  193. package/docs/07-reference/05-ai-sdk-errors/ai-no-object-generated-error.mdx +43 -0
  194. package/docs/07-reference/05-ai-sdk-errors/ai-no-speech-generated-error.mdx +25 -0
  195. package/docs/07-reference/05-ai-sdk-errors/ai-no-such-model-error.mdx +26 -0
  196. package/docs/07-reference/05-ai-sdk-errors/ai-no-such-provider-error.mdx +28 -0
  197. package/docs/07-reference/05-ai-sdk-errors/ai-no-such-tool-error.mdx +26 -0
  198. package/docs/07-reference/05-ai-sdk-errors/ai-no-transcript-generated-error.mdx +25 -0
  199. package/docs/07-reference/05-ai-sdk-errors/ai-retry-error.mdx +27 -0
  200. package/docs/07-reference/05-ai-sdk-errors/ai-too-many-embedding-values-for-call-error.mdx +27 -0
  201. package/docs/07-reference/05-ai-sdk-errors/ai-tool-call-not-found-for-approval-error.mdx +26 -0
  202. package/docs/07-reference/05-ai-sdk-errors/ai-tool-call-repair-error.mdx +28 -0
  203. package/docs/07-reference/05-ai-sdk-errors/ai-type-validation-error.mdx +25 -0
  204. package/docs/07-reference/05-ai-sdk-errors/ai-unsupported-functionality-error.mdx +25 -0
  205. package/docs/07-reference/05-ai-sdk-errors/index.mdx +38 -0
  206. package/docs/07-reference/index.mdx +34 -0
  207. package/docs/08-migration-guides/00-versioning.mdx +46 -0
  208. package/docs/08-migration-guides/24-migration-guide-6-0.mdx +823 -0
  209. package/docs/08-migration-guides/25-migration-guide-5-0-data.mdx +882 -0
  210. package/docs/08-migration-guides/26-migration-guide-5-0.mdx +3427 -0
  211. package/docs/08-migration-guides/27-migration-guide-4-2.mdx +99 -0
  212. package/docs/08-migration-guides/28-migration-guide-4-1.mdx +14 -0
  213. package/docs/08-migration-guides/29-migration-guide-4-0.mdx +1157 -0
  214. package/docs/08-migration-guides/36-migration-guide-3-4.mdx +14 -0
  215. package/docs/08-migration-guides/37-migration-guide-3-3.mdx +64 -0
  216. package/docs/08-migration-guides/38-migration-guide-3-2.mdx +46 -0
  217. package/docs/08-migration-guides/39-migration-guide-3-1.mdx +168 -0
  218. package/docs/08-migration-guides/index.mdx +22 -0
  219. package/docs/09-troubleshooting/01-azure-stream-slow.mdx +33 -0
  220. package/docs/09-troubleshooting/02-client-side-function-calls-not-invoked.mdx +22 -0
  221. package/docs/09-troubleshooting/03-server-actions-in-client-components.mdx +40 -0
  222. package/docs/09-troubleshooting/04-strange-stream-output.mdx +36 -0
  223. package/docs/09-troubleshooting/05-streamable-ui-errors.mdx +16 -0
  224. package/docs/09-troubleshooting/05-tool-invocation-missing-result.mdx +106 -0
  225. package/docs/09-troubleshooting/06-streaming-not-working-when-deployed.mdx +31 -0
  226. package/docs/09-troubleshooting/06-streaming-not-working-when-proxied.mdx +31 -0
  227. package/docs/09-troubleshooting/06-timeout-on-vercel.mdx +60 -0
  228. package/docs/09-troubleshooting/07-unclosed-streams.mdx +34 -0
  229. package/docs/09-troubleshooting/08-use-chat-failed-to-parse-stream.mdx +26 -0
  230. package/docs/09-troubleshooting/09-client-stream-error.mdx +25 -0
  231. package/docs/09-troubleshooting/10-use-chat-tools-no-response.mdx +32 -0
  232. package/docs/09-troubleshooting/11-use-chat-custom-request-options.mdx +149 -0
  233. package/docs/09-troubleshooting/12-typescript-performance-zod.mdx +46 -0
  234. package/docs/09-troubleshooting/12-use-chat-an-error-occurred.mdx +59 -0
  235. package/docs/09-troubleshooting/13-repeated-assistant-messages.mdx +73 -0
  236. package/docs/09-troubleshooting/14-stream-abort-handling.mdx +73 -0
  237. package/docs/09-troubleshooting/14-tool-calling-with-structured-outputs.mdx +48 -0
  238. package/docs/09-troubleshooting/15-abort-breaks-resumable-streams.mdx +55 -0
  239. package/docs/09-troubleshooting/15-stream-text-not-working.mdx +33 -0
  240. package/docs/09-troubleshooting/16-streaming-status-delay.mdx +63 -0
  241. package/docs/09-troubleshooting/17-use-chat-stale-body-data.mdx +141 -0
  242. package/docs/09-troubleshooting/18-ontoolcall-type-narrowing.mdx +66 -0
  243. package/docs/09-troubleshooting/19-unsupported-model-version.mdx +50 -0
  244. package/docs/09-troubleshooting/20-no-object-generated-content-filter.mdx +72 -0
  245. package/docs/09-troubleshooting/30-model-is-not-assignable-to-type.mdx +21 -0
  246. package/docs/09-troubleshooting/40-typescript-cannot-find-namespace-jsx.mdx +24 -0
  247. package/docs/09-troubleshooting/50-react-maximum-update-depth-exceeded.mdx +39 -0
  248. package/docs/09-troubleshooting/60-jest-cannot-find-module-ai-rsc.mdx +22 -0
  249. package/docs/09-troubleshooting/index.mdx +11 -0
  250. package/package.json +8 -4
@@ -0,0 +1,370 @@
1
+ ---
2
+ title: Workflow Patterns
3
+ description: Learn workflow patterns for building reliable agents with the AI SDK.
4
+ ---
5
+
6
+ # Workflow Patterns
7
+
8
+ Combine the building blocks from the [overview](/docs/agents/overview) with these patterns to add structure and reliability to your agents:
9
+
10
+ - [Sequential Processing](#sequential-processing-chains) - Steps executed in order
11
+ - [Parallel Processing](#parallel-processing) - Independent tasks run simultaneously
12
+ - [Evaluation/Feedback Loops](#evaluator-optimizer) - Results checked and improved iteratively
13
+ - [Orchestration](#orchestrator-worker) - Coordinating multiple components
14
+ - [Routing](#routing) - Directing work based on context
15
+
16
+ ## Choose Your Approach
17
+
18
+ Consider these key factors:
19
+
20
+ - **Flexibility vs Control** - How much freedom does the LLM need vs how tightly you must constrain its actions?
21
+ - **Error Tolerance** - What are the consequences of mistakes in your use case?
22
+ - **Cost Considerations** - More complex systems typically mean more LLM calls and higher costs
23
+ - **Maintenance** - Simpler architectures are easier to debug and modify
24
+
25
+ **Start with the simplest approach that meets your needs**. Add complexity only when required by:
26
+
27
+ 1. Breaking down tasks into clear steps
28
+ 2. Adding tools for specific capabilities
29
+ 3. Implementing feedback loops for quality control
30
+ 4. Introducing multiple agents for complex workflows
31
+
32
+ Let's look at examples of these patterns in action.
33
+
34
+ ## Patterns with Examples
35
+
36
+ These patterns, adapted from [Anthropic's guide on building effective agents](https://www.anthropic.com/research/building-effective-agents), serve as building blocks you can combine to create comprehensive workflows. Each pattern addresses specific aspects of task execution. Combine them thoughtfully to build reliable solutions for complex problems.
37
+
38
+ ## Sequential Processing (Chains)
39
+
40
+ The simplest workflow pattern executes steps in a predefined order. Each step's output becomes input for the next step, creating a clear chain of operations. Use this pattern for tasks with well-defined sequences, like content generation pipelines or data transformation processes.
41
+
42
+ ```ts
43
+ import { generateText, generateObject } from 'ai';
44
+ __PROVIDER_IMPORT__;
45
+ import { z } from 'zod';
46
+
47
+ async function generateMarketingCopy(input: string) {
48
+ const model = __MODEL__;
49
+
50
+ // First step: Generate marketing copy
51
+ const { text: copy } = await generateText({
52
+ model,
53
+ prompt: `Write persuasive marketing copy for: ${input}. Focus on benefits and emotional appeal.`,
54
+ });
55
+
56
+ // Perform quality check on copy
57
+ const { object: qualityMetrics } = await generateObject({
58
+ model,
59
+ schema: z.object({
60
+ hasCallToAction: z.boolean(),
61
+ emotionalAppeal: z.number().min(1).max(10),
62
+ clarity: z.number().min(1).max(10),
63
+ }),
64
+ prompt: `Evaluate this marketing copy for:
65
+ 1. Presence of call to action (true/false)
66
+ 2. Emotional appeal (1-10)
67
+ 3. Clarity (1-10)
68
+
69
+ Copy to evaluate: ${copy}`,
70
+ });
71
+
72
+ // If quality check fails, regenerate with more specific instructions
73
+ if (
74
+ !qualityMetrics.hasCallToAction ||
75
+ qualityMetrics.emotionalAppeal < 7 ||
76
+ qualityMetrics.clarity < 7
77
+ ) {
78
+ const { text: improvedCopy } = await generateText({
79
+ model,
80
+ prompt: `Rewrite this marketing copy with:
81
+ ${!qualityMetrics.hasCallToAction ? '- A clear call to action' : ''}
82
+ ${qualityMetrics.emotionalAppeal < 7 ? '- Stronger emotional appeal' : ''}
83
+ ${qualityMetrics.clarity < 7 ? '- Improved clarity and directness' : ''}
84
+
85
+ Original copy: ${copy}`,
86
+ });
87
+ return { copy: improvedCopy, qualityMetrics };
88
+ }
89
+
90
+ return { copy, qualityMetrics };
91
+ }
92
+ ```
93
+
94
+ ## Routing
95
+
96
+ This pattern lets the model decide which path to take through a workflow based on context and intermediate results. The model acts as an intelligent router, directing the flow of execution between different branches of your workflow. Use this when handling varied inputs that require different processing approaches. In the example below, the first LLM call's results determine the second call's model size and system prompt.
97
+
98
+ ```ts
99
+ import { generateObject, generateText } from 'ai';
100
+ __PROVIDER_IMPORT__;
101
+ import { z } from 'zod';
102
+
103
+ async function handleCustomerQuery(query: string) {
104
+ const model = __MODEL__;
105
+
106
+ // First step: Classify the query type
107
+ const { object: classification } = await generateObject({
108
+ model,
109
+ schema: z.object({
110
+ reasoning: z.string(),
111
+ type: z.enum(['general', 'refund', 'technical']),
112
+ complexity: z.enum(['simple', 'complex']),
113
+ }),
114
+ prompt: `Classify this customer query:
115
+ ${query}
116
+
117
+ Determine:
118
+ 1. Query type (general, refund, or technical)
119
+ 2. Complexity (simple or complex)
120
+ 3. Brief reasoning for classification`,
121
+ });
122
+
123
+ // Route based on classification
124
+ // Set model and system prompt based on query type and complexity
125
+ const { text: response } = await generateText({
126
+ model:
127
+ classification.complexity === 'simple'
128
+ ? 'openai/gpt-4o-mini'
129
+ : 'openai/o4-mini',
130
+ system: {
131
+ general:
132
+ 'You are an expert customer service agent handling general inquiries.',
133
+ refund:
134
+ 'You are a customer service agent specializing in refund requests. Follow company policy and collect necessary information.',
135
+ technical:
136
+ 'You are a technical support specialist with deep product knowledge. Focus on clear step-by-step troubleshooting.',
137
+ }[classification.type],
138
+ prompt: query,
139
+ });
140
+
141
+ return { response, classification };
142
+ }
143
+ ```
144
+
145
+ ## Parallel Processing
146
+
147
+ Break down tasks into independent subtasks that execute simultaneously. This pattern uses parallel execution to improve efficiency while maintaining the benefits of structured workflows. For example, analyze multiple documents or process different aspects of a single input concurrently (like code review).
148
+
149
+ ```ts
150
+ import { generateText, generateObject } from 'ai';
151
+ __PROVIDER_IMPORT__;
152
+ import { z } from 'zod';
153
+
154
+ // Example: Parallel code review with multiple specialized reviewers
155
+ async function parallelCodeReview(code: string) {
156
+ const model = __MODEL__;
157
+
158
+ // Run parallel reviews
159
+ const [securityReview, performanceReview, maintainabilityReview] =
160
+ await Promise.all([
161
+ generateObject({
162
+ model,
163
+ system:
164
+ 'You are an expert in code security. Focus on identifying security vulnerabilities, injection risks, and authentication issues.',
165
+ schema: z.object({
166
+ vulnerabilities: z.array(z.string()),
167
+ riskLevel: z.enum(['low', 'medium', 'high']),
168
+ suggestions: z.array(z.string()),
169
+ }),
170
+ prompt: `Review this code:
171
+ ${code}`,
172
+ }),
173
+
174
+ generateObject({
175
+ model,
176
+ system:
177
+ 'You are an expert in code performance. Focus on identifying performance bottlenecks, memory leaks, and optimization opportunities.',
178
+ schema: z.object({
179
+ issues: z.array(z.string()),
180
+ impact: z.enum(['low', 'medium', 'high']),
181
+ optimizations: z.array(z.string()),
182
+ }),
183
+ prompt: `Review this code:
184
+ ${code}`,
185
+ }),
186
+
187
+ generateObject({
188
+ model,
189
+ system:
190
+ 'You are an expert in code quality. Focus on code structure, readability, and adherence to best practices.',
191
+ schema: z.object({
192
+ concerns: z.array(z.string()),
193
+ qualityScore: z.number().min(1).max(10),
194
+ recommendations: z.array(z.string()),
195
+ }),
196
+ prompt: `Review this code:
197
+ ${code}`,
198
+ }),
199
+ ]);
200
+
201
+ const reviews = [
202
+ { ...securityReview.object, type: 'security' },
203
+ { ...performanceReview.object, type: 'performance' },
204
+ { ...maintainabilityReview.object, type: 'maintainability' },
205
+ ];
206
+
207
+ // Aggregate results using another model instance
208
+ const { text: summary } = await generateText({
209
+ model,
210
+ system: 'You are a technical lead summarizing multiple code reviews.',
211
+ prompt: `Synthesize these code review results into a concise summary with key actions:
212
+ ${JSON.stringify(reviews, null, 2)}`,
213
+ });
214
+
215
+ return { reviews, summary };
216
+ }
217
+ ```
218
+
219
+ ## Orchestrator-Worker
220
+
221
+ A primary model (orchestrator) coordinates the execution of specialized workers. Each worker optimizes for a specific subtask, while the orchestrator maintains overall context and ensures coherent results. This pattern excels at complex tasks requiring different types of expertise or processing.
222
+
223
+ ```ts
224
+ import { generateObject } from 'ai';
225
+ __PROVIDER_IMPORT__;
226
+ import { z } from 'zod';
227
+
228
+ async function implementFeature(featureRequest: string) {
229
+ // Orchestrator: Plan the implementation
230
+ const { object: implementationPlan } = await generateObject({
231
+ model: __MODEL__,
232
+ schema: z.object({
233
+ files: z.array(
234
+ z.object({
235
+ purpose: z.string(),
236
+ filePath: z.string(),
237
+ changeType: z.enum(['create', 'modify', 'delete']),
238
+ }),
239
+ ),
240
+ estimatedComplexity: z.enum(['low', 'medium', 'high']),
241
+ }),
242
+ system:
243
+ 'You are a senior software architect planning feature implementations.',
244
+ prompt: `Analyze this feature request and create an implementation plan:
245
+ ${featureRequest}`,
246
+ });
247
+
248
+ // Workers: Execute the planned changes
249
+ const fileChanges = await Promise.all(
250
+ implementationPlan.files.map(async file => {
251
+ // Each worker is specialized for the type of change
252
+ const workerSystemPrompt = {
253
+ create:
254
+ 'You are an expert at implementing new files following best practices and project patterns.',
255
+ modify:
256
+ 'You are an expert at modifying existing code while maintaining consistency and avoiding regressions.',
257
+ delete:
258
+ 'You are an expert at safely removing code while ensuring no breaking changes.',
259
+ }[file.changeType];
260
+
261
+ const { object: change } = await generateObject({
262
+ model: __MODEL__,
263
+ schema: z.object({
264
+ explanation: z.string(),
265
+ code: z.string(),
266
+ }),
267
+ system: workerSystemPrompt,
268
+ prompt: `Implement the changes for ${file.filePath} to support:
269
+ ${file.purpose}
270
+
271
+ Consider the overall feature context:
272
+ ${featureRequest}`,
273
+ });
274
+
275
+ return {
276
+ file,
277
+ implementation: change,
278
+ };
279
+ }),
280
+ );
281
+
282
+ return {
283
+ plan: implementationPlan,
284
+ changes: fileChanges,
285
+ };
286
+ }
287
+ ```
288
+
289
+ ## Evaluator-Optimizer
290
+
291
+ Add quality control to workflows with dedicated evaluation steps that assess intermediate results. Based on the evaluation, the workflow proceeds, retries with adjusted parameters, or takes corrective action. This creates robust workflows capable of self-improvement and error recovery.
292
+
293
+ ```ts
294
+ import { generateText, generateObject } from 'ai';
295
+ __PROVIDER_IMPORT__;
296
+ import { z } from 'zod';
297
+
298
+ async function translateWithFeedback(text: string, targetLanguage: string) {
299
+ let currentTranslation = '';
300
+ let iterations = 0;
301
+ const MAX_ITERATIONS = 3;
302
+
303
+ // Initial translation
304
+ const { text: translation } = await generateText({
305
+ model: __MODEL__,
306
+ system: 'You are an expert literary translator.',
307
+ prompt: `Translate this text to ${targetLanguage}, preserving tone and cultural nuances:
308
+ ${text}`,
309
+ });
310
+
311
+ currentTranslation = translation;
312
+
313
+ // Evaluation-optimization loop
314
+ while (iterations < MAX_ITERATIONS) {
315
+ // Evaluate current translation
316
+ const { object: evaluation } = await generateObject({
317
+ model: __MODEL__,
318
+ schema: z.object({
319
+ qualityScore: z.number().min(1).max(10),
320
+ preservesTone: z.boolean(),
321
+ preservesNuance: z.boolean(),
322
+ culturallyAccurate: z.boolean(),
323
+ specificIssues: z.array(z.string()),
324
+ improvementSuggestions: z.array(z.string()),
325
+ }),
326
+ system: 'You are an expert in evaluating literary translations.',
327
+ prompt: `Evaluate this translation:
328
+
329
+ Original: ${text}
330
+ Translation: ${currentTranslation}
331
+
332
+ Consider:
333
+ 1. Overall quality
334
+ 2. Preservation of tone
335
+ 3. Preservation of nuance
336
+ 4. Cultural accuracy`,
337
+ });
338
+
339
+ // Check if quality meets threshold
340
+ if (
341
+ evaluation.qualityScore >= 8 &&
342
+ evaluation.preservesTone &&
343
+ evaluation.preservesNuance &&
344
+ evaluation.culturallyAccurate
345
+ ) {
346
+ break;
347
+ }
348
+
349
+ // Generate improved translation based on feedback
350
+ const { text: improvedTranslation } = await generateText({
351
+ model: __MODEL__,
352
+ system: 'You are an expert literary translator.',
353
+ prompt: `Improve this translation based on the following feedback:
354
+ ${evaluation.specificIssues.join('\n')}
355
+ ${evaluation.improvementSuggestions.join('\n')}
356
+
357
+ Original: ${text}
358
+ Current Translation: ${currentTranslation}`,
359
+ });
360
+
361
+ currentTranslation = improvedTranslation;
362
+ iterations++;
363
+ }
364
+
365
+ return {
366
+ finalTranslation: currentTranslation,
367
+ iterationsRequired: iterations,
368
+ };
369
+ }
370
+ ```
@@ -0,0 +1,350 @@
1
+ ---
2
+ title: Loop Control
3
+ description: Control agent execution with built-in loop management using stopWhen and prepareStep
4
+ ---
5
+
6
+ # Loop Control
7
+
8
+ You can control both the execution flow and the settings at each step of the agent loop. The loop continues until:
9
+
10
+ - A finish reasoning other than tool-calls is returned, or
11
+ - A tool that is invoked does not have an execute function, or
12
+ - A tool call needs approval, or
13
+ - A stop condition is met
14
+
15
+ The AI SDK provides built-in loop control through two parameters: `stopWhen` for defining stopping conditions and `prepareStep` for modifying settings (model, tools, messages, and more) between steps.
16
+
17
+ ## Stop Conditions
18
+
19
+ The `stopWhen` parameter controls when to stop execution when there are tool results in the last step. By default, agents stop after 20 steps using `stepCountIs(20)`.
20
+
21
+ When you provide `stopWhen`, the agent continues executing after tool calls until a stopping condition is met. When the condition is an array, execution stops when any of the conditions are met.
22
+
23
+ ### Use Built-in Conditions
24
+
25
+ The AI SDK provides several built-in stopping conditions:
26
+
27
+ ```ts
28
+ import { ToolLoopAgent, stepCountIs } from 'ai';
29
+ __PROVIDER_IMPORT__;
30
+
31
+ const agent = new ToolLoopAgent({
32
+ model: __MODEL__,
33
+ tools: {
34
+ // your tools
35
+ },
36
+ stopWhen: stepCountIs(20), // Default state: stop after 20 steps maximum
37
+ });
38
+
39
+ const result = await agent.generate({
40
+ prompt: 'Analyze this dataset and create a summary report',
41
+ });
42
+ ```
43
+
44
+ ### Combine Multiple Conditions
45
+
46
+ Combine multiple stopping conditions. The loop stops when it meets any condition:
47
+
48
+ ```ts
49
+ import { ToolLoopAgent, stepCountIs, hasToolCall } from 'ai';
50
+ __PROVIDER_IMPORT__;
51
+
52
+ const agent = new ToolLoopAgent({
53
+ model: __MODEL__,
54
+ tools: {
55
+ // your tools
56
+ },
57
+ stopWhen: [
58
+ stepCountIs(20), // Maximum 20 steps
59
+ hasToolCall('someTool'), // Stop after calling 'someTool'
60
+ ],
61
+ });
62
+
63
+ const result = await agent.generate({
64
+ prompt: 'Research and analyze the topic',
65
+ });
66
+ ```
67
+
68
+ ### Create Custom Conditions
69
+
70
+ Build custom stopping conditions for specific requirements:
71
+
72
+ ```ts
73
+ import { ToolLoopAgent, StopCondition, ToolSet } from 'ai';
74
+ __PROVIDER_IMPORT__;
75
+
76
+ const tools = {
77
+ // your tools
78
+ } satisfies ToolSet;
79
+
80
+ const hasAnswer: StopCondition<typeof tools> = ({ steps }) => {
81
+ // Stop when the model generates text containing "ANSWER:"
82
+ return steps.some(step => step.text?.includes('ANSWER:')) ?? false;
83
+ };
84
+
85
+ const agent = new ToolLoopAgent({
86
+ model: __MODEL__,
87
+ tools,
88
+ stopWhen: hasAnswer,
89
+ });
90
+
91
+ const result = await agent.generate({
92
+ prompt: 'Find the answer and respond with "ANSWER: [your answer]"',
93
+ });
94
+ ```
95
+
96
+ Custom conditions receive step information across all steps:
97
+
98
+ ```ts
99
+ const budgetExceeded: StopCondition<typeof tools> = ({ steps }) => {
100
+ const totalUsage = steps.reduce(
101
+ (acc, step) => ({
102
+ inputTokens: acc.inputTokens + (step.usage?.inputTokens ?? 0),
103
+ outputTokens: acc.outputTokens + (step.usage?.outputTokens ?? 0),
104
+ }),
105
+ { inputTokens: 0, outputTokens: 0 },
106
+ );
107
+
108
+ const costEstimate =
109
+ (totalUsage.inputTokens * 0.01 + totalUsage.outputTokens * 0.03) / 1000;
110
+ return costEstimate > 0.5; // Stop if cost exceeds $0.50
111
+ };
112
+ ```
113
+
114
+ ## Prepare Step
115
+
116
+ The `prepareStep` callback runs before each step in the loop and defaults to the initial settings if you don't return any changes. Use it to modify settings, manage context, or implement dynamic behavior based on execution history.
117
+
118
+ ### Dynamic Model Selection
119
+
120
+ Switch models based on step requirements:
121
+
122
+ ```ts
123
+ import { ToolLoopAgent } from 'ai';
124
+ __PROVIDER_IMPORT__;
125
+
126
+ const agent = new ToolLoopAgent({
127
+ model: 'openai/gpt-4o-mini', // Default model
128
+ tools: {
129
+ // your tools
130
+ },
131
+ prepareStep: async ({ stepNumber, messages }) => {
132
+ // Use a stronger model for complex reasoning after initial steps
133
+ if (stepNumber > 2 && messages.length > 10) {
134
+ return {
135
+ model: __MODEL__,
136
+ };
137
+ }
138
+ // Continue with default settings
139
+ return {};
140
+ },
141
+ });
142
+
143
+ const result = await agent.generate({
144
+ prompt: '...',
145
+ });
146
+ ```
147
+
148
+ ### Context Management
149
+
150
+ Manage growing conversation history in long-running loops:
151
+
152
+ ```ts
153
+ import { ToolLoopAgent } from 'ai';
154
+ __PROVIDER_IMPORT__;
155
+
156
+ const agent = new ToolLoopAgent({
157
+ model: __MODEL__,
158
+ tools: {
159
+ // your tools
160
+ },
161
+ prepareStep: async ({ messages }) => {
162
+ // Keep only recent messages to stay within context limits
163
+ if (messages.length > 20) {
164
+ return {
165
+ messages: [
166
+ messages[0], // Keep system instructions
167
+ ...messages.slice(-10), // Keep last 10 messages
168
+ ],
169
+ };
170
+ }
171
+ return {};
172
+ },
173
+ });
174
+
175
+ const result = await agent.generate({
176
+ prompt: '...',
177
+ });
178
+ ```
179
+
180
+ ### Tool Selection
181
+
182
+ Control which tools are available at each step:
183
+
184
+ ```ts
185
+ import { ToolLoopAgent } from 'ai';
186
+ __PROVIDER_IMPORT__;
187
+
188
+ const agent = new ToolLoopAgent({
189
+ model: __MODEL__,
190
+ tools: {
191
+ search: searchTool,
192
+ analyze: analyzeTool,
193
+ summarize: summarizeTool,
194
+ },
195
+ prepareStep: async ({ stepNumber, steps }) => {
196
+ // Search phase (steps 0-2)
197
+ if (stepNumber <= 2) {
198
+ return {
199
+ activeTools: ['search'],
200
+ toolChoice: 'required',
201
+ };
202
+ }
203
+
204
+ // Analysis phase (steps 3-5)
205
+ if (stepNumber <= 5) {
206
+ return {
207
+ activeTools: ['analyze'],
208
+ };
209
+ }
210
+
211
+ // Summary phase (step 6+)
212
+ return {
213
+ activeTools: ['summarize'],
214
+ toolChoice: 'required',
215
+ };
216
+ },
217
+ });
218
+
219
+ const result = await agent.generate({
220
+ prompt: '...',
221
+ });
222
+ ```
223
+
224
+ You can also force a specific tool to be used:
225
+
226
+ ```ts
227
+ prepareStep: async ({ stepNumber }) => {
228
+ if (stepNumber === 0) {
229
+ // Force the search tool to be used first
230
+ return {
231
+ toolChoice: { type: 'tool', toolName: 'search' },
232
+ };
233
+ }
234
+
235
+ if (stepNumber === 5) {
236
+ // Force the summarize tool after analysis
237
+ return {
238
+ toolChoice: { type: 'tool', toolName: 'summarize' },
239
+ };
240
+ }
241
+
242
+ return {};
243
+ };
244
+ ```
245
+
246
+ ### Message Modification
247
+
248
+ Transform messages before sending them to the model:
249
+
250
+ ```ts
251
+ import { ToolLoopAgent } from 'ai';
252
+ __PROVIDER_IMPORT__;
253
+
254
+ const agent = new ToolLoopAgent({
255
+ model: __MODEL__,
256
+ tools: {
257
+ // your tools
258
+ },
259
+ prepareStep: async ({ messages, stepNumber }) => {
260
+ // Summarize tool results to reduce token usage
261
+ const processedMessages = messages.map(msg => {
262
+ if (msg.role === 'tool' && msg.content.length > 1000) {
263
+ return {
264
+ ...msg,
265
+ content: summarizeToolResult(msg.content),
266
+ };
267
+ }
268
+ return msg;
269
+ });
270
+
271
+ return { messages: processedMessages };
272
+ },
273
+ });
274
+
275
+ const result = await agent.generate({
276
+ prompt: '...',
277
+ });
278
+ ```
279
+
280
+ ## Access Step Information
281
+
282
+ Both `stopWhen` and `prepareStep` receive detailed information about the current execution:
283
+
284
+ ```ts
285
+ prepareStep: async ({
286
+ model, // Current model configuration
287
+ stepNumber, // Current step number (0-indexed)
288
+ steps, // All previous steps with their results
289
+ messages, // Messages to be sent to the model
290
+ }) => {
291
+ // Access previous tool calls and results
292
+ const previousToolCalls = steps.flatMap(step => step.toolCalls);
293
+ const previousResults = steps.flatMap(step => step.toolResults);
294
+
295
+ // Make decisions based on execution history
296
+ if (previousToolCalls.some(call => call.toolName === 'dataAnalysis')) {
297
+ return {
298
+ toolChoice: { type: 'tool', toolName: 'reportGenerator' },
299
+ };
300
+ }
301
+
302
+ return {};
303
+ },
304
+ ```
305
+
306
+ ## Manual Loop Control
307
+
308
+ For scenarios requiring complete control over the agent loop, you can use AI SDK Core functions (`generateText` and `streamText`) to implement your own loop management instead of using `stopWhen` and `prepareStep`. This approach provides maximum flexibility for complex workflows.
309
+
310
+ ### Implementing a Manual Loop
311
+
312
+ Build your own agent loop when you need full control over execution:
313
+
314
+ ```ts
315
+ import { generateText, ModelMessage } from 'ai';
316
+ __PROVIDER_IMPORT__;
317
+
318
+ const messages: ModelMessage[] = [{ role: 'user', content: '...' }];
319
+
320
+ let step = 0;
321
+ const maxSteps = 10;
322
+
323
+ while (step < maxSteps) {
324
+ const result = await generateText({
325
+ model: __MODEL__,
326
+ messages,
327
+ tools: {
328
+ // your tools here
329
+ },
330
+ });
331
+
332
+ messages.push(...result.response.messages);
333
+
334
+ if (result.text) {
335
+ break; // Stop when model generates text
336
+ }
337
+
338
+ step++;
339
+ }
340
+ ```
341
+
342
+ This manual approach gives you complete control over:
343
+
344
+ - Message history management
345
+ - Step-by-step decision making
346
+ - Custom stopping conditions
347
+ - Dynamic tool and model selection
348
+ - Error handling and recovery
349
+
350
+ [Learn more about manual agent loops in the cookbook](/cookbook/node/manual-agent-loop).