@upstash/workflow 1.4.0 → 1.5.1-canary.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 +375 -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 +575 -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 +114 -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 +2946 -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
@@ -0,0 +1,95 @@
1
+ ---
2
+ title: "Orchestrator-Workers"
3
+ ---
4
+
5
+ <img src="/img/workflow/agents/diagram/orchestrator-diagram.png" alt="Orchestrator-workers workflow diagram" />
6
+
7
+ This workflow uses an orchestrator to direct multiple worker agents to handle different subtasks, then synthesizes their outputs.
8
+
9
+ ```ts
10
+ import { serve } from "@upstash/workflow/nextjs";
11
+ import { agentWorkflow } from "@upstash/workflow-agents";
12
+ import { WikipediaQueryRun } from "@langchain/community/tools/wikipedia_query_run";
13
+
14
+ const wikiTool = new WikipediaQueryRun({
15
+ topKResults: 1,
16
+ maxDocContentLength: 500,
17
+ })
18
+
19
+ export const { POST } = serve(async (context) => {
20
+ const agents = agentWorkflow(context);
21
+ const model = agents.openai('gpt-4o');
22
+
23
+ // Worker agents
24
+ const worker1 = agents.agent({
25
+ model,
26
+ name: 'worker1',
27
+ tools: { wikiTool },
28
+ maxSteps: 3,
29
+ background: 'You are a worker agent that answers general questions about advanced physics.'
30
+ });
31
+
32
+ const worker2 = agents.agent({
33
+ model,
34
+ name: 'worker2',
35
+ tools: { wikiTool },
36
+ maxSteps: 3,
37
+ background: 'You are a worker agent that answers questions about quantum mechanics.'
38
+ });
39
+
40
+ const worker3 = agents.agent({
41
+ model,
42
+ name: 'worker3',
43
+ tools: { wikiTool },
44
+ maxSteps: 3,
45
+ background: 'You are a worker agent that answers questions about relativity.'
46
+ });
47
+
48
+ // Synthesizing results
49
+ const task = agents.task({
50
+ model,
51
+ prompt: `Create a Q&A for advanced topics in physics`,
52
+ agents: [worker1, worker2, worker3],
53
+ maxSteps: 3,
54
+ })
55
+ const { text } = await task.run();
56
+
57
+ console.log(text);
58
+ });
59
+ ```
60
+
61
+ If you wish to manually use the model results instead of utilizing a [manager LLM](/workflow/agents/features#multi-agents) as we did in this example, see the [parallelization example](/workflow/agents/patterns/parallelization)
62
+
63
+ <img src="/img/workflow/agents/logs/logs-manager.png" alt="Orchestrator manager workflow logs" />
64
+
65
+ In response to the prompt, the agents create the following response:
66
+
67
+ ```
68
+ ### Quantum Mechanics
69
+
70
+ **Q: What is quantum mechanics?**
71
+ A: Quantum mechanics is a fundamental theory in physics that describes the behavior of nature at the atomic and subatomic levels. It serves as the foundation for all quantum physics, including quantum chemistry, quantum field theory, quantum technology, and quantum information science.
72
+
73
+ **Q: What are some key principles of quantum mechanics?**
74
+ A:
75
+ 1. **Wave-Particle Duality**: Particles exhibit both wave-like and particle-like properties.
76
+ 2. **Uncertainty Principle**: Certain pairs of physical properties, like position and momentum, cannot be simultaneously measured with arbitrary precision.
77
+ 3. **Quantum Superposition**: A quantum system can exist in multiple states at once until it is measured.
78
+ 4. **Quantum Entanglement**: Particles become interconnected such that the state of one influences the state of another, regardless of distance.
79
+ 5. **Quantization**: Energy levels in quantum systems are discrete.
80
+ 6. **Probability and Wave Functions**: Quantum systems are described by wave functions, which provide probabilities of finding a system in a particular state.
81
+ 7. **Observer Effect**: Measurement affects the system being observed.
82
+
83
+ ### Relativity
84
+
85
+ **Q: What is the theory of relativity?**
86
+ A: Developed by Albert Einstein, the theory of relativity encompasses two interrelated theories: special relativity and general relativity.
87
+
88
+ **Q: What is special relativity?**
89
+ A: Proposed by Einstein in 1905, special relativity addresses the relationship between space and time in the absence of gravity. It is based on two key postulates: the invariance of physical laws in all inertial frames and the constancy of the speed of light in a vacuum.
90
+
91
+ **Q: What is general relativity?**
92
+ A: Published by Einstein in 1915, general relativity is a geometric theory of gravitation. It describes gravity as a geometric property of space and time, or four-dimensional spacetime, and explains how massive objects cause a distortion in spacetime.
93
+
94
+ These topics challenge classical intuitions and have led to significant advancements in our understanding of the universe and the development of new technologies.
95
+ ```
@@ -0,0 +1,77 @@
1
+ ---
2
+ title: "Parallelization"
3
+ ---
4
+
5
+ <img src="/img/workflow/agents/diagram/parallel-diagram.png" alt="Parallel agent workflow diagram" />
6
+
7
+ This workflow calls multiple agents simultaneously to handle tasks, and then aggregates their results.
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
+ // Define worker agents
18
+ const worker1 = agents.agent({
19
+ model,
20
+ name: 'worker1',
21
+ maxSteps: 1,
22
+ background: 'You are an agent that explains quantum physics.',
23
+ tools: {}
24
+ });
25
+
26
+ const worker2 = agents.agent({
27
+ model,
28
+ name: 'worker2',
29
+ maxSteps: 1,
30
+ background: 'You are an agent that explains relativity.',
31
+ tools: {}
32
+ });
33
+
34
+ const worker3 = agents.agent({
35
+ model,
36
+ name: 'worker3',
37
+ maxSteps: 1,
38
+ background: 'You are an agent that explains string theory.',
39
+ tools: {}
40
+ });
41
+
42
+ // Await results
43
+ const [result1, result2, result3] = await Promise.all([
44
+ agents.task({ agent: worker1, prompt: "Explain quantum physics." }).run(),
45
+ agents.task({ agent: worker2, prompt: "Explain relativity." }).run(),
46
+ agents.task({ agent: worker3, prompt: "Explain string theory." }).run(),
47
+ ]);
48
+
49
+ // Aggregating results
50
+ const aggregator = agents.agent({
51
+ model,
52
+ name: 'aggregator',
53
+ maxSteps: 1,
54
+ background: 'You are an agent that summarizes multiple answers.',
55
+ tools: {}
56
+ });
57
+
58
+ const task = await agents.task({
59
+ agent: aggregator,
60
+ prompt: `Summarize these three explanations: ${result1.text}, ${result2.text}, ${result3.text}`
61
+ })
62
+ const finalSummary = await task.run();
63
+
64
+ console.log(finalSummary.text);
65
+ });
66
+
67
+ ```
68
+
69
+ You can also see how the same thing can be achieved using an manager agent in [orchestrator-workers example](/workflow/agents/patterns/orchestrator-workers).
70
+
71
+ <img src="/img/workflow/agents/logs/logs-parallel.png" alt="Parallel agent workflow logs" />
72
+
73
+ In response to the prompt, our agents generate this response:
74
+
75
+ ```
76
+ Quantum physics explores the behavior of very small particles, such as atoms and subatomic particles, in the strange world of quantum mechanics, where particles can exist in multiple states simultaneously. Key principles include superposition and entanglement, leading to technological advancements like quantum computers. Relativity, developed by Albert Einstein, consists of special relativity and general relativity, explaining the behavior of objects moving at high speeds and the warping of spacetime by massive objects. String theory proposes that the universe's fundamental building blocks are tiny vibrating strings, aiming to unify the four fundamental forces of nature and suggest extra dimensions beyond the familiar ones.
77
+ ```
@@ -0,0 +1,84 @@
1
+ ---
2
+ title: "Prompt Chaining"
3
+ ---
4
+
5
+ <img src="/img/workflow/agents/diagram/prompt-chain-diagram.png" alt="Prompt chaining workflow diagram" />
6
+
7
+ This workflow involves chaining multiple LLM calls, where the output of one agent becomes the input for the next agent.
8
+
9
+ ```ts
10
+ import { serve } from "@upstash/workflow/nextjs";
11
+ import { agentWorkflow } from "@upstash/workflow-agents";
12
+ import { WikipediaQueryRun } from "@langchain/community/tools/wikipedia_query_run";
13
+
14
+ export const { POST } = serve(async (context) => {
15
+ const agents = agentWorkflow(context);
16
+ const model = agents.openai('gpt-3.5-turbo');
17
+
18
+ const agent1 = agents.agent({
19
+ model,
20
+ name: 'firstAgent',
21
+ maxSteps: 1,
22
+ background: 'You are an agent that lists famous physicists.',
23
+ tools: {}
24
+ });
25
+
26
+ const agent2 = agents.agent({
27
+ model,
28
+ name: 'secondAgent',
29
+ // set to 2 as this agent will first request tools
30
+ // and then summarize them:
31
+ maxSteps: 2,
32
+ background:
33
+ 'You are an agent that describes the work of' +
34
+ ' the physicists listed in the previous prompt.',
35
+ tools: {
36
+ wikiTool: new WikipediaQueryRun({
37
+ topKResults: 1,
38
+ maxDocContentLength: 500,
39
+ })
40
+ }
41
+ });
42
+
43
+ const agent3 = agents.agent({
44
+ model,
45
+ name: 'thirdAgent',
46
+ maxSteps: 1,
47
+ background:
48
+ 'You are an agent that summarizes the ' +
49
+ 'works of the physicists mentioned previously.',
50
+ tools: {}
51
+ });
52
+
53
+ // Chaining agents
54
+ const firstOutput = await agents.task({
55
+ agent: agent1,
56
+ prompt: "List 3 famous physicists."
57
+ }).run();
58
+
59
+ const secondOutput = await agents.task({
60
+ agent: agent2,
61
+ prompt: `Describe the work of: ${firstOutput.text}`
62
+ }).run();
63
+
64
+
65
+ const { text } = await agents.task({
66
+ agent: agent3,
67
+ prompt: `Summarize: ${secondOutput.text}`
68
+ }).run();
69
+
70
+ console.log(text);
71
+ });
72
+ ```
73
+
74
+ <img src="/img/workflow/agents/logs/logs-chain.png" alt="Prompt chaining workflow logs" />
75
+
76
+ In response to the prompt, our agents generate this response:
77
+
78
+ ```
79
+ Albert Einstein was a German physicist known for his theory of relativity and the famous equation E=mc^2. He made significant contributions to quantum mechanics and was awarded the Nobel Prize in Physics in 1921.
80
+
81
+ Isaac Newton, an English polymath, was a key figure in the Scientific Revolution and the Enlightenment. He is famous for his laws of motion and universal gravitation, as outlined in his book "Philosophiæ Naturalis Principia Mathematica."
82
+
83
+ Marie Curie, a Polish-French physicist and chemist, conducted pioneering research on radioactivity and was the first woman to win a Nobel Prize. She is the only person to win Nobel Prizes in two scientific fields and her work has had a lasting impact on physics and chemistry.
84
+ ```
@@ -0,0 +1,57 @@
1
+ ---
2
+ title: "Include At Least One Step in Workflow"
3
+ sidebarTitle: "At Least One Step"
4
+ ---
5
+
6
+ Every workflow must include at least one step execution with `context.run`. If no steps are defined, the workflow will throw a `Failed to authenticate Workflow request.` error.
7
+
8
+ <CodeGroup>
9
+
10
+ ```typescript ❌ Missing steps - TypeScript
11
+ export const { POST } = serve<string>(async (context) => {
12
+ const input = context.requestPayload
13
+
14
+ // 👇 Problem: No context.run call
15
+ console.log("Processing input:", input)
16
+
17
+ // This workflow will fail with "Failed to authenticate Workflow request."
18
+ })
19
+ ```
20
+
21
+ ```typescript ✅ Correct - TypeScript
22
+ export const { POST } = serve<string>(async (context) => {
23
+ const input = context.requestPayload
24
+
25
+ // 👇 At least one step is required
26
+ await context.run("dummy-step", async () => {
27
+ return
28
+ })
29
+ })
30
+ ```
31
+
32
+ ```python ❌ Missing steps - Python
33
+ @serve.post("/api/example")
34
+ async def example(context: AsyncWorkflowContext[str]) -> None:
35
+ input = context.request_payload
36
+
37
+ # 👇 Problem: No context.run call
38
+ print("Processing input:", input)
39
+
40
+ # This workflow will fail with "Failed to authenticate Workflow request."
41
+ ```
42
+
43
+ ```python ✅ Correct - Python
44
+ @serve.post("/api/example")
45
+ async def example(context: AsyncWorkflowContext[str]) -> None:
46
+ input = context.request_payload
47
+
48
+ # 👇 At least one step is required
49
+ async def _dummy_step():
50
+ return
51
+
52
+ await context.run("dummy-step", _dummy_step)
53
+ ```
54
+
55
+ </CodeGroup>
56
+
57
+ Even for the placeholder implementations, you must include one dummy step for the Workflow authentication mechanism to function properly.
@@ -0,0 +1,52 @@
1
+ ---
2
+ title: "Execute Business Logic in context.run"
3
+ sidebarTitle: "Business Logic in Steps"
4
+ ---
5
+
6
+ Your workflow endpoint will be called multiple times during a workflow run. Therefore:
7
+
8
+ - Place your business logic code inside the `context.run` function for each step
9
+ - Code outside `context.run` only serves to connect steps
10
+
11
+ <CodeGroup>
12
+
13
+ ```typescript api/workflow/route.ts
14
+ export const { POST } = serve<string>(async (context) => {
15
+ const input = context.requestPayload
16
+
17
+ const result = await context.run("step-1", () => {
18
+ return { success: true }
19
+ })
20
+
21
+ console.log("This log will appear multiple times")
22
+
23
+ await context.run("step-2", () => {
24
+ console.log("This log will appear just once")
25
+ console.log("Step 1 status is:", result.success)
26
+ })
27
+ })
28
+ ```
29
+
30
+ ```python main.py
31
+ @serve.post("/api/example")
32
+ async def example(context: AsyncWorkflowContext[str]) -> None:
33
+ input = context.request_payload
34
+
35
+ async def _step_1() -> Dict:
36
+ return {"success": True}
37
+
38
+ result = await context.run("step-1", _step_1)
39
+
40
+ print("This log will appear multiple times")
41
+
42
+ async def _step_2() -> None:
43
+ print("This log will appear just once")
44
+ print("Step 1 status is:", result["success"])
45
+
46
+ await context.run("step-2", _step_2)
47
+
48
+ ```
49
+
50
+ </CodeGroup>
51
+
52
+ If you are curious about why an endpoint is called multiple times, see [how Workflow works](/workflow/basics/how).
@@ -0,0 +1,132 @@
1
+ ---
2
+ title: "Avoid Non-deterministic Code Outside context.run"
3
+ sidebarTitle: "Deterministic Code"
4
+ ---
5
+
6
+ A workflow endpoint should always produce the same results, even if it's called multiple times. Avoid:
7
+
8
+ - Non-idempotent functions
9
+ - Time-dependent code
10
+ - Randomness
11
+
12
+ Example of what to avoid:
13
+
14
+ <CodeGroup>
15
+
16
+ ```typescript ❌ Non-idempotent functions - TypeScript
17
+ export const { POST } = serve<{ entryId: string }>(async (context) => {
18
+ const { entryId } = context.requestPayload;
19
+
20
+ // 👇 Problem: Non-idempotent function outside context.run:
21
+ const result = await getResultFromDb(entryId);
22
+ if (result.return) {
23
+ return;
24
+ }
25
+
26
+ // ...
27
+ })
28
+ ```
29
+
30
+ ```typescript ❌ Time-dependent code - TypeScript
31
+ export const { POST } = serve<string>(async (context) => {
32
+ const input = context.requestPayload
33
+
34
+ // 👇 Problem: time-dependent code
35
+ if (Date.now() % 5 == 2) {
36
+ await context.run("step-1", () => {
37
+ // ...
38
+ })
39
+ } else {
40
+ await context.run("step-2", () => {
41
+ // ...
42
+ })
43
+ }
44
+ })
45
+ ```
46
+
47
+ ```typescript ❌ Random code - TypeScript
48
+ export const { POST } = serve<string>(async (context) => {
49
+ const input = context.requestPayload
50
+
51
+ // 👇 Problem: random code
52
+ if (Math.floor(Math.random() * 10) % 5 == 2) {
53
+ await context.run("step-1", () => {
54
+ // ...
55
+ })
56
+ } else {
57
+ await context.run("step-2", () => {
58
+ // ...
59
+ })
60
+ }
61
+ })
62
+ ```
63
+
64
+ ```python ❌ Non-idempotent functions - Python
65
+ @serve.post("/api/example")
66
+ async def example(context: AsyncWorkflowContext[str]) -> None:
67
+ entry_id = context.request_payload["entry_id"]
68
+
69
+ # 👇 Problem: Non-idempotent function outside context.run:
70
+ result = await get_result_from_db(entry_id)
71
+ if result.should_return:
72
+ return
73
+
74
+ # ...
75
+
76
+ ```
77
+
78
+ ```python ❌ Time-dependent code - Python
79
+ @serve.post("/api/example")
80
+ async def example(context: AsyncWorkflowContext[str]) -> None:
81
+ input = context.request_payload
82
+
83
+ # 👇 Problem: time-dependent code
84
+ if time.time() % 5 == 2:
85
+ await context.run("step-1", lambda: ...)
86
+ else:
87
+ await context.run("step-2", lambda: ...)
88
+
89
+ ```
90
+
91
+ ```python ❌ Random code - Python
92
+ @serve.post("/api/example")
93
+ async def example(context: AsyncWorkflowContext[str]) -> None:
94
+ input = context.request_payload
95
+
96
+ # 👇 Problem: random code
97
+ if random.randint(0, 9) % 5 == 2:
98
+ await context.run("step-1", lambda: ...)
99
+ else:
100
+ await context.run("step-2", lambda: ...)
101
+
102
+ ```
103
+
104
+ </CodeGroup>
105
+
106
+ If you implement a non-idempotent code like the one shown above, you might encounter `Failed to authenticate Workflow request.` errors. This can happen if you `return` based on the result of the non-idempotent code before any workflow step.
107
+
108
+ To prevent this, ensure that the non-idempotent code (such as `getResultFromDb` in the example) runs within `context.run`.
109
+
110
+ <CodeGroup>
111
+
112
+ ```typescript TypeScript
113
+ const result = await context.run("get-result-from-db", async () => {
114
+ return await getResultFromDb(entryId)
115
+ });
116
+ if (result.return) {
117
+ return;
118
+ }
119
+ ```
120
+
121
+ ```python Python
122
+ async def _get_result_from_db():
123
+ return await get_result_from_db(entry_id)
124
+
125
+ result = await context.run("get-result-from-db", _get_result_from_db)
126
+
127
+ if result.should_return:
128
+ return
129
+
130
+ ```
131
+
132
+ </CodeGroup>
@@ -0,0 +1,38 @@
1
+ ---
2
+ title: "Ensure Idempotency in context.run"
3
+ sidebarTitle: "Idempotency"
4
+ ---
5
+
6
+ Business logic should be idempotent due to potential retries in distributed systems. In other words, **when a workflow runs twice with the same input, the end result should be the same as if the workflow only ran once**.
7
+
8
+ In the example below, the `someWork` function must be idempotent:
9
+
10
+ <CodeGroup>
11
+
12
+ ```typescript api/workflow/route.ts
13
+ export const { POST } = serve<string>(async (context) => {
14
+ const input = context.requestPayload
15
+
16
+ await context.run("step-1", async () => {
17
+ return someWork(input)
18
+ })
19
+ })
20
+ ```
21
+
22
+ ```python main.py
23
+ @serve.post("/api/example")
24
+ async def example(context: AsyncWorkflowContext[str]) -> None:
25
+ input = context.request_payload
26
+
27
+ async def _step_1() -> None:
28
+ return await some_work(input)
29
+
30
+ await context.run("step-1", _step_1)
31
+
32
+ ```
33
+
34
+ </CodeGroup>
35
+
36
+ Imagine that `someWork` executes once and makes a change to a database. However, before the database had a chance to respond with the successful change, the connection is lost. Your Workflow cannot know if the database change was successful or not. The caller has no choice but to retry, which will cause `someWork` to run twice.
37
+
38
+ If `someWork` is not idempotent, this could lead to unintended consequences. For example duplicated records or corrupted data. Idempotency is crucial to maintaining the integrity and reliability of your workflow.
@@ -0,0 +1,38 @@
1
+ ---
2
+ title: "Don't Nest Context Methods"
3
+ sidebarTitle: "Nested Context Methods"
4
+ ---
5
+
6
+ Avoid calling `context.call`, `context.sleep`, `context.sleepFor`, or `context.run` within another `context.run`.
7
+
8
+ <CodeGroup>
9
+
10
+ ```typescript api/workflow/route.ts
11
+ import { serve } from "@upstash/workflow/nextjs"
12
+
13
+ export const { POST } = serve<string>(async (context) => {
14
+ const input = context.requestPayload
15
+
16
+ await context.run("step-1", async () => {
17
+ await context.sleep(...) // ❌ INCORRECT
18
+ await context.run(...) // ❌ INCORRECT
19
+ await context.call(...) // ❌ INCORRECT
20
+ })
21
+ })
22
+ ```
23
+
24
+ ```python main.py
25
+ @serve.post("/api/example")
26
+ async def example(context: AsyncWorkflowContext[str]) -> None:
27
+ input = context.request_payload
28
+
29
+ async def _step_1() -> None:
30
+ await context.sleep(...) # ❌ INCORRECT
31
+ await context.run(...) # ❌ INCORRECT
32
+ await context.call(...) # ❌ INCORRECT
33
+
34
+ await context.run("step-1", _step_1)
35
+
36
+ ```
37
+
38
+ </CodeGroup>
@@ -0,0 +1,35 @@
1
+ ---
2
+ title: "Best practices"
3
+ sidebarTitle: "Overview"
4
+ ---
5
+
6
+ Keep the rules below in mind to avoid unexpected behavior and failures.
7
+
8
+ To learn more about how the internal of Upstash Workflow works, see [how Workflow works](/workflow/basics/how).
9
+
10
+ <Columns cols={1}>
11
+ <Card title="Execute business logic in context.run" href="/workflow/basics/best-practices/business-logic-in-steps" arrow>
12
+ Your endpoint runs many times per workflow run. Only code inside a step runs exactly once.
13
+ </Card>
14
+ <Card title="Return results from context.run" href="/workflow/basics/best-practices/return-step-results" arrow>
15
+ Variables assigned inside a step are lost on the next call. Return the value instead.
16
+ </Card>
17
+ <Card title="Avoid non-deterministic code outside context.run" href="/workflow/basics/best-practices/deterministic-code" arrow>
18
+ Database reads, time checks, and randomness must produce the same result on every call.
19
+ </Card>
20
+ <Card title="Ensure idempotency in context.run" href="/workflow/basics/best-practices/idempotency" arrow>
21
+ Steps can be retried. Running one twice must have the same effect as running it once.
22
+ </Card>
23
+ <Card title="Keep workflows within hard limits" href="/workflow/basics/best-practices/workflow-limits" arrow>
24
+ A workflow run can have at most 1,000 steps and a 100 MB context.
25
+ </Card>
26
+ <Card title="Don't nest context methods" href="/workflow/basics/best-practices/nested-context-methods" arrow>
27
+ Never call `context.run`, `context.sleep`, or `context.call` inside another `context.run`.
28
+ </Card>
29
+ <Card title="Include at least one step" href="/workflow/basics/best-practices/at-least-one-step" arrow>
30
+ A workflow without any `context.run` fails with `Failed to authenticate Workflow request.`
31
+ </Card>
32
+ <Card title="Avoid Promise.any" href="/workflow/basics/best-practices/promise-any" arrow>
33
+ `Promise.all` works for parallel steps, but `Promise.any` isn't supported.
34
+ </Card>
35
+ </Columns>
@@ -0,0 +1,9 @@
1
+ ---
2
+ title: "Avoid Promise.any"
3
+ ---
4
+
5
+ In workflow-js, you can use [`Promise.all` to run steps in parallel](/workflow/howto/parallel-runs). However, a similar method, [`Promise.any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/any), is not supported for workflow steps.
6
+
7
+ While `Promise.all` works seamlessly, `Promise.any` does not currently function with workflow steps. We are exploring the possibility of adding support for `Promise.any` in the future.
8
+
9
+ If you have a specific use case that requires `Promise.any`, don't hesitate to reach out to Upstash support.