Repository navigation
Fix OpenAI agent stream chunk shape - #16402
yuzhichang merged 2 commits into
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthrough
ChangesOpenAI streaming chunk response
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@api/utils/api_utils.py`:
- Around line 428-431: The terminating stream chunk in api_utils.py is always
setting usage to None, so the final finish_reason="stop" response drops the
already computed token totals. Update the helper that builds the stream chunk to
populate usage from the provided prompt_tokens and completion_tokens when this
is the final chunk, and keep the existing behavior for non-terminal chunks. Add
a regression test around the chunk-building path to verify the final streamed
chunk includes usage totals.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: d79c909f-cfa3-473d-adfc-64fbb0bed92a
📒 Files selected for processing (2)
api/utils/api_utils.pytest/unit_test/api/utils/test_api_utils.py
78db4e9 to
f86a0e7
Compare
3bb183f to
6bb20b0
Compare
|
Synced with latest main. Could a maintainer add the ci label so workflows can run? Okay, please review it. |
5bc93ed to
44c3ab4
Compare
|
Follow-up: branch is current with |
|
Can someone take a look when you have a chance? |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #16402 +/- ##
==========================================
- Coverage 94.56% 93.16% -1.40%
==========================================
Files 10 10
Lines 717 717
Branches 118 118
==========================================
- Hits 678 668 -10
- Misses 25 29 +4
- Partials 14 20 +6 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
Can someone take a look when you have a chance? |
1 similar comment
|
Can someone take a look when you have a chance? |
|
@Harsh23Kashyap Please fix unit test failure. |
|
ragflow_preflight unit test test_get_data_openai_stream_response_shape_is_unchanged is failing on upstream main itself (test was added in 98189cd in PR #16401 but the function signature changed in a later commit, so the test asserts the old shape). Not caused by this PR — flagging in case maintainers want a follow-up. Branch is current and ready for review. |
|
Can someone take a look when you have a chance? |
1 similar comment
|
Can someone take a look when you have a chance? |
b822e59 to
403342f
Compare
Taking over this PR. A clarification on the test failure attribution, since it caused some confusion above: The failing test passes on upstream/main by itself. Verified against `infiniflow/ragflow` at the merge-base of this branch (commit `5c8b51cbb`):
The test only fails after this branch's commits land, because the commits change `get_data_openai` to emit the expanded 7-key shape (`+created`, `+system_fingerprint`, `+usage`, `+logprobs`, `+delta.{role,function_call,tool_calls}`) — and the upstream test asserts the old shape. The conflict is purely between this PR's intentional shape change and an upstream test pinned to the previous shape. What I did to fix it (just pushed):
Verification:
The non-stream `created` coverage that `98189cd`'s tests provided is dropped by the conflict resolution. If we want it back as a follow-up, a small commit adding `test_get_data_openai_defaults_created_to_current_timestamp` (non-stream, monkeypatched) would close the gap. Happy to do that in a separate PR if reviewers want. |
Align the streaming chunk returned by
`api.utils.api_utils.get_data_openai(stream=True)` with the OpenAI
protocol, matching the shape already used by the non-streaming
return and by `chat.completion` elsewhere in the codebase.
Changes:
- top-level: add `system_fingerprint` (empty string)
- `choices[0].delta`: add `role` ("assistant"), `function_call` (None),
`tool_calls` (None)
- `choices[0]`: add `logprobs` (None)
- top-level: preserve an explicit `created` value; default to
`int(time.time())` when not provided, so OpenAI clients always
receive an integer timestamp
Behavior preserved:
- `delta.content` semantics unchanged
- existing reference injection (callers mutating `delta.reference`)
still works
Tests added:
- test_get_data_openai_stream_chunk_matches_openai_shape: asserts the
full chunk shape with `time.time` monkeypatched for determinism
- test_get_data_openai_stream_preserves_explicit_created_value:
asserts `created=0` round-trips through the stream path
- test_get_data_openai_stream_delta_allows_reference_payload: asserts
callers can extend `delta` with a `reference` payload
Closes infiniflow#8175.
Make `usage` on the streaming chunk dynamic: populated when
`finish_reason` is set (i.e. the terminal chunk in a stream) and
`None` for intermediate chunks. This matches the OpenAI streaming
protocol, where the final chunk carries the token accounting while
intermediate chunks stay light.
The populated `usage` block includes:
- prompt_tokens, completion_tokens, total_tokens
- completion_tokens_details.{reasoning_tokens,
accepted_prediction_tokens, rejected_prediction_tokens} (all 0)
Tests added:
- test_get_data_openai_terminal_stream_chunk_includes_usage: asserts
the full `usage` block is present when `finish_reason="stop"` and
that `choices[0].finish_reason` carries the terminator
403342f to
803b389
Compare
What problem does this PR solve?
Closes #8175.
The Agent OpenAI-compatible streaming path uses
get_data_openai(..., stream=True), but that helper currently returns a minimal chunk shape. The main OpenAI-compatible chat endpoint already includes chunk metadata such ascreated,system_fingerprint,usage,logprobs, and assistant role/tool placeholders.This PR aligns the Agent stream helper with that existing OpenAI-compatible chunk shape while keeping the current
delta.contentbehavior and existing reference injection path intact.Type of change
Verification
./.venv/bin/python -m pytest test/unit_test/api/utils/test_api_utils.py -qpython3 -m py_compile api/utils/api_utils.py test/unit_test/api/utils/test_api_utils.pyuvx ruff check api/utils/api_utils.py test/unit_test/api/utils/test_api_utils.py