Lesson 30 of 39 · Workflows
Agents in Workflows and Workflows as Agents
Put agents into Agent Framework workflows with AgentExecutor, control what each one sees, stream replies, run a workflow as an agent and nest workflows.
- 19 min read
- Intermediate
- Reviewed
- Add agents to a workflow and explain what AgentExecutor does for them
- Send AgentExecutorRequest messages and read AgentExecutorResponse results
- Choose what each agent sees with context_mode, and keep the conversation when you change a reply
- Stream agents' replies from a running workflow
- Run a whole workflow as an agent with as_agent() and answer its questions
- Put one workflow inside another with WorkflowExecutor
Agents and workflows, together
So far, your workflows were made of executors you wrote yourself: plain Python that does exactly what the code says. Agents are different: they read a conversation and decide what to say or which tool to call. Real systems mix the two. The workflow fixes the order of the work, and agents do the steps that need language skills, such as writing, reviewing, translating or classifying.
Agent Framework connects agents and workflows in three ways:
| You want to... | Use |
|---|---|
| Use an agent as one step of a workflow | AgentExecutor (usually created for you) |
| Let people and programs call a whole workflow as if it were one agent | workflow.as_agent(), which returns a WorkflowAgent |
| Reuse a complete workflow as one step of a bigger workflow | WorkflowExecutor |
Agents as steps
This lesson builds a tiny marketing desk for Velo, the bike shop in Porto: one agent writes a slogan and another reviews it.
import asyncio
from agent_framework import Agent, WorkflowBuilder
from agent_framework.openai import OpenAIChatClient
async def main():
client = OpenAIChatClient(model="MODEL_NAME") # reads OPENAI_API_KEY
writer = Agent(
client=client, name="writer",
instructions="Write one short slogan for the product. Reply with the slogan only.",
)
reviewer = Agent(
client=client, name="reviewer",
instructions="Review the slogan in one sentence: is it clear, honest and short?",
)
workflow = (
WorkflowBuilder(start_executor=writer, output_from=[reviewer]) # pass agents like executors
.add_edge(writer, reviewer)
.build()
)
print([(e.id, type(e).__name__) for e in workflow.get_executors_list()])
result = await workflow.run("An e-bike with a 120 km battery")
review = result.get_outputs()[0] # an AgentResponse
print(type(review).__name__, "->", review.text)
asyncio.run(main())[('writer', 'AgentExecutor'), ('reviewer', 'AgentExecutor')]
AgentResponse -> Clear and honest: it names the real benefit without exaggerating.What happened:
WorkflowBuilderaccepts agents anywhere it accepts executors. It wraps eachAgentin anAgentExecutorand uses the agent'snameas the executor ID. Passing the same agent object again gives the same executor.- The writer gets the input string, runs, and sends an
AgentExecutorResponsealong the edge. The reviewer receives it and runs with the whole conversation so far: the user's request and the writer's slogan. - Every agent executor also yields its reply as a workflow output: an
AgentResponse, the same objectagent.run()returns. Withoutoutput_from=[reviewer],get_outputs()would hold two responses, the writer's first.
What an AgentExecutor receives and sends
An AgentExecutor keeps a cache: the messages waiting for the agent's next run. What it does depends on the type of message it receives:
| It receives | What happens |
|---|---|
A str, a Message or a list of them | Added to the cache as user input, then the agent runs |
An AgentExecutorResponse from an earlier agent | The earlier conversation is added (see context_mode below), then the agent runs |
An AgentExecutorRequest(messages, should_respond=True) | The messages are added. The agent runs only if should_respond is True |
should_respond=False adds background, such as "Our shop is in Porto", without spending a model call: the agent reads it the next time it runs.
After each run, the executor sends one AgentExecutorResponse to the next executors:
| Field | What it holds |
|---|---|
executor_id | Which executor answered, for example "writer" |
agent_response | The agent's AgentResponse, with .text, .messages and token usage |
full_conversation | Everything the agent read, plus its reply, ready for the next agent |
Create an AgentExecutor yourself when you need one of its options:
| Option | What it's for |
|---|---|
id | Your own executor ID. Needed to use one agent at two places in a workflow: wrap it twice with different IDs |
session | An AgentSession to use. Without one, the executor creates its own and keeps it between runs, so the agent remembers its earlier turns |
context_mode, context_filter | What the agent sees from earlier agents (next section) |
ensure_trailing_user_turn | When True, adds a short "please continue." user message if the conversation ends with an assistant message. Some providers return an empty reply otherwise |
Choosing what the next agent sees
Here a translator sits between the writer and the reviewer, and the reviewer is created with each of the three modes:
import asyncio
from typing import Never
from agent_framework import Agent, AgentExecutor, AgentExecutorResponse, WorkflowBuilder, WorkflowContext, executor
from agent_framework.openai import OpenAIChatClient
@executor(id="show_context")
async def show_context(response: AgentExecutorResponse, ctx: WorkflowContext[Never, str]) -> None:
seen = [m.author_name or m.role for m in response.full_conversation[:-1]] # what the reviewer read
await ctx.yield_output(f"{response.executor_id} read: {seen}")
def build(mode: str):
client = OpenAIChatClient(model="MODEL_NAME")
writer = Agent(client=client, name="writer",
instructions="Write one short slogan for the product. Reply with the slogan only.")
translator = Agent(client=client, name="translator",
instructions="Translate the slogan into Spanish. Reply with the translation only.")
reviewer = AgentExecutor(
Agent(client=client, name="reviewer",
instructions="Review the slogan in one sentence: is it clear, honest and short?"),
context_mode=mode, # what this agent gets to see
context_filter=(lambda conversation: [conversation[0], conversation[-1]]) if mode == "custom" else None,
)
return (WorkflowBuilder(start_executor=writer, output_from=[show_context])
.add_chain([writer, translator, reviewer, show_context]).build())
async def main():
for mode in ["full", "last_agent", "custom"]:
result = await build(mode).run("An e-bike with a 120 km battery")
print(f"{mode:<10}", result.get_outputs()[0])
asyncio.run(main())full reviewer read: ['user', 'writer', 'translator'] last_agent reviewer read: ['translator'] custom reviewer read: ['user', 'translator']
"full": the whole conversation, so the reviewer knows the original request. This is the default."last_agent": only the previous agent's reply. It uses fewer tokens and keeps the agent focused, but the agent no longer knows what the user asked for."custom": yourcontext_filterfunction receives the full conversation as a list ofMessageobjects and returns the ones to keep. This one keeps the request and the latest reply. Using"custom"without a filter raisesValueError: context_filter must be provided when context_mode is set to 'custom'.
show_context is a normal executor that receives the reviewer's AgentExecutorResponse and lists who wrote each message the reviewer read (full_conversation without the reviewer's own reply at the end).
The same three choices in plain Python. Change the filter and run it again:
# What each context_mode passes to the next agent, in plain Python.
conversation = [
("user", "An e-bike with a 120 km battery"),
("writer", "Ride further, pay less."),
("translator", "Ve más lejos, paga menos."),
]
def keep_brief_and_last(messages): # a custom filter: the task plus the latest reply
return [messages[0], messages[-1]]
modes = {
"full": conversation, # everything so far (the default)
"last_agent": conversation[-1:], # only the previous agent's reply
"custom": keep_brief_and_last(conversation),
}
for mode, seen in modes.items():
print(f"{mode:<10}", [speaker for speaker, text in seen])Changing a reply between two agents
Sometimes a normal executor sits between two agents, for example to add the shop's name to every slogan. Pass the result on with with_text:
@executor(id="add_brand")
async def add_brand(response: AgentExecutorResponse, ctx: WorkflowContext[AgentExecutorResponse]) -> None:
slogan = response.agent_response.text.strip()
await ctx.send_message(response.with_text(f"{slogan} Velo, Porto.")) # keeps the conversationresponse.with_text(new_text) returns a new AgentExecutorResponse. The agent's reply is replaced by your text, and everything before it in full_conversation stays. In the chain writer → add_brand → reviewer, the reviewer reads the request and the branded slogan:
['An e-bike with a 120 km battery', 'Ride further every day and pay much less for it. Velo, Porto.']
If add_brand sent a plain str instead, the reviewer would start a new conversation containing only that string, and the user's request would be lost (see Common mistakes).
A review loop with AgentExecutorRequest
Your own executors talk to an agent by sending an AgentExecutorRequest: you decide exactly which messages it gets. That makes review loops easy to build:
import asyncio
from agent_framework import (Agent, AgentExecutor, AgentExecutorRequest, AgentExecutorResponse, Message,
WorkflowBuilder, WorkflowContext, executor)
from agent_framework.openai import OpenAIChatClient
MAX_WORDS = 6
@executor(id="brief")
async def brief(product: str, ctx: WorkflowContext[AgentExecutorRequest]) -> None:
prompt = f"Product: {product}. At most {MAX_WORDS} words."
await ctx.send_message(AgentExecutorRequest(messages=[Message("user", [prompt])], should_respond=True))
@executor(id="check_length")
async def check_length(response: AgentExecutorResponse, ctx: WorkflowContext[AgentExecutorRequest, str]) -> None:
slogan = response.agent_response.text.strip()
words = len(slogan.split())
print(f" {response.executor_id} wrote {words} words: {slogan}")
if words <= MAX_WORDS:
await ctx.yield_output(slogan) # done: leave the loop
else: # loop back with feedback
feedback = f"That has {words} words. Shorten it to {MAX_WORDS} or fewer."
await ctx.send_message(AgentExecutorRequest(messages=[Message("user", [feedback])], should_respond=True))
async def main():
writer = AgentExecutor(
Agent(client=OpenAIChatClient(model="MODEL_NAME"), name="writer",
instructions="Write one short slogan for the product. Reply with the slogan only."),
id="writer",
)
workflow = (
WorkflowBuilder(start_executor=brief, output_from=[check_length])
.add_edge(brief, writer)
.add_edge(writer, check_length)
.add_edge(check_length, writer) # the feedback loop
.build()
)
result = await workflow.run("An e-bike with a 120 km battery")
print("Final:", result.get_outputs()[0])
asyncio.run(main())writer wrote 10 words: Ride further every day and pay much less for it. writer wrote 4 words: Ride further, pay less. Final: Ride further, pay less.
briefturns the product into a prompt and sends it to the writer in anAgentExecutorRequest.check_lengthreads the writer'sAgentExecutorResponse. If the slogan is too long, it sends feedback back to the writer in a new request. If it's short enough, it yields the output, and no more messages means the run ends.- The writer remembers its first draft, because its
AgentExecutorkeeps oneAgentSessionbetween runs. That's why "Shorten it" makes sense to the model.
Every loop needs an exit. WorkflowBuilder(max_iterations=...) (100 supersteps by default) is the safety net, as in the Branching, Fan-Out, Fan-In and Loops lesson.
Streaming agent replies
Long replies feel faster when people watch them appear. Run the workflow with stream=True:
import asyncio
from agent_framework import Agent, AgentResponseUpdate, WorkflowBuilder
from agent_framework.openai import OpenAIChatClient
async def main():
client = OpenAIChatClient(model="MODEL_NAME")
writer = Agent(client=client, name="writer",
instructions="Write one short slogan for the product. Reply with the slogan only.")
reviewer = Agent(client=client, name="reviewer",
instructions="Review the slogan in one sentence: is it clear, honest and short?")
workflow = WorkflowBuilder(start_executor=writer).add_edge(writer, reviewer).build()
current = None
async for event in workflow.run("An e-bike with a 120 km battery", stream=True):
if event.type == "output" and isinstance(event.data, AgentResponseUpdate):
if event.executor_id != current: # a new agent started talking
if current is not None:
print()
current = event.executor_id
print(f"[{current}] ", end="")
print(event.data.text, end="", flush=True) # a few characters at a time
print()
asyncio.run(main())[writer] Ride further every day and pay much less for it. [reviewer] Clear and honest: it names the real benefit without exaggerating.
- With
stream=True, each agent executor yieldsAgentResponseUpdatechunks asoutputevents while the model writes, a few words at a time. Without streaming, it yields oneAgentResponsewhen the agent finishes. event.executor_idsays which agent is talking, so a chat screen can label each agent's text.- The next agent still receives the complete reply: the chunks are joined into one
AgentResponsebefore theAgentExecutorResponseis sent. output_fromandintermediate_output_fromchoose whose chunks you see, exactly as for other executors.
A workflow as an agent
workflow.as_agent(name=..., description=...) returns a WorkflowAgent. It has the same run() as every other agent, so chat apps, DevUI, hosting adapters and orchestrations can use your workflow without knowing it's a workflow.
In this example a person must approve each slogan before it's published. ctx.request_info(...) pauses the workflow to ask a question, and the method marked @response_handler receives the answer. The next lesson covers both in depth.
import asyncio
from typing import Never
from agent_framework import (Agent, AgentExecutorResponse, Content, Executor, Message, WorkflowBuilder,
WorkflowContext, handler, response_handler)
from agent_framework.openai import OpenAIChatClient
class Publish(Executor):
@handler
async def ask(self, response: AgentExecutorResponse, ctx: WorkflowContext[Never, str]) -> None:
await ctx.request_info({"slogan": response.agent_response.text}, response_type=str)
@response_handler
async def decided(self, original: dict, answer: str, ctx: WorkflowContext[Never, str]) -> None:
verdict = "Published" if answer.lower().startswith("yes") else "Rejected"
await ctx.yield_output(f"{verdict}: {original['slogan']}")
def build_slogan_desk():
writer = Agent(client=OpenAIChatClient(model="MODEL_NAME"), name="writer",
instructions="Write one short slogan for the product. Reply with the slogan only.")
publish = Publish(id="publish")
workflow = WorkflowBuilder(start_executor=writer, output_from=[publish]).add_edge(writer, publish).build()
return workflow.as_agent(name="slogan_desk", description="Writes slogans and publishes approved ones")
async def main():
agent = build_slogan_desk() # a WorkflowAgent
response = await agent.run("An e-bike with a 120 km battery")
question = next(c for m in response.messages for c in m.contents if c.type == "function_call")
print(type(agent).__name__, "asks:", question.name, question.parse_arguments()["request_event"]["data"])
answer = Content.from_function_result(call_id=question.call_id, result="yes, ship it")
response = await agent.run(Message("user", [answer])) # the answer goes back in a message
print(response.text)
asyncio.run(main())WorkflowAgent asks: request_info {'slogan': 'Ride further every day and pay much less for it.'}
Published: Ride further every day and pay much less for it.How a conversation with a workflow agent works:
agent.run(text)turns the text into alist[Message]and starts the workflow with it. The start executor must acceptlist[Message]. Agents do; a custom start executor needs a handler for it, oras_agent()raisesValueError: Workflow's start executor cannot handle list[Message].- Outputs of the executors in
output_frombecome the reply's messages. The writer isn't listed, so the caller never sees the unapproved draft. - A waiting
request_infoappears in the reply as afunction_callnamedrequest_info. Itscall_idis the request ID, and its arguments hold the original event, with your question under"data". - To answer, send a message containing
Content.from_function_result(call_id=..., result=...)with the same call ID. The workflow continues, andresponse.textis its final output.
Workflows inside workflows
Here a refund check is its own small workflow: it approves small refunds and asks a person about big ones. The parent workflow parses the customer's text, runs the check, and emails the result:
import asyncio
from typing import Never
from agent_framework import (Executor, WorkflowBuilder, WorkflowContext, WorkflowExecutor, executor,
handler, response_handler)
class RefundCheck(Executor): # lives in the inner workflow
@handler
async def check(self, amount: float, ctx: WorkflowContext[Never, str]) -> None:
if amount > 100:
question = {"question": f"Approve a refund of {amount:.2f} EUR?", "amount": amount}
await ctx.request_info(question, response_type=str) # pause and ask outside
else:
await ctx.yield_output(f"refund of {amount:.2f} EUR approved automatically")
@response_handler
async def answered(self, original: dict, answer: str, ctx: WorkflowContext[Never, str]) -> None:
await ctx.yield_output(f"refund {answer}")
def build_refund_check(): # a complete, reusable workflow
return WorkflowBuilder(start_executor=RefundCheck(id="check")).build()
@executor(id="parse")
async def parse(text: str, ctx: WorkflowContext[float]) -> None:
await ctx.send_message(float(text.split()[-1]))
@executor(id="notify")
async def notify(result: str, ctx: WorkflowContext[Never, str]) -> None:
await ctx.yield_output(f"Email to customer: {result}")
async def main():
refunds = WorkflowExecutor(build_refund_check(), id="refunds", propagate_request=True)
workflow = WorkflowBuilder(start_executor=parse).add_edge(parse, refunds).add_edge(refunds, notify).build()
print((await workflow.run("refund 40")).get_outputs())
result = await workflow.run("refund 250")
request = result.get_request_info_events()[0] # bubbled up from inside
print(request.source_executor_id, "asks:", request.data["question"])
result = await workflow.run(responses={request.request_id: "approved by Mia"})
print(result.get_outputs())
asyncio.run(main())['Email to customer: refund of 40.00 EUR approved automatically'] refunds asks: Approve a refund of 250.00 EUR? ['Email to customer: refund approved by Mia']
WorkflowExecutor(workflow, id=...)accepts whatever the inner workflow's start executor accepts, here afloat.- The inner workflow runs until it finishes or waits for an answer. Its outputs are sent as messages to the next executors in the parent (here
notify). Withallow_direct_output=Truethey become outputs of the parent workflow instead. - With
propagate_request=True, a question from inside goes up to whoever runs the parent:get_request_info_events()lists it withsource_executor_id"refunds", andrun(responses=...)answers it. - The parent saves the sub-workflow's state in its own checkpoints, so don't give the inner workflow a checkpoint storage of its own.
- Each
WorkflowExecutorneeds its own workflow instance, so build the inner workflow in a function, likebuild_refund_check().
Answering a sub-workflow's question in the parent
With propagate_request=False (the default), the question doesn't leave the parent workflow. It travels along the parent's edges as a SubWorkflowRequestMessage, so an executor in the parent can answer it. Here a store policy decides instead of a person:
class StorePolicy(Executor): # lives in the PARENT workflow
@handler
async def decide(self, request: SubWorkflowRequestMessage,
ctx: WorkflowContext[SubWorkflowResponseMessage]) -> None:
amount = request.source_event.data["amount"] # the inner request's data
answer = "approved by store policy" if amount <= 300 else "refused: over 300 EUR"
await ctx.send_message(request.create_response(answer), target_id=request.executor_id)
def build_with_policy():
refunds = WorkflowExecutor(build_refund_check(), id="refunds") # propagate_request is False
policy = StorePolicy(id="policy")
return (
WorkflowBuilder(start_executor=parse)
.add_edge(parse, refunds)
.add_edge(refunds, notify) # outputs (str) go to notify
.add_edge(refunds, policy) # requests go to the policy
.add_edge(policy, refunds) # answers go back down
.build()
)Running "refund 250" and "refund 900" through build_with_policy():
['Email to customer: refund approved by store policy'] ['Email to customer: refund refused: over 300 EUR']
request.source_eventis the innerrequest_infoevent, and its.datais the question dictionary.request.create_response(answer)checks the answer against the type the inner executor asked for (strhere) and wraps it in aSubWorkflowResponseMessage.target_id=request.executor_idsends it straight back to the rightWorkflowExecutor, which resumes the inner workflow.- When the policy can't decide, it can still ask a person with
ctx.request_info(...).
Common mistakes
Write the feedback loop from the check_length executor in plain Python: keep asking the writer for a new draft until the slogan has at most four words.
drafts = iter([
"Ride further every day and pay much less for it.",
"Ride further and pay a lot less.",
"Ride further, pay less.",
])
def writer(feedback):
# Stands in for the writer agent: every call returns its next draft.
return next(drafts)
MAX_WORDS = 4
# 1. Get the first draft with writer(None).
# 2. While the draft has more than MAX_WORDS words:
# print "<n> words: <draft>", then call writer() again with a feedback string.
# 3. Print "Final: <draft>".
A normal executor between two agents rewrites the first agent's reply. What should it send so the second agent still sees the user's original request?
Summary
WorkflowBuilderwraps each agent in anAgentExecutor(ID = the agent's name). Create one yourself to set theid,session,context_modeorcontext_filter.- An agent executor accepts strings, messages, an
AgentExecutorRequestor an earlierAgentExecutorResponse, and sends anAgentExecutorResponsewithexecutor_id,agent_responseandfull_conversation. Usewith_textto change a reply without losing the conversation. context_modedecides what an agent sees: everything, only the last agent's reply, or your own filter. Withstream=True, agents yieldAgentResponseUpdatechunks as they write.as_agent()returns aWorkflowAgent. Questions from the workflow arrive asrequest_infofunction calls and are answered with function results. Build one per conversation.WorkflowExecutornests a workflow. Its questions go up to the caller (propagate_request=True) or reach a parent executor as aSubWorkflowRequestMessage.
Next: Human-in-the-Loop and Checkpoints.
Finished reading? Tick it off to track your progress.