Skip to content

fix(openai): keep streamed choices separate when n > 1 - #2155

Open
mayuriphad wants to merge 2 commits into
langfuse:mainfrom
mayuriphad:fix/openai-stream-multiple-choices
Open

mayuriphad wants to merge 2 commits into
langfuse:mainfrom
mayuriphad:fix/openai-stream-multiple-choices

Conversation

@mayuriphad

@mayuriphad mayuriphad commented Nov 25, 2026 •

Copy link
Copy Markdown

What does this PR do?

With n > 1 and stream=True, OpenAI sends the deltas of all choices interleaved in one stream, each tagged with choice.index. _extract_streamed_openai_response ignored the index and appended every delta to one message, so the generation output was a mix of all choices:

client.chat.completions.create(model="gpt-4o-mini", messages=[...], n=2, stream=True)
# deltas: (0, "Hello"), (1, "Hi"), (0, " world"), (1, " there")
# recorded output before: "HelloHi world there"
# recorded output after:  ["Hello world", "Hi there"]

Tool calls from different choices were merged into one list in the same way.

This PR accumulates each chat choice by its index. When the stream has more than one choice, the output is a list of choices, the same shape _get_langfuse_data_from_default_response already records for a non-streamed response with several choices. A stream with one choice (or chunks without an index) gives the same output as before.

Type of change

  • Bug fix
  • New feature
  • Breaking change
  • Refactor
  • Documentation update
  • Tooling, CI, or repo maintenance

Verification

python -m pytest tests/unit/test_openai.py tests/unit/test_openai_prompt_extraction.py   # 62 passed
python -m pytest -n 4 tests/unit                                                       # same results as on main
ruff check langfuse/openai.py tests/unit/test_openai.py
ruff format --check langfuse/openai.py tests/unit/test_openai.py

The new test test_streaming_chat_completion_keeps_multiple_choices_separate fails on main with assert 'HelloHi world there' == ['Hello world', 'Hi there'] and passes with this change. I could not run mypy locally; CI covers it.

Checklist

  • I self-reviewed the diff using code_review.md.
  • I added or updated tests for behavior changes.
  • I updated docs, examples, or .env.template if needed.
  • I did not hand-edit generated files; if generated files changed, I used the upstream regeneration path.
  • I did not commit secrets or credentials.

RetriggerView in GreptileConfidence Score: 4/5

The PR appears safe to merge, with a non-blocking test gap for tool calls across choices.

Summary

Keeps streamed chat choices separate by choice.index.

  • Streamed chat choices are recorded as separate answers.

Reviews (1) · Last reviewed commit: "fix(openai): keep streamed choices separ..." · Reviewed by Greptile


Note

Low Risk
Localized fix to streamed chat output parsing for tracing; single-choice behavior is unchanged and tests lock in the new multi-choice shape.

Overview
Fixes incorrect Langfuse generation output when streaming chat completions with n > 1. OpenAI interleaves deltas from all choices in one stream, tagged by choice.index; the extractor previously merged every delta into a single message (and mixed tool calls across choices).

_extract_streamed_openai_response now accumulates each choice in a chat_completions map keyed by index. When more than one choice is present, the recorded output is a list of assistant message dicts, matching the shape already used for non-streamed multi-choice responses. Single-choice streams (or missing index) behave as before.

Unit tests cover interleaved text and per-choice tool call assembly.

Reviewed by Cursor Bugbot for commit 626679d. Bugbot is set up for automated code reviews on this repo. Configure here.

