Skip to content

[BUG] Chat stream chunk model rejects standard OpenAI chunks - streaming examples print nothing #172

Closed

Description

Summary

The streaming chat examples print no assistant text for a standard OpenAI-format stream. create_chat_completion_stream yields raw SSEvent objects, and the root README.md ("Streaming Content"), examples/chat/README.md and examples/chat/main.py all validate each chunk with CreateChatCompletionStreamResponse and skip the chunk on ValidationError. The generated model is stricter than the chunks the gateway relays: ChatCompletionStreamChoice.finish_reason is required and non-nullable (inference_gateway/models.py:2644, openapi.yaml:3125-3128), and ChatCompletionStreamResponseDelta requires both content and role (inference_gateway/models.py:2573 and :2586, openapi.yaml:3212-3214). OpenAI-compatible providers send "finish_reason": null on every chunk except the last, send role only in the first delta and send an empty delta in the last chunk, and the gateway forwards provider lines unmodified (ChatCompletionsHandler in api/chat.go and StreamChatCompletions in providers/core/provider.go of inference-gateway/inference-gateway, whose own tests use {"delta":{"content":"Hello"},"finish_reason":null} chunks). Every content chunk is therefore rejected and silently skipped. The repo already records part of this in the strict xfail test test_stream_response_delta_allows_missing_content (tests/test_client.py:488-512), and closed issue #147 made the examples skip rejected chunks instead of crashing, which hides the problem. Fix options: relax the spec in inference-gateway/schemas (nullable finish_reason, optional content and role on the stream delta) and regenerate with task generate, or until then make the three examples read choices[0]["delta"].get("content") from the parsed JSON instead of validating with the strict model. Reproduced at v0.25.0 with a mocked HTTP response, not against a live gateway.

Steps to Reproduce

  1. Install the SDK from main (v0.25.0) with pip install -e ".[dev]".
  2. Save and run this script. It replays three chunks in the standard OpenAI stream shape through the loop from the README "Streaming Content" section:
import json
from unittest.mock import Mock, patch

from pydantic import ValidationError

from inference_gateway import CreateChatCompletionStreamResponse, InferenceGatewayClient, Message

chunks = [
    '{"id":"c1","object":"chat.completion.chunk","created":1,"model":"gpt-4o","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}',
    '{"id":"c1","object":"chat.completion.chunk","created":1,"model":"gpt-4o","choices":[{"index":0,"delta":{"content":"Hello"},"finish_reason":null}]}',
    '{"id":"c1","object":"chat.completion.chunk","created":1,"model":"gpt-4o","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}',
]
response = Mock(status_code=200)
response.raise_for_status.return_value = None
response.iter_lines.return_value = [f"data: {c}".encode() for c in chunks] + [b"data: [DONE]"]

client = InferenceGatewayClient("http://localhost:8080/v1")
printed = []
with patch("requests.Session.post", return_value=response):
    for chunk in client.create_chat_completion_stream(
        model="openai/gpt-4o", messages=[Message(role="user", content="Hi")]
    ):
        try:
            parsed = CreateChatCompletionStreamResponse.model_validate(json.loads(chunk.data))
        except ValidationError as e:
            print("rejected:", [f"{'.'.join(map(str, err['loc']))}: {err['type']}" for err in e.errors()])
            continue
        printed.append(parsed.choices[0].delta.content)
print("content printed:", printed)
  1. Observe that every chunk is rejected and no content is collected.

Expected Behavior

All three chunks validate and the loop prints Hello, so the README snippet and examples/chat/main.py show the streamed answer.

Actual Behavior

All three chunks are rejected and nothing is printed:

rejected: ['choices.0.finish_reason: literal_error']
rejected: ['choices.0.delta.role: missing', 'choices.0.finish_reason: literal_error']
rejected: ['choices.0.delta.content: missing', 'choices.0.delta.role: missing']
content printed: []

With the same chunks, the streaming section of examples/chat/main.py prints Assistant: followed by an empty line and no error.

Activity

  1. edenreich commented on Nov 17, 2026

    @edenreich
    Contributor

    @claude can you fix this?

  2. inference-gateway-maintainer commented on Nov 17, 2026

    @inference-gateway-maintainer
    ContributorAuthor

    Claude finished @edenreich's task in 2m 16s —— View job • fix/issue-172-20261117-1939 • [Create PR ➔](https://github.com/inference-gateway/python-sdk/compare/main...fix/issue-172-20261117-1939?quick_pull=1&title=Issue%20%23172%3A%20Changes%20from%20Claude&body=This%20PR%20addresses%20issue%20%23172%0A%0AGenerated%20with%20%5BClaude%20Code%5D(https%3A%2F%2Fclaude.ai%2Fcode)


    Fixed in PR #178

    • Add the issue to the Roadmap board (now in QA)
    • Read the examples, README, models and tests
    • Fix the streaming examples and README snippets
    • Run lint and tests
    • Commit, open the PR and file follow-up issues

    What changed

    The three streaming snippets no longer check each chunk against the strict CreateChatCompletionStreamResponse model. They read the parsed JSON instead (data.get("choices", []) -> choice.get("delta", {}).get("content")):

    • examples/chat/main.py - prints the content, and prints [Finished: <reason>] when finish_reason is set. I removed the imports that are no longer used.
    • README.md "Streaming Content" - same change. It still handles reasoning / reasoning_content, and a note now explains why the model isn't used.
    • examples/chat/README.md - same change, with a short note.

    inference_gateway/models.py is unchanged because it is generated code. The real fix belongs in the spec, so I opened inference-gateway/schemas#328: finish_reason needs to accept null, and role and content need to be optional on the stream delta. Once that lands, run task generate and the strict xfail test test_stream_response_delta_allows_missing_content will start passing.

    Verification

    • I ran the three chunks from this issue through examples/chat/main.py with a mocked HTTP response. It now prints Assistant: Hello and then [Finished: stop]. Before the fix it printed an empty line.
    • task lint passes.
    • task test: 53 passed, 1 xfailed (same as before).

    Follow-ups

    Not done: I didn't test against a live gateway, and I didn't edit models.py or the spec in this repo.
    | Branch

  3. moved this from Todo to In progress in 2026on Nov 17, 2026
  4. added a commit that references this issue on Nov 17, 2026
    a91a235
  5. moved this from In progress to QA in 2026on Nov 17, 2026
  6. moved this from QA to Done in 2026on Nov 17, 2026
  7. inference-gateway-releaser commented on Nov 17, 2026

    @inference-gateway-releaser
    Contributor

    🎉 This issue has been resolved in version 0.26.0 🎉

    The release is available on GitHub release

    Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugreleased

    Type

    Projects

    • Status
      Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions