Agent Workflows
Purpose and Scope
Agent workflows are repeatable structures for turning model calls, tools, and intermediate results into reliable systems. The workflow documentation frames these patterns as a way to add structure around the agent building blocks introduced earlier in the agents section. Instead of treating every agent as an unconstrained loop, this page helps you choose between explicit sequencing, branching, concurrency, review loops, and coordination patterns. That choice matters because each pattern changes the amount of control you retain, the number of model calls you make, and the debugging surface you own. Sources: content/docs/03-agents/03-workflows.mdx
The repository documentation names five core patterns: sequential processing, parallel processing, evaluation and feedback loops, orchestration, and routing. These are not separate products or packages; they are design patterns that use the same AI SDK primitives, especially model calls such as generateText and typed output generation with Output.object. The page explicitly recommends starting with the simplest approach that meets the requirement, then adding complexity when a task needs clearer steps, specialized tools, quality-control loops, or multiple collaborating agents. Sources: content/docs/03-agents/03-workflows.mdx
Relevant Source Files
content/docs/03-agents/03-workflows.mdx- The first-party documentation page for workflow patterns. It defines the pattern list, the decision factors for choosing an approach, and the sequential-processing example that combines text generation with structured evaluation.
Choosing a Workflow Pattern
The most important decision is how much freedom the model should have. A free-form agent loop can adapt to ambiguous requests, but it is harder to constrain, audit, and test. A structured workflow narrows the path through the system so that the model only makes decisions at specific points. The documentation highlights this as a flexibility-versus-control tradeoff and pairs it with error tolerance, cost, and maintenance concerns. In practice, high-risk workflows usually deserve more explicit structure, while exploratory tasks can allow more model autonomy. Sources: content/docs/03-agents/03-workflows.mdx
Cost and maintenance should be treated as first-order design constraints, not afterthoughts. Every additional branch, evaluator, or worker can introduce another model call, another schema, and another failure mode. The docs therefore advise increasing complexity only when required by the problem: break work into steps, add tools for specific capabilities, add feedback loops for quality control, and introduce multiple agents only when the workflow has enough complexity to justify coordination overhead. This gives teams a progressive path from simple calls to durable agent systems. Sources: content/docs/03-agents/03-workflows.mdx
| Pattern | Best fit | Main tradeoff |
|---|---|---|
| Sequential processing | A known set of steps where each output feeds the next step | Easy to reason about, but less flexible |
| Parallel processing | Independent subtasks that can run at the same time | Faster throughput, but requires result merging |
| Evaluation and feedback loops | Outputs that need scoring, validation, or improvement | Better quality, but more calls and latency |
| Orchestration | Systems with multiple components or workers | Strong coordination, but more architecture |
| Routing | Varied inputs that need different branches | Adaptive handling, but routing quality matters |
Sequential Processing and Chains
Sequential processing is the simplest pattern because execution order is known before the request starts. The docs describe it as a chain where each step output becomes the next step input. A common example is a content pipeline: first generate copy, then evaluate it, then rewrite it if the evaluation shows weaknesses. This pattern works well when the business process already has a natural order and when each stage can be tested independently. It is also the easiest pattern to log because every run follows the same broad shape. Sources: content/docs/03-agents/03-workflows.mdx
The documented example uses generateText for the first step and then uses generateText again with Output.object and a Zod schema to produce structured quality metrics. The evaluator asks for booleans and numeric scores such as whether the copy has a call to action, how strong the emotional appeal is, and how clear the writing is. If those metrics do not meet thresholds, the workflow calls the model again with targeted rewrite instructions. The important design detail is that the loop condition is ordinary application logic, not hidden inside the model. Sources: content/docs/03-agents/03-workflows.mdx
import { generateText, Output } from 'ai';
import { z } from 'zod';
async function generateMarketingCopy(model: any, input: string) {
const { text: copy } = await generateText({
model,
prompt: `Write persuasive marketing copy for: ${input}.`,
});
const { output: qualityMetrics } = await generateText({
model,
output: Output.object({
schema: z.object({
hasCallToAction: z.boolean(),
emotionalAppeal: z.number().min(1).max(10),
clarity: z.number().min(1).max(10),
}),
}),
prompt: `Evaluate this copy: ${copy}`,
});
if (!qualityMetrics.hasCallToAction || qualityMetrics.clarity < 7) {
return generateText({ model, prompt: `Improve this copy: ${copy}` });
}
return { copy, qualityMetrics };
}Use chains when downstream steps require upstream context, such as extract then summarize, draft then review, or plan then execute. Avoid using a chain when the steps are truly independent; that would serialize work unnecessarily and increase latency. Also avoid burying all decision-making inside a single huge prompt if the task naturally decomposes into typed stages. The sequential pattern is valuable because it lets you inspect the artifact produced at each stage and apply normal TypeScript control flow around the model results.
Routing, Parallelism, and Orchestration
Routing is the pattern for heterogeneous inputs. The documentation describes the model as an intelligent router that chooses which path a workflow should take based on context and intermediate results. This is useful when one endpoint handles many kinds of user requests, such as support triage, document classification, or task delegation. A routing step should produce a small, inspectable decision, ideally constrained to known route names. The rest of the workflow can then call the specialized prompt, tool set, or agent that fits the selected branch. Sources: content/docs/03-agents/03-workflows.mdx
Parallel processing is the natural counterpart to sequential processing. Use it when tasks do not depend on each other, such as generating independent analyses, checking several sources, or asking specialized workers for separate opinions. The key implementation concern is not just starting work concurrently; it is designing the merge step. The system needs a clear rule for combining results, resolving conflicts, and reporting partial failures. Parallel workflows often pair well with a final evaluator or synthesizer because independent model outputs can overlap, disagree, or vary in quality.
Orchestration is broader than routing or parallel execution. It is the coordination layer that decides which components participate, how intermediate state is passed, and when the workflow is complete. In a small app, orchestration may be a single function that calls model APIs and tools. In a larger agent system, it can coordinate multiple specialized agents, workflow steps, or user approval points. The repository docs place orchestration alongside the other patterns to emphasize that coordination is itself a design problem, not merely an implementation detail. Sources: content/docs/03-agents/03-workflows.mdx
Evaluation and Feedback Loops
Evaluation and feedback loops improve reliability by checking model output before accepting it. The sequential marketing-copy example already demonstrates this pattern: generate an artifact, produce typed quality metrics, and conditionally regenerate with specific instructions. A feedback loop can be small, such as one rewrite attempt after a failed score, or more formal, such as an evaluator-optimizer system that iterates until a threshold, step limit, or human review condition is reached. The safest loops have explicit stopping rules so they do not create runaway cost or latency.
Treat evaluator outputs as operational data. If an evaluator returns structured fields, those fields can become logs, user-facing explanations, test assertions, or routing inputs for later steps. This is why schema-backed output matters: it turns a model judgment into data that application code can validate and act on. The same pattern can support moderation, code review, extraction quality checks, answer grading, or content policy review. However, because the evaluator is also model-based, teams should still test it with realistic examples and consider human review where mistakes have high impact.
Implementation Guidance and Next Steps
When implementing these patterns, keep the model decision points narrow and explicit. Use normal application code for deterministic branching, thresholds, retries, and result aggregation. Use model calls where interpretation, generation, classification, or synthesis is required. This separation makes the workflow easier to debug because you can inspect prompts, structured outputs, and branch decisions independently. It also helps you migrate between patterns: a chain can later gain an evaluator, a router can add a parallel branch, and an orchestrator can introduce specialized agents without rewriting the whole system.
A good next step is to prototype the simplest version of the target workflow with one or two model calls and a clear return shape. Add instrumentation around each step before adding more agents or branches, because complex workflows are only useful if you can understand why they behaved the way they did. After that, read the loop-control, tool-calling, and WorkflowAgent pages to decide whether the workflow should remain an ordinary function, become a tool-loop agent, or run as a durable workflow with resumable execution.