With n > 1, OpenAI interleaves the deltas of every choice in one stream.
The stream handler accumulated all of them into a single message, so the
generation output was a garbled mix of the choices (e.g. "HelloHi world
there"). Accumulate each choice by its index and record a list of
choices, matching the non-streamed response shape.

Signed-off-by: mayuriphad <mayuriphad656@gmail.com>
Copilot AI balanced review requested due to automatic review settings November 25, 2026 02:03

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Claude Code Review

This pull request is from a fork — automated review is disabled. A repository maintainer can comment @claude review to run a one-time review.

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

Comment thread tests/unit/test_openai.py
Comment on lines +475 to +476
function_call=None,
tool_calls=None,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Tool choices lack test coverage

The new test covers only text, although this fix also separates tool calls between choices. Add a case where two choices both emit tool_calls with tool index 0, then interleave their argument fragments. Assert that each choice keeps its own call ID, function name, and arguments. The existing single-choice tool test cannot catch calls being merged across choices.

Prompt To Fix With AI
This is a comment left during a code review.
Path: tests/unit/test_openai.py
Line: 475-476

Comment:
**Tool choices lack test coverage**

The new test covers only text, although this fix also separates tool calls between choices. Add a case where two choices both emit `tool_calls` with tool index `0`, then interleave their argument fragments. Assert that each choice keeps its own call ID, function name, and arguments. The existing single-choice tool test cannot catch calls being merged across choices.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added test_streaming_chat_completion_keeps_tool_calls_of_choices_separate in 626679d. Two choices both use tool index 0 and their argument fragments interleave. The test checks that each choice keeps its own call ID, name and arguments.

@ayushmnnit ayushmnnit left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ran c20bf5a end to end: real openai client, SSE served by httpx.MockTransport, n=2, output read from the in-memory span exporter. tests/unit/test_openai.py and test_openai_prompt_extraction.py pass (62 passed).

case main this PR
text, interleaved HelloHi world there ["Hello world", "Hi there"]
tool calls, both choices use tool index 0, args interleaved one call, id call_b, name get_weather, args {"city":{"tz":"Paris"}"UTC"} two calls, each with its own id, name and args
async stream, text HelloHi world there ["Hello world", "Hi there"]

So the tool-call case Greptile asked about already works; adding that sequence as a test would lock it in. Two smaller things below. Script: lf_2155_edges.py (in the details block).

script
"""Edge cases for langfuse-python PR #2155 (n > 1 streaming).

Copy into tests/unit/ and run:
LANGFUSE_PUBLIC_KEY=pk LANGFUSE_SECRET_KEY=sk uv run --frozen pytest tests/unit/test_lf_2155_edges.py -s -q
Real openai SDK, SSE served by httpx.MockTransport, spans read from the in-memory exporter.
"""
import json

import httpx
import pytest

from langfuse._client.attributes import LangfuseOtelSpanAttributes as A
from langfuse.openai import openai as lf_openai


def sse(chunks):
    body = "".join(
        "data: " + json.dumps({"id": "c", "object": "chat.completion.chunk", "created": 1,
                               "model": "gpt-4o-mini", **c}) + "\n\n"
        for c in chunks
    )
    return (body + "data: [DONE]\n\n").encode()


def ch(i, delta, finish=None):
    return {"choices": [{"index": i, "delta": delta, "finish_reason": finish}]}


def tc(i, tid, name, args):
    d = {"index": 0, "function": {"arguments": args}}
    if tid:
        d.update(id=tid, type="function")
        d["function"]["name"] = name
    return d


TEXT = [
    ch(0, {"role": "assistant", "content": "Hello"}),
    ch(1, {"role": "assistant", "content": "Hi"}),
    ch(0, {"content": " world"}),
    ch(1, {"content": " there"}),
    ch(0, {}, "length"),
    ch(1, {}, "stop"),
    {"choices": [], "usage": {"prompt_tokens": 3, "completion_tokens": 4, "total_tokens": 7}},
]

TOOLS = [
    ch(0, {"role": "assistant", "tool_calls": [tc(0, "call_a", "get_weather", "")]}),
    ch(1, {"role": "assistant", "tool_calls": [tc(1, "call_b", "get_time", "")]}),
    ch(0, {"tool_calls": [tc(0, None, None, '{"city":')]}),
    ch(1, {"tool_calls": [tc(1, None, None, '{"tz":')]}),
    ch(0, {"tool_calls": [tc(0, None, None, '"Paris"}')]}),
    ch(1, {"tool_calls": [tc(1, None, None, '"UTC"}')]}),
    ch(0, {}, "tool_calls"),
    ch(1, {}, "tool_calls"),
]

NON_STREAMED = {
    "id": "c", "object": "chat.completion", "created": 1, "model": "gpt-4o-mini",
    "choices": [
        {"index": 0, "message": {"role": "assistant", "content": "Hello world"}, "finish_reason": "length"},
        {"index": 1, "message": {"role": "assistant", "content": "Hi there"}, "finish_reason": "stop"},
    ],
    "usage": {"prompt_tokens": 3, "completion_tokens": 4, "total_tokens": 7},
}


def client(chunks, is_async=False):
    def handler(request):
        if b'"stream":true' in request.content.replace(b" ", b""):
            return httpx.Response(200, content=sse(chunks), headers={"content-type": "text/event-stream"})
        return httpx.Response(200, json=NON_STREAMED)

    if is_async:
        return lf_openai.AsyncOpenAI(api_key="t", http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)))
    return lf_openai.OpenAI(api_key="t", http_client=httpx.Client(transport=httpx.MockTransport(handler)))


def dump(span, label):
    print(f"\n[{label}] output   =", span.attributes.get(A.OBSERVATION_OUTPUT))
    print(f"[{label}] finish   =", span.attributes.get("langfuse.observation.metadata.finish_reason"))


KW = dict(model="gpt-4o-mini", messages=[{"role": "user", "content": "hi"}], n=2)


def test_stream_text(langfuse_memory_client, get_span):
    list(client(TEXT).chat.completions.create(name="s_text", stream=True, **KW))
    langfuse_memory_client.flush()
    dump(get_span("s_text"), "stream text")


def test_stream_tools(langfuse_memory_client, get_span):
    list(client(TOOLS).chat.completions.create(name="s_tools", stream=True, **KW))
    langfuse_memory_client.flush()
    dump(get_span("s_tools"), "stream tools")


def test_non_streamed(langfuse_memory_client, get_span):
    client(TEXT).chat.completions.create(name="ns", **KW)
    langfuse_memory_client.flush()
    dump(get_span("ns"), "non-streamed")


@pytest.mark.asyncio
async def test_async_stream_text(langfuse_memory_client, get_span):
    stream = await client(TEXT, is_async=True).chat.completions.create(name="as_text", stream=True, **KW)
    async for _ in stream:
        pass
    langfuse_memory_client.flush()
    dump(get_span("as_text"), "async stream text")

Comment thread langfuse/openai.py
)

delta = choice.get("delta", None)
choice_finish_reason = choice.get("finish_reason", None)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

finish_reason is still a single value for the whole stream, so with n=2 the metadata keeps whichever choice finished last. With choice 0 ending on length and choice 1 on stop, the span says "stop" and the truncated choice can't be seen. Fine to leave out of this PR, but now that outputs are kept per choice, a list of finish reasons (or one per choice) would match them.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, finish_reason should be one per choice. I left it out of this PR because it changes the metadata type from a string to a list, which may affect existing consumers. I can open a follow-up if you want it.

Comment thread langfuse/openai.py Outdated

def get_chat_response() -> Any:
if len(chat_completions) > 1:
# Same shape as a non-streamed response with several choices.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not quite the same shape: a non-streamed n=2 response records [{"role": "assistant", "content": "Hello world"}, {"role": "assistant", "content": "Hi there"}], while this records ["Hello world", "Hi there"]. That follows the existing single-choice streaming convention (plain string), so it may be the intended trade-off, but the comment and PR text should say which one it matches. If one choice returns text and the other a tool call, the list mixes a string and a dict (checked: ['Hello', {'role': 'assistant', 'tool_calls': [...]}]).

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for checking this. In 626679d, every choice in a streamed n>1 response is now a message dict, the same as the non-streamed path: [{"role": "assistant", "content": "Hello world"}, {"role": "assistant", "content": "Hi there"}]. Text and tool-call choices no longer mix strings and dicts. A single-choice stream still records a plain string, as before.

@langfuse-ai-gate-approver

langfuse-ai-gate-approver Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

AI review gate — AI review passed

Clean review from: Cursor Bugbot.

Configuration: the repository's .github/ai-gate.yml on the base branch (the defaults without one).

History (latest 5 heads, newest first)

  • 626679d092d1 gate success — AI review passed
  • c20bf5ae363f gate pending — Waiting for AI review

With n > 1, streamed text choices were recorded as plain strings,
unlike the non-streamed path which records one message dict per
choice. Wrap text-only choices so both paths produce the same shape,
and test that tool calls of two choices sharing tool index 0 stay
separate.

Signed-off-by: mayuriphad <mayuriphad656@gmail.com>
@ayushmnnit

Copy link
Copy Markdown

Re-ran my script on 626679d: streamed n=2 text, tool calls and async now record the same message dicts as the non-streamed path, and the mixed text plus tool-call case gives two dicts instead of a string and a dict. test_openai.py and test_openai_prompt_extraction.py pass here (63 passed).

Keeping finish_reason out of this PR makes sense given the type change. A follow-up is up to the maintainers; if it happens, a list in choice order would line up with the output list.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants