Lesson 36 of 39 · Production
Hosting: A2A, AG-UI, ChatKit and Azure Functions
Expose Agent Framework agents to other agents and apps: A2A, AG-UI and ChatKit front ends, Azure Functions with durable agents, and Foundry hosting.
- 11 min read
- Intermediate
- Reviewed
- Choose a hosting option for an agent: A2A, AG-UI, ChatKit, Azure Functions or Foundry
- Serve an agent over A2A with A2AExecutor and call any A2A agent with A2AAgent
- Connect a web front end with AG-UI and ChatKit
- Host agents on Azure Functions with AgentFunctionApp and DurableAIAgent
- Run an agent as a Responses API server with ResponsesHostServer
Where your agent lives
Until now, your agents ran inside your own Python script. Real products need other programs to reach them: another team's agent, a web page, a mobile app, a scheduled job. Each of those talks through a protocol, and Agent Framework has a ready-made host for the common ones.
| Option | Who calls the agent | Use it when |
|---|---|---|
| A2A | other agents, in any language or framework | agents from different teams or vendors must work together |
| AG-UI | web front ends (for example CopilotKit) | you build your own chat UI with streaming, tools and state |
| ChatKit | OpenAI's ChatKit UI components | you use ChatKit for the chat window |
| Azure Functions | HTTP clients and durable orchestrations | you want serverless hosting with saved conversations |
| Foundry hosting | any OpenAI Responses API client | you deploy the agent as a container to Microsoft Foundry |
Each protocol wraps the same answer differently. In plain Python, with simplified shapes:
# One agent, three protocols: the same answer wrapped for different callers (simplified shapes).
def agent(question):
return "A City E costs 35 EUR a day."
answer = agent("How much does a City E cost?")
a2a = {"jsonrpc": "2.0", "result": {"role": "agent", "parts": [{"text": answer}]}}
ag_ui = ([{"type": "RUN_STARTED"}, {"type": "TEXT_MESSAGE_START"}]
+ [{"type": "TEXT_MESSAGE_CONTENT", "delta": word + " "} for word in answer.split()]
+ [{"type": "TEXT_MESSAGE_END"}, {"type": "RUN_FINISHED"}])
responses = {"object": "response", "output_text": answer}
print("A2A:", a2a["result"]["parts"][0]["text"])
print("AG-UI:", len(ag_ui), "events, starting with", [event["type"] for event in ag_ui[:3]])
print("Responses API:", responses["output_text"])A2A: agents talking to agents
A2A (Agent2Agent) is an open protocol for agents to call each other over HTTP, whatever framework they were built with. A server publishes an agent card, a description of what it can do, at /.well-known/agent-card.json, and answers JSON-RPC requests.
To serve your agent, wrap it in an A2AExecutor and plug that into the a2a-sdk server pieces:
import uvicorn
from a2a.server.request_handlers import DefaultRequestHandler
from a2a.server.routes import create_agent_card_routes, create_jsonrpc_routes
from a2a.server.tasks import InMemoryTaskStore
from a2a.types import AgentCapabilities, AgentCard, AgentInterface, AgentSkill
from starlette.applications import Starlette
from agent_framework import Agent
from agent_framework.a2a import A2AExecutor
from agent_framework.openai import OpenAIChatClient
agent = Agent(
client=OpenAIChatClient(model="MODEL_NAME"),
name="velo_desk",
instructions="You are Velo's rental desk in Porto. A City E costs 35 EUR a day.",
)
card = AgentCard( # the public description other agents read
name="Velo rental desk",
description="Answers questions about renting bikes from Velo in Porto.",
version="1.0.0",
default_input_modes=["text"],
default_output_modes=["text"],
capabilities=AgentCapabilities(streaming=True),
supported_interfaces=[AgentInterface(url="http://127.0.0.1:9999/", protocol_binding="JSONRPC")],
skills=[AgentSkill(id="rentals", name="Bike rentals", description="Prices and rules for renting bikes",
tags=["bikes", "rental"])],
)
handler = DefaultRequestHandler(agent_executor=A2AExecutor(agent), task_store=InMemoryTaskStore(), agent_card=card)
app = Starlette(routes=[*create_agent_card_routes(card), *create_jsonrpc_routes(handler, "/")])
if __name__ == "__main__":
uvicorn.run(app, host="127.0.0.1", port=9999)To call any A2A agent, yours or someone else's, use A2AAgent:
import asyncio
from agent_framework.a2a import A2AAgent
async def main():
velo = A2AAgent(name="velo_desk", url="http://127.0.0.1:9999/") # any A2A agent, in any language
response = await velo.run("How much does a City E cost?")
print(response.text)
asyncio.run(main())A City E costs 35 EUR a day.
A2AAgent is a normal agent: it works with sessions, in workflows, as a tool with as_tool() and in orchestrations, so a remote agent can join your team as easily as a local one.
AG-UI: agents in your web app
AG-UI is an open protocol for streaming an agent run to a front end as events: text as it is written, tool calls, state updates. add_agent_framework_fastapi_endpoint() adds an AG-UI endpoint to a FastAPI app:
import uvicorn
from fastapi import FastAPI
from agent_framework import Agent
from agent_framework.ag_ui import add_agent_framework_fastapi_endpoint
from agent_framework.openai import OpenAIChatClient
agent = Agent(
client=OpenAIChatClient(model="MODEL_NAME"),
name="velo_desk",
instructions="You are Velo's rental desk in Porto. A City E costs 35 EUR a day.",
)
app = FastAPI(title="Velo desk")
add_agent_framework_fastapi_endpoint(app, agent, "/agent", single_user=True) # one user: a local demo
if __name__ == "__main__":
uvicorn.run(app, host="127.0.0.1", port=8888)single_user=True says that one person uses this endpoint, which is right for a local demo. For a real app, pass authorization_scope_resolver=: a function that returns the signed-in user's id for each request, so users never see each other's conversations. A front end such as CopilotKit can now talk to /agent. From Python, use AGUIChatClient:
import asyncio
from agent_framework import Agent
from agent_framework.ag_ui import AGUIChatClient
async def main():
remote = Agent(name="velo_web", client=AGUIChatClient(endpoint="http://127.0.0.1:8888/agent"))
async for update in remote.run("How much does a City E cost?", stream=True):
print(update.text, end="", flush=True)
print()
asyncio.run(main())A City E costs 35 EUR a day.
ChatKit: OpenAI's chat components
ChatKit is OpenAI's set of chat UI components with its own server protocol (the openai-chatkit package). Inside your ChatKit server's respond() method, stream_agent_response() turns an agent's stream into ChatKit events:
import asyncio
from agent_framework import Agent
from agent_framework.chatkit import stream_agent_response
from agent_framework.openai import OpenAIChatClient
async def main():
agent = Agent(
client=OpenAIChatClient(model="MODEL_NAME"),
instructions="You are Velo's rental desk in Porto. A City E costs 35 EUR a day.",
)
updates = agent.run("How much does a City E cost?", stream=True)
events = [event async for event in stream_agent_response(updates, thread_id="thread_asha")]
print(list(dict.fromkeys(event.type for event in events))) # the kinds of ChatKit events, in order
asyncio.run(main())['thread.item.added', 'thread.item.updated', 'thread.item.done']
The UI shows the message when it's added, updates it as text arrives, and marks it done. In a real server you yield these events from respond() instead of collecting them.
Azure Functions and durable agents
AgentFunctionApp turns agents into an Azure Functions app. Each agent gets an HTTP endpoint and a durable entity that keeps its conversations, so they survive restarts and scale out:
from agent_framework import Agent
from agent_framework.azure import AgentFunctionApp
from agent_framework.openai import OpenAIChatClient
velo_desk = Agent(
client=OpenAIChatClient(model="MODEL_NAME"),
name="velo_desk",
instructions="You are Velo's rental desk in Porto. A City E costs 35 EUR a day.",
)
# Creates POST /api/agents/velo_desk/run, a durable entity that keeps each conversation, and GET /api/health.
app = AgentFunctionApp(agents=[velo_desk], deployment_mode="isolated_v2")
@app.orchestration_trigger(context_name="context")
def weekly_newsletter(context):
desk = app.get_agent(context, "velo_desk") # a DurableAIAgent: each run is a durable step
session = desk.create_session()
prices = yield desk.run("List this week's bike prices.", session=session)
note = yield desk.run("Turn that into one sentence for our newsletter.", session=session)
return {"prices": prices.text, "note": note.text}This app has a POST /api/agents/velo_desk/run endpoint for chatting with the agent, GET /api/health, and a durable orchestration. Inside an orchestration, app.get_agent() returns a DurableAIAgent: each run() is a durable step that you yield, so a long process continues where it stopped after a crash or restart. Run it locally with Azure Functions Core Tools (func start) and a storage emulator, then deploy it to Azure.
Foundry hosting: a Responses API server
ResponsesHostServer serves an agent over the OpenAI Responses API, the format Microsoft Foundry uses for hosted agents. You can run it on your computer, in any container, or deploy it to Foundry:
from agent_framework import Agent
from agent_framework.foundry import ResponsesHostServer
from agent_framework.openai import OpenAIChatClient
agent = Agent(
client=OpenAIChatClient(model="MODEL_NAME"),
name="velo_desk",
instructions="You are Velo's rental desk in Porto. A City E costs 35 EUR a day.",
)
server = ResponsesHostServer(agent) # speaks the OpenAI Responses API
if __name__ == "__main__":
server.run() # port 8088, or the PORT environment variableAny OpenAI client can then call it:
from openai import OpenAI
client = OpenAI(base_url="http://127.0.0.1:8088", api_key="not-used-locally")
response = client.responses.create(model="velo_desk", input="How much does a City E cost?")
print(response.output_text)A City E costs 35 EUR a day.
For requests that don't fit a chat, such as "process this order" with your own JSON, use InvocationsHostServer instead: it accepts your own payload at POST /invocations and can describe it with an OpenAPI spec.
Common mistakes
Write the adapter an AG-UI endpoint needs: turn the text chunks of a streamed answer into AG-UI events, skipping empty chunks.
def to_agui_events(chunks):
# Start with RUN_STARTED and TEXT_MESSAGE_START.
# Add one TEXT_MESSAGE_CONTENT event with a delta for each chunk that isn't empty.
# Finish with TEXT_MESSAGE_END and RUN_FINISHED.
return []
for event in to_agui_events(["A City E ", "", "costs 35 EUR", " a day."]):
print(event["type"], repr(event.get("delta", "")))
Which host do you use so that another team's agent, written with a different framework, can call yours?
Summary
- A2A connects agents across frameworks: serve with
A2AExecutor, call withA2AAgent. - AG-UI streams runs to web front ends:
add_agent_framework_fastapi_endpoint()on the server,AGUIChatClientin Python, with an explicit authorization mode. - ChatKit apps use
stream_agent_response()to turn agent streams into ChatKit events. AgentFunctionApphosts agents on Azure Functions, andDurableAIAgentmakes each run a durable step in orchestrations.ResponsesHostServerandInvocationsHostServerserve agents for Microsoft Foundry or any container.
Next: Migrating From AutoGen and Semantic Kernel.
Finished reading? Tick it off to track your progress.