feat(runtime): stream chat completion answers when clients ask for stream: true
Nobody has claimed this yet.
Assessment
- Difficulty
- 5/5
- Estimated time
- Over a week
- Newbie friendliness
- 48/100
- Issue type
- Feature
- Clarity
- Clearly specified
- Activity status
- Active
- Domain
- api, backend-api-design, testing
Research direction
Start with runtimes/common/agentkit_serve_common/server.py and conversation.py to trace request handling and the RunRequest callback pattern; then read each runtime's agent_factory.py. Run the shared tests in runtimes/common/agentkit_serve_common/conformance.py and each runtime's tests/test_server.py and parity tests. Done means streaming works across all three runtimes, existing non-streaming behavior is preserved, and the documented tests pass.
Written by the indexing model from the issue text.
Description
Problem
If a client sends "stream": true to POST /v1/chat/completions, AgentKit rejects the request:
HTTP 400
{"error": {"message": "streaming is not supported; this agent serves non-streaming chat completions only", "type": "invalid_request_error", "code": "stream_unsupported"}}
Many chat apps and client libraries stream by default. Open WebUI and LibreChat do, and a lot of OpenAI SDK code uses stream=True. Today those clients can't talk to an AgentKit agent at all. Clients that can turn streaming off show a blank screen until the whole answer is ready, including every tool the agent calls on the way.
What
Support "stream": true on POST /v1/chat/completions in the default openai protocol mode, for all three runtimes: pydantic-ai, Microsoft Agent Framework and LangGraph.
- If
streamisfalseor missing, nothing changes. - If
streamistrue, AgentKit keeps the HTTP response open and sends the answer in small pieces as the model writes it. This is called Server-Sent Events (SSE). Use the same format as the OpenAI API:chat.completion.chunkobjects, ending withdata: [DONE].
Do this in two steps. Each one can be its own PR.
- Basic streaming in the shared server. Accept
stream: true, run the agent as today, and send the whole answer as one piece. No runtime changes. This alone makes streaming clients work. - Real streaming in each runtime. Send text as the model writes it.
Out of scope
- Streaming in the other protocol modes (
foundry,orka,acp,agentsessions) and on/v1/responsesfrom #36. Build the step 2 hook so they can reuse it later. - Sending tool calls to the client. The agent runs its own tools, so the client only gets text.
- Changes to the Agentkitfile or to the
/agent/agent.yamlfile built into the image. The client picks streaming per request, not when the image is built.
Why
- People can use the chat apps and SDK code they already have, with no extra settings or proxy.
- People see the answer begin within about a second instead of waiting for the whole run. That matters most for agents that call several tools.
- Streaming is the first thing most clients expect from an "OpenAI-compatible" server, and that is AgentKit's main API.
How
Where things are
| File | What it does |
|---|---|
runtimes/common/agentkit_serve_common/server.py |
The shared OpenAI server. chat_completions() rejects stream today. _completion_response() builds the reply. |
runtimes/common/agentkit_serve_common/conversation.py |
RunRequest, the request each runtime receives. Its optional on_tool_event callback, which runtimes call during a run, is the pattern to copy. |
runtimes/<runtime>/agentkit_serve/agent_factory.py |
Each runtime's run_agent(). |
runtimes/common/agentkit_serve_common/conformance.py |
Shared tests of the OpenAI server. Every runtime runs them through its tests/test_server.py. |
runtimes/common/agentkit_serve_common/parity.py |
Shared tests that run each real runtime against a fake model server. The fake model can already reply in streaming form when the request has "stream": true. |
Heads-up: open PR #36 also changes server.py. If it merges first, rebase onto it.
Step 1: basic streaming in the shared server
- In
chat_completions(), remove thestream_unsupportedcheck. Keep thetoolsandtool_choicechecks as they are, and run them before anything is sent. - When
req.streamis true, return a FastAPIStreamingResponsewithContent-Type: text/event-stream. Also setCache-Control: no-cacheandX-Accel-Buffering: noso proxies such as nginx don't hold pieces back. - Write each piece as
data: <json>\n\n. Use the sameid,createdandmodelin every piece. Send them in this order:- First piece:
"choices": [{"index": 0, "delta": {"role": "assistant", "content": ""}, "finish_reason": null}]. - One piece for each bit of text:
"delta": {"content": "..."}. - Last piece:
"delta": {}with"finish_reason": "stop". - Only if the request has
"stream_options": {"include_usage": true}: one more piece with"choices": []and theusageobject. Add astream_optionsfield toChatCompletionRequest. Today unknown fields are ignored. - Then
data: [DONE]\n\n.
- First piece:
- Errors:
- Before any text is sent, return the same JSON error and HTTP status that a non-streaming request gets today. To make this possible, wait for the first piece of text, or the end of the run, before you start the streaming response.
- After text has been sent, the 200 status is already out. Send
data: {"error": {"message": ..., "type": "agent_error", "code": ...}}and close the stream without[DONE]. The OpenAI Python SDK raises an error when it reads this. - In both cases, still call
health.record(exc)so/healthzfails after a fatal error, as it does today. - Same rule as today: error messages come only from the runtime's
AgentRunErrormessage and code, never from framework or model provider text.
- If the client disconnects, cancel the run. The next request must still work.
- In step 1 the runtime still returns the whole answer at once, so send
result.textas a single content piece.
Step 2: real streaming in each runtime
- Add an optional callback to
RunRequestnext toon_tool_event, for exampleon_text_delta: Callable[[str], Awaitable[None]] | None = None. The server sets it only for streaming requests.- If the runtime called
on_text_deltaat least once, the server has already sent the text, so it does not sendresult.textagain. - If the runtime never called it, the server sends
result.textas one piece, as in step 1. A runtime without real streaming still works.
- If the runtime called
- Send assistant text from every model step as it arrives. A model sometimes writes a short note such as "Let me look that up" before it calls a tool. That note shows up in the stream, even though the non-streaming answer may leave it out. Note this in the docs.
- Turn on model streaming only when
on_text_deltais set, so non-streaming requests behave exactly as they do now. - Each runtime already hooks into the run to report tool events, so add the text hook in the same place:
- pydantic-ai:
run_agent()already passes anevent_stream_handlertoagent.run()to watch tool calls. In that handler, also forward text fromPartStartEventwhen its part is aTextPart, and fromPartDeltaEventwhen its delta is aTextPartDelta. - LangGraph:
run_agent()callsgraph.ainvoke(). Switch tograph.astream()withstream_mode=["messages", "values"]. Forward text only from the model's AI message chunks, not from tool messages. BuildRunResultfrom the final"values"state, as today. - Microsoft Agent Framework:
run_agent()callsagent.run(...)inside a task that also watches for fatal tool failures. Keep that logic. Callagent.run(..., stream=True), forward the text of each update, and build the final response from the updates so the final text and usage come out as they do today.
- pydantic-ai:
Tests
- In
conformance.py, replacetest_stream_true_rejectedwith tests that check:- the content type, a first piece with
role, a last piece withfinish_reason: "stop", and the closing[DONE]; - that the joined text matches the non-streaming answer for the same reply;
- that the usage piece appears only with
stream_options.include_usage; - that
toolsandtool_choiceare still rejected whenstream: true; - that an error before any text returns the normal JSON error and status;
- that a missing bearer token still gets 401.
- the content type, a first piece with
- In
parity.py, add a test that runs each runtime against the fake model with one tool call, then a final answer split into several pieces. The client should receive more than one text piece. The fake model currently sends each reply as a single piece, so it may need a small change to split text. - Nice to have: a check with the official
openaiPython SDK andstream=Trueagainst a built image inscripts/parity-container-smoke.sh.
Run the tests for the shared package and for each runtime. See docs/development.md for setup:
uv run --directory runtimes/common --extra dev pytest -q
cd runtimes/<runtime> && python -m pytest -q # pydantic-ai, microsoft-agent-framework, langgraph
Docs
Update every place that says the OpenAI server doesn't stream:
README.md: the protocol table row "Default, non-streaming Chat Completions".docs/runtime-adapters.md: the line "stream: truereturns HTTP 400 with codestream_unsupported".docs/agent-abi.mdsection 4: "non-streaming run", andstream: truein the list of rejected fields.docs/architecture.md.- The docstring at the top of
server.py. runtimes/*/README.md.
Done when
curl -Nwith"stream": trueagainst a built image prints the answer in pieces and ends withdata: [DONE].- The OpenAI Python SDK with
stream=Trueworks against all three runtimes, and the joined text matches the non-streaming answer for the same reply. - Requests without
stream: truebehave exactly as before. All existing tests pass except the removedtest_stream_true_rejected. - An error before the first piece returns the same status and JSON as a non-streaming request. An error after the first piece ends the stream with an
errorpiece. - When a client disconnects, the run stops and the next request works.
- No doc says the OpenAI server doesn't stream.
- Dominant language
- Python
- Stars
- 7
- Forks
- 5
- Avg merge
- 3h 39m
- Merged PRs (30d)
- 1
Getting set up
- Ships a Dockerfile or Docker Compose file
- No pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from orka-agents/agentkit
-
fix(pydantic-ai): CI fails with newest pydantic-ai (unexpected 'history' argument)Possibly taken @gambtho claimed this 30 days ago. Open
Difficulty 3/5 1-2 days Newbie friendliness 35/100
orka-agents/agentkit#77 ·
-
Difficulty 5/5 Over a week Newbie friendliness 25/100
orka-agents/agentkit#76 · 3 comments ·
-
area/build area/orka area/runtime blocked enhancement
Difficulty 4/5 3-5 days Newbie friendliness 45/100
orka-agents/agentkit#69 ·
-
area/build area/orka area/runtime enhancement
Difficulty 4/5 3-5 days Newbie friendliness 68/100
orka-agents/agentkit#68 ·
-
area/build enhancement testing
Difficulty 5/5 Over a week Newbie friendliness 42/100
orka-agents/agentkit#65 ·
All issues in orka-agents/agentkit
Similar issues
-
enhancement
Difficulty 1/5 Under an hour Newbie friendliness 62/100
DaoCloud/DaoCloud-docs#7839 ·
Maintainers usually reply within 1 day
-
Difficulty 1/5 Under an hour Newbie friendliness 78/100
sav-oss-org/ptusa_main#1610 ·
Maintainers usually reply within 1 day
-
Difficulty 1/5 Under an hour Newbie friendliness 85/100
Maintainers usually reply within 1 day
-
bug status/accepted type/bug
Difficulty 2/5 1-3 hours Newbie friendliness 62/100
microsoft/apm#4925 · 1 comment ·
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
sagemathinc/sagebrush#1701 ·
Maintainers usually reply within 1 day