Repository navigation
fix(openai): keep streamed choices separate when n > 1 - #2155
mayuriphad wants to merge 2 commits into
Conversation
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>
|
|
| function_call=None, | ||
| tool_calls=None, |
There was a problem hiding this 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.
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!
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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")| ) | ||
|
|
||
| delta = choice.get("delta", None) | ||
| choice_finish_reason = choice.get("finish_reason", None) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
|
||
| def get_chat_response() -> Any: | ||
| if len(chat_completions) > 1: | ||
| # Same shape as a non-streamed response with several choices. |
There was a problem hiding this comment.
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': [...]}]).
There was a problem hiding this comment.
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.
AI review gate — AI review passedClean review from: Cursor Bugbot. Configuration: the repository's History (latest 5 heads, newest first)
|
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>
|
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. Keeping |
What does this PR do?
With
n > 1andstream=True, OpenAI sends the deltas of all choices interleaved in one stream, each tagged withchoice.index._extract_streamed_openai_responseignored the index and appended every delta to one message, so the generation output was a mix of all choices: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_responsealready records for a non-streamed response with several choices. A stream with one choice (or chunks without anindex) gives the same output as before.Type of change
Verification
The new test
test_streaming_chat_completion_keeps_multiple_choices_separatefails onmainwithassert 'HelloHi world there' == ['Hello world', 'Hi there']and passes with this change. I could not run mypy locally; CI covers it.Checklist
code_review.md..env.templateif needed.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.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 bychoice.index; the extractor previously merged every delta into a single message (and mixed tool calls across choices)._extract_streamed_openai_responsenow accumulates each choice in achat_completionsmap 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 missingindex) 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.