feat(runtime): stream chat completion answers when clients ask for stream: true

Open
#53 0 comments 0 reactions 0 assignees View on GitHub

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
Tech stack
fastapi, python

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

area/runtime enhancement help wanted

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 stream is false or missing, nothing changes.
  • If stream is true, 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.chunk objects, ending with data: [DONE].

Do this in two steps. Each one can be its own PR.

  1. 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.
  2. 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/responses from #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.yaml file 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
  1. In chat_completions(), remove the stream_unsupported check. Keep the tools and tool_choice checks as they are, and run them before anything is sent.
  2. When req.stream is true, return a FastAPI StreamingResponse with Content-Type: text/event-stream. Also set Cache-Control: no-cache and X-Accel-Buffering: no so proxies such as nginx don't hold pieces back.
  3. Write each piece as data: <json>\n\n. Use the same id, created and model in 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 the usage object. Add a stream_options field to ChatCompletionRequest. Today unknown fields are ignored.
    • Then data: [DONE]\n\n.
  4. 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 /healthz fails after a fatal error, as it does today.
    • Same rule as today: error messages come only from the runtime's AgentRunError message and code, never from framework or model provider text.
  5. If the client disconnects, cancel the run. The next request must still work.
  6. In step 1 the runtime still returns the whole answer at once, so send result.text as a single content piece.
Step 2: real streaming in each runtime
  1. Add an optional callback to RunRequest next to on_tool_event, for example on_text_delta: Callable[[str], Awaitable[None]] | None = None. The server sets it only for streaming requests.
    • If the runtime called on_text_delta at least once, the server has already sent the text, so it does not send result.text again.
    • If the runtime never called it, the server sends result.text as one piece, as in step 1. A runtime without real streaming still works.
  2. 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.
  3. Turn on model streaming only when on_text_delta is set, so non-streaming requests behave exactly as they do now.
  4. 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 an event_stream_handler to agent.run() to watch tool calls. In that handler, also forward text from PartStartEvent when its part is a TextPart, and from PartDeltaEvent when its delta is a TextPartDelta.
    • LangGraph: run_agent() calls graph.ainvoke(). Switch to graph.astream() with stream_mode=["messages", "values"]. Forward text only from the model's AI message chunks, not from tool messages. Build RunResult from the final "values" state, as today.
    • Microsoft Agent Framework: run_agent() calls agent.run(...) inside a task that also watches for fatal tool failures. Keep that logic. Call agent.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.
Tests
  • In conformance.py, replace test_stream_true_rejected with tests that check:
    • the content type, a first piece with role, a last piece with finish_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 tools and tool_choice are still rejected when stream: true;
    • that an error before any text returns the normal JSON error and status;
    • that a missing bearer token still gets 401.
  • 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 openai Python SDK and stream=True against a built image in scripts/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: true returns HTTP 400 with code stream_unsupported".
  • docs/agent-abi.md section 4: "non-streaming run", and stream: true in the list of rejected fields.
  • docs/architecture.md.
  • The docstring at the top of server.py.
  • runtimes/*/README.md.

Done when

  • curl -N with "stream": true against a built image prints the answer in pieces and ends with data: [DONE].
  • The OpenAI Python SDK with stream=True works against all three runtimes, and the joined text matches the non-streaming answer for the same reply.
  • Requests without stream: true behave exactly as before. All existing tests pass except the removed test_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 error piece.
  • 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

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from orka-agents/agentkit

All issues in orka-agents/agentkit

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.