@upstash/workflow 1.4.0 → 1.5.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 (223) hide show
  1. package/README.md +9 -0
  2. package/astro.d.mts +19 -2
  3. package/astro.d.ts +19 -2
  4. package/astro.js +670 -159
  5. package/astro.mjs +1 -1
  6. package/{chunk-DRHEHWMS.mjs → chunk-J3PXPHSB.mjs} +828 -317
  7. package/cloudflare.d.mts +17 -2
  8. package/cloudflare.d.ts +17 -2
  9. package/cloudflare.js +670 -159
  10. package/cloudflare.mjs +1 -1
  11. package/docs/agents/examples.mdx +8 -0
  12. package/docs/agents/features.mdx +374 -0
  13. package/docs/agents/getting-started.mdx +139 -0
  14. package/docs/agents/overview.mdx +40 -0
  15. package/docs/agents/patterns/evaluator-optimizer.mdx +72 -0
  16. package/docs/agents/patterns/orchestrator-workers.mdx +95 -0
  17. package/docs/agents/patterns/parallelization.mdx +77 -0
  18. package/docs/agents/patterns/prompt-chaining.mdx +84 -0
  19. package/docs/basics/best-practices/at-least-one-step.mdx +57 -0
  20. package/docs/basics/best-practices/business-logic-in-steps.mdx +52 -0
  21. package/docs/basics/best-practices/deterministic-code.mdx +132 -0
  22. package/docs/basics/best-practices/idempotency.mdx +38 -0
  23. package/docs/basics/best-practices/nested-context-methods.mdx +38 -0
  24. package/docs/basics/best-practices/overview.mdx +35 -0
  25. package/docs/basics/best-practices/promise-any.mdx +9 -0
  26. package/docs/basics/best-practices/return-step-results.mdx +80 -0
  27. package/docs/basics/best-practices/workflow-limits.mdx +62 -0
  28. package/docs/basics/client/cancel.mdx +137 -0
  29. package/docs/basics/client/dlq/callback.mdx +21 -0
  30. package/docs/basics/client/dlq/delete.mdx +120 -0
  31. package/docs/basics/client/dlq/list.mdx +96 -0
  32. package/docs/basics/client/dlq/restart.mdx +164 -0
  33. package/docs/basics/client/dlq/resume.mdx +167 -0
  34. package/docs/basics/client/logs.mdx +139 -0
  35. package/docs/basics/client/notify.mdx +79 -0
  36. package/docs/basics/client/trigger.mdx +139 -0
  37. package/docs/basics/client/waiters.mdx +31 -0
  38. package/docs/basics/client.mdx +40 -0
  39. package/docs/basics/how.mdx +65 -0
  40. package/docs/basics/serve/advanced.mdx +435 -0
  41. package/docs/basics/serve.mdx +142 -0
  42. package/docs/changelog.mdx +174 -0
  43. package/docs/examples/allInOne.mdx +377 -0
  44. package/docs/examples/authWebhook.mdx +567 -0
  45. package/docs/examples/customRetry.mdx +309 -0
  46. package/docs/examples/customerOnboarding.mdx +230 -0
  47. package/docs/examples/dynamicWorkflow.mdx +203 -0
  48. package/docs/examples/eCommerceOrderFulfillment.mdx +281 -0
  49. package/docs/examples/imageProcessing.mdx +339 -0
  50. package/docs/examples/paymentRetry.mdx +438 -0
  51. package/docs/examples/waitForEvent.mdx +201 -0
  52. package/docs/features/dlq/callback.mdx +42 -0
  53. package/docs/features/dlq/delete.mdx +29 -0
  54. package/docs/features/dlq/restart.mdx +33 -0
  55. package/docs/features/dlq/resume.mdx +37 -0
  56. package/docs/features/dlq.mdx +39 -0
  57. package/docs/features/failure-callback.mdx +102 -0
  58. package/docs/features/failureFunction/advanced.mdx +36 -0
  59. package/docs/features/failureFunction/reliability.mdx +33 -0
  60. package/docs/features/flow-control/monitor.mdx +22 -0
  61. package/docs/features/flow-control/parallelism.mdx +45 -0
  62. package/docs/features/flow-control/rate-period.mdx +46 -0
  63. package/docs/features/flow-control.mdx +164 -0
  64. package/docs/features/invoke/serveMany.mdx +109 -0
  65. package/docs/features/invoke.mdx +39 -0
  66. package/docs/features/notify.mdx +127 -0
  67. package/docs/features/parallel-steps.mdx +41 -0
  68. package/docs/features/retries/prevent-retries.mdx +140 -0
  69. package/docs/features/retries.mdx +93 -0
  70. package/docs/features/wait-for-event.mdx +104 -0
  71. package/docs/features/wait.mdx +44 -0
  72. package/docs/features/webhooks.mdx +116 -0
  73. package/docs/getstarted.mdx +200 -0
  74. package/docs/howto/cancel.mdx +50 -0
  75. package/docs/howto/changes.mdx +33 -0
  76. package/docs/howto/configure.mdx +42 -0
  77. package/docs/howto/failures.mdx +185 -0
  78. package/docs/howto/get-token.mdx +18 -0
  79. package/docs/howto/local-development/development-server.mdx +130 -0
  80. package/docs/howto/local-development/local-tunnel.mdx +73 -0
  81. package/docs/howto/middlewares.mdx +263 -0
  82. package/docs/howto/migrations.mdx +335 -0
  83. package/docs/howto/multi-region.mdx +107 -0
  84. package/docs/howto/parallel-runs.mdx +52 -0
  85. package/docs/howto/readonly-token.mdx +19 -0
  86. package/docs/howto/realtime/basic.mdx +315 -0
  87. package/docs/howto/realtime/human-in-the-loop.mdx +454 -0
  88. package/docs/howto/redact-fields.mdx +61 -0
  89. package/docs/howto/retry-now.mdx +41 -0
  90. package/docs/howto/schedule.mdx +104 -0
  91. package/docs/howto/security.mdx +143 -0
  92. package/docs/howto/singleton.mdx +137 -0
  93. package/docs/howto/start.mdx +69 -0
  94. package/docs/howto/use-webhooks.mdx +256 -0
  95. package/docs/integrations/aisdk.mdx +316 -0
  96. package/docs/integrations/anthropic.mdx +51 -0
  97. package/docs/integrations/datadog.mdx +69 -0
  98. package/docs/integrations/openai.mdx +87 -0
  99. package/docs/integrations/prometheus.mdx +65 -0
  100. package/docs/integrations/resend.mdx +82 -0
  101. package/docs/llms-txt.mdx +4 -0
  102. package/docs/openapi.yaml +2944 -0
  103. package/docs/pricing.mdx +22 -0
  104. package/docs/quickstarts/astro.mdx +185 -0
  105. package/docs/quickstarts/cloudflare-workers.mdx +190 -0
  106. package/docs/quickstarts/express.mdx +190 -0
  107. package/docs/quickstarts/fastapi.mdx +282 -0
  108. package/docs/quickstarts/flask.mdx +282 -0
  109. package/docs/quickstarts/hono.mdx +221 -0
  110. package/docs/quickstarts/nextjs-fastapi.mdx +147 -0
  111. package/docs/quickstarts/nextjs-flask.mdx +147 -0
  112. package/docs/quickstarts/nuxt.mdx +169 -0
  113. package/docs/quickstarts/platforms.mdx +78 -0
  114. package/docs/quickstarts/solidjs.mdx +161 -0
  115. package/docs/quickstarts/svelte.mdx +170 -0
  116. package/docs/quickstarts/tanstack-start.mdx +205 -0
  117. package/docs/quickstarts/vercel-nextjs.mdx +233 -0
  118. package/docs/roadmap.mdx +8 -0
  119. package/docs/sdk/workflow-js.mdx +4 -0
  120. package/docs/sdk/workflow-py.mdx +4 -0
  121. package/docs/steps/api.mdx +64 -0
  122. package/docs/steps/call.mdx +183 -0
  123. package/docs/steps/cancel.mdx +25 -0
  124. package/docs/steps/createWebhook.mdx +40 -0
  125. package/docs/steps/invoke.mdx +100 -0
  126. package/docs/steps/notify.mdx +105 -0
  127. package/docs/steps/run.mdx +150 -0
  128. package/docs/steps/sleep.mdx +97 -0
  129. package/docs/steps/sleepUntil.mdx +88 -0
  130. package/docs/steps/waitForEvent.mdx +60 -0
  131. package/docs/steps/waitForWebhook.mdx +78 -0
  132. package/docs/steps.mdx +108 -0
  133. package/docs/troubleshooting/general.mdx +331 -0
  134. package/docs/troubleshooting/vercel.mdx +82 -0
  135. package/express.d.mts +19 -2
  136. package/express.d.ts +19 -2
  137. package/express.js +670 -159
  138. package/express.mjs +1 -1
  139. package/h3.d.mts +19 -2
  140. package/h3.d.ts +19 -2
  141. package/h3.js +670 -159
  142. package/h3.mjs +1 -1
  143. package/hono.d.mts +17 -2
  144. package/hono.d.ts +17 -2
  145. package/hono.js +670 -159
  146. package/hono.mjs +1 -1
  147. package/index.d.mts +50 -21
  148. package/index.d.ts +50 -21
  149. package/index.js +686 -171
  150. package/index.mjs +17 -13
  151. package/nextjs.d.mts +40 -2
  152. package/nextjs.d.ts +40 -2
  153. package/nextjs.js +670 -159
  154. package/nextjs.mjs +1 -1
  155. package/package.json +1 -1
  156. package/react-router.d.mts +16 -2
  157. package/react-router.d.ts +16 -2
  158. package/react-router.js +670 -159
  159. package/react-router.mjs +1 -1
  160. package/{serve-many-CG3BFvO3.d.mts → serve-many-BKukvLNl.d.mts} +1 -1
  161. package/{serve-many-iJF1IUXk.d.ts → serve-many-CrLKQpuZ.d.ts} +1 -1
  162. package/solidjs.d.mts +10 -1
  163. package/solidjs.d.ts +10 -1
  164. package/solidjs.js +670 -159
  165. package/solidjs.mjs +1 -1
  166. package/src/platforms/astro.ts +84 -0
  167. package/src/platforms/cloudflare.ts +127 -0
  168. package/src/platforms/express.ts +147 -0
  169. package/src/platforms/h3.ts +105 -0
  170. package/src/platforms/hono.ts +103 -0
  171. package/src/platforms/nextjs.ts +193 -0
  172. package/src/platforms/react-router.ts +92 -0
  173. package/src/platforms/solidjs.ts +59 -0
  174. package/src/platforms/svelte.ts +99 -0
  175. package/src/platforms/tanstack.ts +96 -0
  176. package/src/src/client/dlq.ts +387 -0
  177. package/src/src/client/filter-types.ts +166 -0
  178. package/src/src/client/index.ts +350 -0
  179. package/src/src/client/types.ts +501 -0
  180. package/src/src/client/utils.ts +307 -0
  181. package/src/src/constants.ts +82 -0
  182. package/src/src/context/api/anthropic.ts +58 -0
  183. package/src/src/context/api/base.ts +52 -0
  184. package/src/src/context/api/index.ts +24 -0
  185. package/src/src/context/api/openai.ts +125 -0
  186. package/src/src/context/api/resend.ts +57 -0
  187. package/src/src/context/auto-executor.ts +707 -0
  188. package/src/src/context/context.ts +681 -0
  189. package/src/src/context/index.ts +1 -0
  190. package/src/src/context/provider.ts +37 -0
  191. package/src/src/context/steps.ts +965 -0
  192. package/src/src/error.ts +203 -0
  193. package/src/src/index.ts +13 -0
  194. package/src/src/middleware/default-callbacks.ts +20 -0
  195. package/src/src/middleware/index.ts +2 -0
  196. package/src/src/middleware/logging.ts +39 -0
  197. package/src/src/middleware/manager.ts +148 -0
  198. package/src/src/middleware/middleware.ts +46 -0
  199. package/src/src/middleware/types.ts +72 -0
  200. package/src/src/qstash/headers.ts +397 -0
  201. package/src/src/qstash/step-config.ts +268 -0
  202. package/src/src/qstash/submit-steps.ts +284 -0
  203. package/src/src/serve/authorization.ts +118 -0
  204. package/src/src/serve/index.ts +475 -0
  205. package/src/src/serve/multi-region/handlers.ts +225 -0
  206. package/src/src/serve/multi-region/utils.ts +88 -0
  207. package/src/src/serve/options.ts +241 -0
  208. package/src/src/serve/serve-many.ts +117 -0
  209. package/src/src/serve/utils.ts +11 -0
  210. package/src/src/types.ts +590 -0
  211. package/src/src/utils.ts +141 -0
  212. package/src/src/workflow-parser.ts +472 -0
  213. package/src/src/workflow-requests.ts +575 -0
  214. package/svelte.d.mts +17 -2
  215. package/svelte.d.ts +17 -2
  216. package/svelte.js +670 -159
  217. package/svelte.mjs +1 -1
  218. package/tanstack.d.mts +15 -2
  219. package/tanstack.d.ts +15 -2
  220. package/tanstack.js +670 -159
  221. package/tanstack.mjs +1 -1
  222. package/{types-CekOpKvz.d.ts → types-CrgK5P6p.d.mts} +372 -32
  223. package/{types-CekOpKvz.d.mts → types-CrgK5P6p.d.ts} +372 -32
package/cloudflare.mjs CHANGED
@@ -2,7 +2,7 @@ import {
2
2
  SDK_TELEMETRY,
3
3
  serveBase,
4
4
  serveManyBase
5
- } from "./chunk-DRHEHWMS.mjs";
5
+ } from "./chunk-J3PXPHSB.mjs";
6
6
 
7
7
  // platforms/cloudflare.ts
8
8
  import { startDevServer } from "@upstash/qstash";
@@ -0,0 +1,8 @@
1
+ ---
2
+ title: Workflow Agents Examples
3
+ sidebarTitle: "Examples"
4
+ ---
5
+
6
+ Explore our collection of examples to learn how to build robust agent systems. From architectural patterns to real-world implementations, these examples demonstrate the full potential of our Agents API.
7
+
8
+ <Snippet file="workflow/agent-examples.mdx" />
@@ -0,0 +1,374 @@
1
+ ---
2
+ title: Workflow Agents Features
3
+ sidebarTitle: "Features"
4
+ ---
5
+
6
+ On this page, we explain the features of the Workflow Agents API in more detail.
7
+
8
+ Prerequisites:
9
+ - Setup your first Agent endpoint by following [the Getting Started page](/workflow/agents/getting-started).
10
+ - Install the following packages to define tools:
11
+
12
+ ```bash
13
+ npm i ai mathjs zod @agentic/ai-sdk @agentic/weather @langchain/core @langchain/community
14
+ ```
15
+
16
+ ## Models
17
+
18
+ The `model` is responsible for deciding which tools to call and generating the final response
19
+
20
+ First, add `QSTASH_TOKEN` and `OPENAI_API_KEY` to your environment:
21
+
22
+ ```
23
+ QSTASH_TOKEN="<QSTASH_TOKEN>"
24
+ OPENAI_API_KEY="<OPENAI_API_KEY>"
25
+ ```
26
+
27
+ Next, define the model in your route:
28
+
29
+ ```ts
30
+ import { serve } from "@upstash/workflow/nextjs";
31
+ import { agentWorkflow } from "@upstash/workflow-agents";
32
+
33
+ export const { POST } = serve(async (context) => {
34
+ const agents = agentWorkflow(context);
35
+ const model = agents.openai('gpt-3.5-turbo')
36
+
37
+ // ...
38
+ })
39
+ ```
40
+
41
+ If you want to use an OpenAI compatible provider, you can do so by passing `baseURL` and `apiKey`:
42
+
43
+ ```ts
44
+ const model = agents.openai('deepseek-chat', {
45
+ baseURL: "https://api.deepseek.com",
46
+ apiKey: process.env.DEEPSEEK_API_KEY
47
+ })
48
+ ```
49
+
50
+ If you want to use other providers available on AI SDK, you can import the `create<Provider>` methods exported from provider packages. For example, in order to use Anthropic you can do the following:
51
+
52
+ ```ts
53
+ import { createAnthropic } from "@ai-sdk/anthropic";
54
+
55
+ const model = agents.AISDKModel({
56
+ context,
57
+ provider: createAnthropic,
58
+ providerParams: {
59
+ apiKey: "<ANTHROPIC_API_KEY>",
60
+ },
61
+ });
62
+ ```
63
+
64
+ If you want to configure the calls made to the LLM APIs, you can use the `agentCallParams` parameter:
65
+
66
+ ```ts
67
+ const model = agents.openai('gpt-3.5-turbo', {
68
+ callSettings: {
69
+ timeout: 1000, // optional request timeout
70
+ retries: 0, // optional retries
71
+ flowControl: { // optional flow control
72
+ key: "flow-control-key",
73
+ rate: 10,
74
+ period: "10s",
75
+ parallelism: 10,
76
+ },
77
+ }
78
+ })
79
+ ```
80
+
81
+ Same parameter is available in `agents.AISDKModel` as the `agentCallParams` parameter.
82
+
83
+ ## Tools
84
+
85
+ Next, we will define the tools that our agents will use. The **Agents API** is compatible with both **AI SDK** and **LangChain** tools. This means you can either:
86
+
87
+ - Use existing tools that are compatible with these SDKs.
88
+ - Define your own custom tools that are compatible with these SDKs.
89
+
90
+ This flexibility allows you to tailor the tools to your specific needs while leveraging the power of these frameworks.
91
+
92
+ <CodeGroup>
93
+
94
+ ```ts WorkflowTool (custom)
95
+ import { WorkflowTool } from '@upstash/workflow'
96
+ import { z } from 'zod'
97
+ import * as mathjs from 'mathjs'
98
+
99
+ const tool = new WorkflowTool({
100
+ description:
101
+ 'A tool for evaluating mathematical expressions. ' +
102
+ 'Example expressions: ' +
103
+ "'1.2 * (2 + 4.5)', '12.7 cm to inch', 'sin(45 deg) ^ 2'.",
104
+ schema: z.object({ expression: z.string() }),
105
+ invoke: async ({ expression }) => mathjs.evaluate(expression),
106
+ })
107
+ ```
108
+
109
+ ```ts AI SDK (custom)
110
+ import { z } from 'zod'
111
+ import { tool } from 'ai'
112
+ import * as mathjs from 'mathjs'
113
+
114
+ const mathTool = tool({
115
+ description:
116
+ 'A tool for evaluating mathematical expressions. ' +
117
+ 'Example expressions: ' +
118
+ "'1.2 * (2 + 4.5)', '12.7 cm to inch', 'sin(45 deg) ^ 2'.",
119
+ parameters: z.object({ expression: z.string() }),
120
+ execute: async ({ expression }) => mathjs.evaluate(expression),
121
+ })
122
+ ```
123
+
124
+ ```ts Agentic
125
+ import { createAISDKTools } from '@agentic/ai-sdk'
126
+ import { WeatherClient } from '@agentic/weather'
127
+
128
+ const weather = new WeatherClient()
129
+ const tools = createAISDKTools(weather)
130
+ ```
131
+
132
+ ```ts LangChain (custom)
133
+ import { DynamicStructuredTool } from "@langchain/core/tools";
134
+
135
+ const numberGenerator = new DynamicStructuredTool({
136
+ name: "random-number-generator",
137
+ description: "generates a random number between two input numbers",
138
+ schema: z.object({
139
+ low: z.number().describe("The lower bound of the generated number"),
140
+ high: z.number().describe("The upper bound of the generated number"),
141
+ }),
142
+ func: async ({ low, high }) =>
143
+ (Math.random() * (high - low) + low).toString(), // Outputs still must be strings
144
+ })
145
+ ```
146
+
147
+ ```ts LangChain
148
+ import { WikipediaQueryRun } from '@langchain/community/tools/wikipedia_query_run'
149
+
150
+ const wikiTool = new WikipediaQueryRun({
151
+ topKResults: 1,
152
+ maxDocContentLength: 500,
153
+ })
154
+ ```
155
+
156
+ </CodeGroup>
157
+
158
+ For available toolkits, you can explore the [LangChain Toolkits](https://js.langchain.com/v0.1/docs/modules/agents/tools/toolkits/) or other AI SDK-compatible toolkits like [Agentic](https://agentic.so/sdks/ai-sdk).
159
+
160
+ By default, the Workflow SDK will wrap the execute/invoke methods of the tools you pass with [`context.run`](/workflow/steps/run) to run them as a Workflow step. This means, you can't use steps like context.call, context.notify etc in execute/invoke right away. If you want to define steps in invoke/execute, you can use the `executeAsStep` option:
161
+
162
+ ```ts {12}
163
+ import { WorkflowTool } from '@upstash/workflow'
164
+ import { serve } from '@upstash/workflow/nextjs'
165
+
166
+ export const { POST } = serve(async (context) => {
167
+ const tool = new WorkflowTool({
168
+ description: ...,
169
+ schema: ...,
170
+ invoke: ( ... ) => {
171
+ // make HTTP call inside the tool with context.call:
172
+ await context.call( ... )
173
+ },
174
+ executeAsStep: false
175
+ })
176
+
177
+ // pass the tool to agent
178
+ })
179
+ ```
180
+
181
+ ## Agents
182
+
183
+ After defining a model and tools, we can define agents. Agents are essentially LLM models with access to a set of tools and background knowledge. In Upstash Workflow, agents are defined like this:
184
+
185
+ ```ts route.ts
186
+ import { serve } from "@upstash/workflow/nextjs";
187
+ import { agentWorkflow } from "@upstash/workflow-agents";
188
+ import { WikipediaQueryRun } from "@langchain/community/tools/wikipedia_query_run";
189
+
190
+ export const { POST } = serve(async (context) => {
191
+ const agents = agentWorkflow(context);
192
+ const model = agents.openai('gpt-3.5-turbo')
193
+
194
+ const researcherAgent = agents.agent({
195
+ model,
196
+ name: 'academic',
197
+ maxSteps: 2,
198
+ tools: {
199
+ wikiTool: new WikipediaQueryRun({
200
+ topKResults: 1,
201
+ maxDocContentLength: 500,
202
+ })
203
+ },
204
+ background:
205
+ 'You are researcher agent with access to Wikipedia. ' +
206
+ 'Utilize Wikipedia as much as possible for correct information',
207
+ })
208
+ })
209
+ ```
210
+
211
+ The parameters for defining an agent are as follows:
212
+
213
+ - **`model`**: The LLM model that the agent will use.
214
+ - **`name`**: The name of the agent. This name will be used when naming the [context.call steps](/workflow/steps/call) for this agent. `context.call` is used when calling the LLM provider (such as OpenAI).
215
+ - **`maxSteps`**: The maximum number of times this agent can call the LLM provider (e.g., OpenAI).
216
+ - **`tools`**: The list of tools available to the agent for completing tasks.
217
+ - **`background`**: A description of the agent, which is used as a system prompt to provide context for the agent's behavior.
218
+
219
+ ## Tasks
220
+
221
+ Now that we have agents defined, the only thing left is to assign tasks to them. A **task** is simply a prompt passed to the agent.
222
+
223
+ There are two ways to create a task:
224
+
225
+ 1. **Single Agent Task**: The task is assigned to a single agent, which will complete it using the tools available to it.
226
+
227
+ 2. **Multiple Agent Task**: A **manager agent** is used to decide which agents will be involved and in what order. The manager agent makes this decision based on the task prompt, the agents' backgrounds, and the tools available to them.
228
+
229
+ ### Single Agent
230
+
231
+ ```ts Single Agent {22-27}
232
+ import { serve } from "@upstash/workflow/nextjs";
233
+ import { agentWorkflow } from "@upstash/workflow-agents";
234
+ import { WikipediaQueryRun } from "@langchain/community/tools/wikipedia_query_run";
235
+
236
+ export const { POST } = serve(async (context) => {
237
+ const agents = agentWorkflow(context);
238
+ const model = agents.openai('gpt-3.5-turbo');
239
+
240
+ const researcherAgent = agents.agent({
241
+ model,
242
+ name: 'academic',
243
+ maxSteps: 2,
244
+ tools: {
245
+ wikiTool: new WikipediaQueryRun({
246
+ topKResults: 1,
247
+ maxDocContentLength: 500,
248
+ })
249
+ },
250
+ background:
251
+ 'You are researcher agent with access to Wikipedia. ' +
252
+ 'Utilize Wikipedia as much as possible for correct information',
253
+ });
254
+
255
+ const task = agents.task({
256
+ agent: researcherAgent,
257
+ prompt: "Tell me about 5 topics in advanced physics.",
258
+ });
259
+ const { text } = await task.run();
260
+ console.log("result:", text)
261
+ })
262
+ ```
263
+
264
+ As response to the task, the agent generates the following response:
265
+
266
+ ```
267
+ Here are summaries of 5 topics in advanced physics:
268
+
269
+ 1. **Quantum Mechanics**: Quantum mechanics is a fundamental theory that describes the behavior of nature at and below the scale of atoms. It is the foundation of all quantum physics, including quantum chemistry, quantum field theory, quantum technology, and quantum information science. Quantum mechanics can describe many systems that classical physics cannot.
270
+
271
+ 2. **General Relativity**: General relativity, also known as Einstein's theory of gravity, is the geometric theory of gravitation published by Albert Einstein in 1915. It is the current description of gravitation in modern physics, generalizing special relativity and refining Newton's law of universal gravitation. General relativity provides a unified description of gravity as a geometric property of space and time.
272
+
273
+ 3. **Particle Physics**: Particle physics, also known as high-energy physics, is the study of fundamental particles and forces that constitute matter and radiation. The field also studies combinations of elementary particles up to the scale of protons and neutrons. Fundamental particles in the universe are classified in the Standard Model as fermions (matter particles) and bosons (force-carrying particles).
274
+
275
+ 4. **Astrophysics**: Astrophysics is a science that applies the methods and principles of physics and chemistry to the study of astronomical objects and phenomena. It seeks to ascertain the nature of heavenly bodies and is distinct from celestial mechanics, which focuses on the positions and motions of objects in space. Subjects studied in astrophysics include the Sun, stars, galaxies, and the universe.
276
+
277
+ 5. **String Theory**: String theory is a theoretical framework in physics where point-like particles are replaced by one-dimensional objects called strings. These strings describe how they propagate through space and interact with each other. On distance scales larger than the string scale, a string behaves like a particle, with its properties determined by the vibrational state of the string
278
+ ```
279
+
280
+ Here is the logs on Upstash Console:
281
+
282
+ <img src="/img/workflow/agents/logs/logs-single.png" alt="Single-agent workflow logs" />
283
+
284
+ In the logs, you can see that the **academic agent** was called. It decided to invoke **wikiTool** five times in parallel. Once the tool requests were completed, the agent summarized the results from the individual calls in one final response and returned the outcome.
285
+
286
+ ### Multi Agents
287
+
288
+ ```ts Multi Agents {45-53}
289
+ import { serve } from "@upstash/workflow/nextjs";
290
+ import { agentWorkflow } from "@upstash/workflow-agents";
291
+ import { WikipediaQueryRun } from "@langchain/community/tools/wikipedia_query_run";
292
+ import * as mathjs from 'mathjs'
293
+ import { tool } from "ai";
294
+ import { z } from "zod";
295
+
296
+ export const { POST } = serve(async (context) => {
297
+ const agents = agentWorkflow(context);
298
+ const model = agents.openai('gpt-4o');
299
+
300
+ const researcherAgent = agents.agent({
301
+ model,
302
+ name: 'academic',
303
+ maxSteps: 2,
304
+ tools: {
305
+ wikiTool: new WikipediaQueryRun({
306
+ topKResults: 1,
307
+ maxDocContentLength: 500,
308
+ })
309
+ },
310
+ background:
311
+ 'You are researcher agent with access to Wikipedia. ' +
312
+ 'Utilize Wikipedia as much as possible for correct information',
313
+ });
314
+
315
+ const mathAgent = agents.agent({
316
+ model,
317
+ name: "mathematician",
318
+ maxSteps: 2,
319
+ tools: {
320
+ calculate: tool({
321
+ description:
322
+ 'A tool for evaluating mathematical expressions. ' +
323
+ 'Example expressions: ' +
324
+ "'1.2 * (2 + 4.5)', '12.7 cm to inch', 'sin(45 deg) ^ 2'." +
325
+ "only call this tool if you need to calculate a mathematical expression." +
326
+ "when writing an expression, don't use words like 'thousand' or 'million'",
327
+ parameters: z.object({ expression: z.string() }),
328
+ execute: async ({ expression }) => mathjs.evaluate(expression),
329
+ }),
330
+ },
331
+ background:
332
+ "You are a mathematician agent which can utilize" +
333
+ "a calculator to compute expressions"
334
+ })
335
+
336
+ const task = agents.task({
337
+ model,
338
+ maxSteps: 3,
339
+ agents: [researcherAgent, mathAgent],
340
+ prompt: "Tell me about 3 cities in Japan and calculate the sum of their populations",
341
+ });
342
+ const { text } = await task.run();
343
+ console.log("result:", text)
344
+ })
345
+ ```
346
+
347
+ As response to the task, the agents generate the following response:
348
+
349
+ ```
350
+ Here is a brief overview of three cities in Japan:
351
+
352
+ ### Tokyo
353
+ - **Official Name**: Tokyo Metropolis
354
+ - **Population**: Over 14 million in the city proper as of 2023.
355
+ - **Significance**: Capital of Japan and one of the most populous urban areas in the world.
356
+
357
+ ### Osaka
358
+ - **Japanese Name**: 大éå¸ (Åsaka-shi)
359
+ - **Population**: 2.7 million as per the 2020 census.
360
+ - **Significance**: Capital and most populous city in Osaka Prefecture, third-most populous city in Japan.
361
+
362
+ ### Kyoto
363
+ - **Japanese Name**: 京é½å¸ (KyÅto-shi)
364
+ - **Population**: 1.46 million as of 2020.
365
+ - **Significance**: Capital city of Kyoto Prefecture, ninth-most populous city in Japan.
366
+
367
+ The sum of their populations is approximately 18.16 million.
368
+ ```
369
+
370
+ Here are the logs on Upstash Console:
371
+
372
+ <img src="/img/workflow/agents/logs/logs-multi.png" alt="Multi-agent workflow logs" />
373
+
374
+ The logs show that the `Manager LLM` first called the `academic` agent. The `academic` agent used the `wikiTool` three times, each with a different Japanese city, and summarized the results. Next, the `Manager LLM` called the `mathematician` agent, which used its `calculate` tool to compute the total population of the three cities and returned the result to the `Manager LLM`. With information about the cities and their total population, the `Manager LLM` generated the final response.
@@ -0,0 +1,139 @@
1
+ ---
2
+ title: Workflow Agents Getting Started
3
+ sidebarTitle: "Getting Started"
4
+ ---
5
+
6
+ In this guide, we will be using **Next.js**. If you're working with a different supported framework, you can find instructions on how to define a workflow endpoint in the [quickstarts](/workflow/quickstarts/platforms).
7
+
8
+ If you're new to **Upstash Workflow**, it's a good idea to start by exploring the [Local Development documentation](/workflow/howto/local-development/development-server). This guide will help you set up and use Upstash Workflow in a local environment.
9
+
10
+ ## Installation
11
+
12
+ First, create a new Next.js project with:
13
+
14
+ ```
15
+ npx create-next-app@latest [project-name] [options]
16
+ ```
17
+
18
+ Then, install the following packages:
19
+
20
+ ```
21
+ npm i @upstash/workflow @upstash/workflow-agents ai zod
22
+ ```
23
+
24
+ ## Start the development server
25
+
26
+ Since you are using `@upstash/workflow`, set `QSTASH_DEV=true` in your `.env.local` file and the SDK will download, start, and connect to a local QStash development server automatically — no tokens or signing keys to copy over. Add your `OPENAI_API_KEY` alongside it:
27
+
28
+ ```txt .env.local
29
+ QSTASH_DEV=true
30
+
31
+ OPENAI_API_KEY=<OPENAI_API_KEY>
32
+ ```
33
+
34
+ For manual setup, custom ports, and the `registerQStashDev()` helper for Next.js edge routes, see the [Development Server guide](/workflow/howto/local-development/development-server).
35
+
36
+ ## Define an endpoint
37
+
38
+ Next, we will define the endpoint to run the agent.
39
+
40
+ ```ts app/workflow/route.ts
41
+ import { z } from "zod";
42
+ import { tool } from "ai";
43
+
44
+ import { serve } from "@upstash/workflow/nextjs";
45
+ import { agentWorkflow } from "@upstash/workflow-agents";
46
+
47
+ export const { POST } = serve<{ prompt: string }>(async (context) => {
48
+ const prompt = context.requestPayload.prompt
49
+ const agents = agentWorkflow(context)
50
+ const model = agents.openai('gpt-3.5-turbo')
51
+
52
+ const communicatorAgent = agents.agent({
53
+ model,
54
+ name: 'communicatorAgent',
55
+ maxSteps: 2,
56
+ tools: {
57
+ communicationTool: tool({
58
+ description: 'A tool for informing the caller about your inner thoughts',
59
+ parameters: z.object({ message: z.string() }),
60
+ execute: async ({ message }) => {
61
+ console.log("Inner thought:", message)
62
+ return "success"
63
+ }
64
+ })
65
+ },
66
+ background:
67
+ 'Answer questions directed towards you.' +
68
+ ' You have access to a tool to share your inner thoughts' +
69
+ ' with the caller. Utilize this tool at least once before' +
70
+ ' answering the prompt. In your inner thougts, briefly' +
71
+ ' explain what you will talk about and why. Keep your' +
72
+ ' answers brief.',
73
+ })
74
+
75
+ const task = agents.task({
76
+ agent: communicatorAgent,
77
+ prompt
78
+ })
79
+
80
+ const { text } = await task.run()
81
+
82
+ console.log("Final response:", text);
83
+ })
84
+ ```
85
+
86
+ You can refer to the documentations for [defining a workflow endpoint](/workflow/basics/serve) and [the Agents API features](/workflow/agents/features) to learn more.
87
+
88
+ ## Calling the Endpoint
89
+
90
+ To run the endpoint, first run the Next.js app with:
91
+
92
+ ```bash
93
+ npm run dev
94
+ ```
95
+
96
+ Then, we call the endpoint using [the Workflow Client](/workflow/basics/client):
97
+
98
+ ```ts
99
+ import { Client } from "@upstash/workflow";
100
+
101
+ const client = new Client({
102
+ baseUrl: process.env.QSTASH_URL,
103
+ token: process.env.QSTASH_TOKEN!,
104
+ })
105
+
106
+ const workflowRunId = await client.trigger({
107
+ url: "http://127.0.0.1:3000/workflow",
108
+ body: { prompt: "Explain the future of space exploration" }
109
+ })
110
+
111
+ console.log(workflowRunId);
112
+ ```
113
+
114
+ <Tip>
115
+ If you are using a local tunnel, replace the url above (`http://127.0.0.1:3000`)
116
+ with the public URL.
117
+ </Tip>
118
+
119
+
120
+ In the console where you run the Next.js app, you should see logs like this:
121
+
122
+ ```
123
+ Inner thought: I will discuss the future of space
124
+ exploration and the potential advancements in
125
+ technology and missions.
126
+
127
+ Final response: The future of space exploration
128
+ holds exciting possibilities with advancements
129
+ in technology, potential manned missions to
130
+ Mars, increased commercial space travel,
131
+ and exploration of distant celestial
132
+ bodies.
133
+ ```
134
+
135
+ If you [run the same endpoint using a local tunnel](/workflow/howto/local-development/local-tunnel), you can also see how Upstash Workflow runs the agent in steps:
136
+
137
+ <img src="/img/workflow/agents/logs/logs-getting-started.png" alt="First agent workflow run logs" />
138
+
139
+ Each tool invocation and LLM call is a seperate step. Our agent first made a call to OpenAI to decide whether to use a tool or reply right away. OpenAI responded with a request to use the tool `communicationTool`. Tool was executed and OpenAI was called with the result of the tool. OpenAI then responded with the final response.
@@ -0,0 +1,40 @@
1
+ ---
2
+ title: Workflow Agents Overview
3
+ sidebarTitle: "Overview"
4
+ ---
5
+
6
+ The **Agents API** of Upstash Workflow enables you to:
7
+ - Execute an individual agent or facilitate collaboration among multiple agents.
8
+ - Integrate any tool compatible with AI SDK or LangChain.
9
+ - Reliably invoke agents without concerns about timeouts or transient errors.
10
+ - Unlike mainstream agent frameworks, we prioritize debuggability and extensibility.
11
+
12
+ To get started, you can refer to the [Getting Started page](/workflow/agents/getting-started). For more details about the features, you can refer to [the Features page](/workflow/agents/features).
13
+
14
+ <Note>
15
+ This feature is not yet available in
16
+ [workflow-py](https://github.com/upstash/workflow-py). See our
17
+ [Roadmap](/workflow/roadmap) for feature parity plans and
18
+ [Changelog](/workflow/changelog) for updates.
19
+ </Note>
20
+
21
+ ## Agent Patterns
22
+
23
+ If you're interested, you can also explore our rich examples that showcase how various patterns can be built using the Agents API:
24
+
25
+ <CardGroup cols={2}>
26
+ <Card title="Prompt Chaining" icon="link" href="/workflow/agents/patterns/prompt-chaining">
27
+ Sequential LLM calls where each output becomes the input for the next, enabling structured reasoning and step-by-step task completion.
28
+ </Card>
29
+ <Card title="Evaluator-optimizer" icon="arrows-rotate" href="/workflow/agents/patterns/evaluator-optimizer">
30
+ A feedback loop where LLM outputs are evaluated and refined iteratively to improve accuracy and relevance.
31
+ </Card>
32
+ <Card title="Parallelization" icon="arrows-to-dot" href="/workflow/agents/patterns/parallelization">
33
+ Distribute tasks across multiple LLMs and aggregate the results for efficient handling of complex or large-scale operations.
34
+ </Card>
35
+ <Card title="Orchestrator-workers" icon="sparkles" href="/workflow/agents/patterns/orchestrator-workers">
36
+ A central orchestrator directs multiple worker LLMs to complete subtasks and synthesize their outputs for complex operations.
37
+ </Card>
38
+ </CardGroup>
39
+
40
+ <Snippet file="workflow/agent-examples.mdx" />
@@ -0,0 +1,72 @@
1
+ ---
2
+ title: "Evaluator-Optimizer"
3
+ ---
4
+
5
+ <img src="/img/workflow/agents/diagram/evaluator-diagram.png" alt="Evaluator-optimizer workflow diagram" />
6
+
7
+ In this example, the generator creates output and passes it to the evaluator, which evaluates the response. If the evaluation fails, the evaluator returns corrections, and the generator is called again using the corrected output.
8
+
9
+ ```ts
10
+ import { serve } from "@upstash/workflow/nextjs";
11
+ import { agentWorkflow } from "@upstash/workflow-agents";
12
+
13
+ export const { POST } = serve(async (context) => {
14
+ const agents = agentWorkflow(context);
15
+ const model = agents.openai('gpt-3.5-turbo');
16
+
17
+ // Generator agent that generates content
18
+ const generator = agents.agent({
19
+ model,
20
+ name: 'generator',
21
+ maxSteps: 1,
22
+ background: 'You are an agent that generates text based on a prompt.',
23
+ tools: {}
24
+ });
25
+
26
+ // Evaluator agent that evaluates the text and gives corrections
27
+ const evaluator = agents.agent({
28
+ model,
29
+ name: 'evaluator',
30
+ maxSteps: 1,
31
+ background: 'You are an agent that evaluates the generated text and provides corrections if needed.',
32
+ tools: {}
33
+ });
34
+
35
+ let generatedText = '';
36
+ let evaluationResult = '';
37
+
38
+ const prompt = "Generate a short explanation of quantum mechanics.";
39
+ let nextPrompt = prompt;
40
+ for (let i = 0; i < 3; i++) {
41
+ // Construct prompt for generator:
42
+ // - If there's no evaluation, use the original prompt
43
+ // - If there's an evaluation, provide the prompt, the last generated text, and the evaluator's feedback
44
+ if (evaluationResult && evaluationResult !== "PASS") {
45
+ nextPrompt = `Please revise the answer to the question "${prompt}". Previous answer was: "${generatedText}", which received this feedback: "${evaluationResult}".`;
46
+ }
47
+
48
+ // Generate content
49
+ const generatedResponse = await agents.task({ agent: generator, prompt: nextPrompt }).run();
50
+ generatedText = generatedResponse.text
51
+
52
+ // Evaluate the generated content
53
+ const evaluationResponse = await agents.task({ agent: evaluator, prompt: `Evaluate and provide feedback for the following text: ${generatedText}` }).run();
54
+ evaluationResult = evaluationResponse.text
55
+
56
+ // If the evaluator accepts the content (i.e., "PASS"), stop
57
+ if (evaluationResult.includes("PASS")) {
58
+ break;
59
+ }
60
+ }
61
+
62
+ console.log(generatedText);
63
+ });
64
+ ```
65
+
66
+ <img src="/img/workflow/agents/logs/logs-evaluator.png" alt="Evaluator-optimizer workflow logs" />
67
+
68
+ In response to the prompt, our agents generate this response:
69
+
70
+ ```
71
+ Quantum mechanics is a branch of physics that describes the behavior of particles at the smallest scales, such as atoms and subatomic particles. It introduces the concept of quantized energy levels, wave-particle duality, and probabilistic nature of particles. In quantum mechanics, particles can exist in multiple states simultaneously until measured, and their behavior is governed by mathematical equations known as wave functions. This theory has revolutionized our understanding of the fundamental building blocks of the universe and has led to the development of technologies like quantum computing and quantum cryptography.
72
+ ```