Repository navigation
Fix: default OpenAI chat completions to non-stream - #15394
Conversation
📝 WalkthroughWalkthroughThe OpenAI-compatible chat completions endpoint default behavior changed: when the ChangesStream Default Behavior
🎯 1 (Trivial) | ⏱️ ~3 minutes Possibly related issues
Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. 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
🧹 Nitpick comments (2)
test/testcases/restful_api/test_openai_compatible.py (1)
143-161: 💤 Low valueConsider enhancing test coverage to match the comprehensive checks in
test_openai_compatible_nonstream_shape.The new test validates the default non-streaming behavior, but it duplicates some assertions from
test_openai_compatible_nonstream_shape(lines 113-141) while being less comprehensive. Consider either:
- Adding the full validation checks (usage tokens, message structure, etc.) to ensure the default behavior is identical to explicit
stream=False, or- Simplifying to only verify that the response is JSON (not SSE) and defer detailed structure validation to the existing test.
🔍 Proposed enhancement to match comprehensive validation
`@pytest.mark.p2` def test_openai_compatible_defaults_to_nonstream_when_stream_is_missing(rest_client, create_chat): chat_id = create_chat("restful_openai_default_nonstream_chat") res = rest_client.post( f"/openai/{chat_id}/chat/completions", json={ "model": "model", "messages": [{"role": "user", "content": "hello"}], }, timeout=60, ) assert res.status_code == 200 assert "application/json" in res.headers.get("Content-Type", ""), res.headers.get("Content-Type", "") payload = res.json() assert payload["object"] == "chat.completion", payload assert isinstance(payload["choices"], list) and payload["choices"], payload - assert payload["choices"][0].get("finish_reason") == "stop", payload + first_choice = payload["choices"][0] + assert first_choice.get("finish_reason") == "stop", payload + assert first_choice.get("message", {}).get("role") == "assistant", payload + assert "content" in first_choice.get("message", {}), payload + + usage = payload.get("usage", {}) + assert "prompt_tokens" in usage, usage + assert "completion_tokens" in usage, usage + assert "total_tokens" in usage, usage🤖 Prompt for 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. In `@test/testcases/restful_api/test_openai_compatible.py` around lines 143 - 161, The test test_openai_compatible_defaults_to_nonstream_when_stream_is_missing currently duplicates but is less thorough than test_openai_compatible_nonstream_shape; either extend it to perform the same comprehensive assertions as test_openai_compatible_nonstream_shape (verify payload["usage"] tokens, message structure in payload["choices"][0]["message"], finish_reason, object, non-empty choices, and content/text fields) so default behavior equals explicit stream=False, or reduce this test to only assert that the response is JSON (Content-Type and non-SSE) and remove duplicated structural checks so the detailed validation remains solely in test_openai_compatible_nonstream_shape.api/apps/restful_apis/openai_api.py (1)
165-165: 💤 Low valueConsider adding logging for the default streaming behavior.
When the
streamparameter is omitted and the default is used, consider logging this decision to aid debugging and observability. As per coding guidelines, new flows should include logging.📝 Proposed logging addition
stream_mode = bool(req.get("stream", False)) +if "stream" not in req: + logging.debug("stream parameter not provided, defaulting to non-streaming mode for chat_id=%s", chat_id)🤖 Prompt for 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. In `@api/apps/restful_apis/openai_api.py` at line 165, When the code computes stream_mode = bool(req.get("stream", False)) add an explicit log entry when the "stream" parameter is absent (i.e., req.get("stream") returns the default) to record that the default streaming behavior was used; locate the code around stream_mode and call the module's logger (e.g., logger.info or app.logger.debug consistent with existing logging in the file) with a concise message like "stream parameter missing; using default stream_mode=False" (include the resolved stream_mode value) so the decision is observable for debugging.
🤖 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/apps/restful_apis/openai_api.py`:
- Line 165: The current line setting stream_mode = bool(req.get("stream",
False)) is correct per OpenAI's contract but needs to be explicitly documented
as intentional: update the comment or docstring near stream_mode (and any nearby
handler for /openai/{chat_id}/chat/completions) to state that when "stream" is
omitted it intentionally defaults to false (single JSON response) to match
OpenAI, and ensure related test name/description
("defaults_to_nonstream_when_stream_is_missing") and docs reflect this as
expected behavior rather than a bug.
---
Nitpick comments:
In `@api/apps/restful_apis/openai_api.py`:
- Line 165: When the code computes stream_mode = bool(req.get("stream", False))
add an explicit log entry when the "stream" parameter is absent (i.e.,
req.get("stream") returns the default) to record that the default streaming
behavior was used; locate the code around stream_mode and call the module's
logger (e.g., logger.info or app.logger.debug consistent with existing logging
in the file) with a concise message like "stream parameter missing; using
default stream_mode=False" (include the resolved stream_mode value) so the
decision is observable for debugging.
In `@test/testcases/restful_api/test_openai_compatible.py`:
- Around line 143-161: The test
test_openai_compatible_defaults_to_nonstream_when_stream_is_missing currently
duplicates but is less thorough than test_openai_compatible_nonstream_shape;
either extend it to perform the same comprehensive assertions as
test_openai_compatible_nonstream_shape (verify payload["usage"] tokens, message
structure in payload["choices"][0]["message"], finish_reason, object, non-empty
choices, and content/text fields) so default behavior equals explicit
stream=False, or reduce this test to only assert that the response is JSON
(Content-Type and non-SSE) and remove duplicated structural checks so the
detailed validation remains solely in test_openai_compatible_nonstream_shape.
🪄 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: e314a775-5360-449c-b51c-a1a94154725d
📒 Files selected for processing (2)
api/apps/restful_apis/openai_api.pytest/testcases/restful_api/test_openai_compatible.py
| tools = None | ||
| toolcall_session = None | ||
| stream_mode = req.get("stream", True) | ||
| stream_mode = bool(req.get("stream", False)) |
There was a problem hiding this comment.
🧩 Analysis chain
🌐 Web query:
OpenAI chat completions API stream parameter default value
💡 Result:
The default value of the OpenAI Chat Completions API request parameter stream is non-streaming (i.e., false) when you omit it. Streaming only happens when you explicitly set stream: true. [1] In other words: if you don’t provide stream in the JSON body to /v1/chat/completions, you should expect a single non-SSE JSON response rather than SSE token deltas.[1]
Citations:
🏁 Script executed:
#!/bin/bash
# Description: Find references to OpenAI endpoint usage without explicit stream parameter
# Search for calls to the endpoint without stream parameter
rg -n -A5 -B5 '/openai/.*/chat/completions' --type=py --type=md --type=js --type=ts
# Search for documentation mentioning default streaming behavior
rg -n -i 'stream.*default|default.*stream' --type=md --type=py -g '!test*'Repository: infiniflow/ragflow
Length of output: 20340
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Show the surrounding implementation for stream_mode
sed -n '130,220p' api/apps/restful_apis/openai_api.py | nl -ba | sed -n '1,120p'
# Inspect where stream_mode is used (nearby)
rg -n "stream_mode\s*=" api/apps/restful_apis/openai_api.py
rg -n "stream_mode" api/apps/restful_apis/openai_api.py
# Inspect the specific test that asserts default behavior when stream is missing
sed -n '120,210p' test/testcases/restful_api/test_openai_compatible.py | nl -ba
# Inspect the client note about server defaults to stream=True
rg -n "server defaults to stream=True|stream parameter is not sent" admin/client/ragflow_client.py
sed -n '1180,1255p' admin/client/ragflow_client.py | nl -ba
# Inspect docs lines that mention default streaming behavior
rg -n -i "\"stream\".*default|stream.*default|true.*Enable streaming.*default|\"false\".*default" docs/references/http_api_reference.md
sed -n '4100,4175p' docs/references/http_api_reference.md | nl -baRepository: infiniflow/ragflow
Length of output: 105
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Add line numbers via awk (nl is unavailable)
# Show surrounding implementation for stream_mode
awk 'NR>=130 && NR<=220 {printf "%6d\t%s\n", NR, $0}' api/apps/restful_apis/openai_api.py
# Inspect where stream_mode is used
rg -n "stream_mode\s*=" api/apps/restful_apis/openai_api.py
rg -n "stream_mode" api/apps/restful_apis/openai_api.py
# Inspect the test that asserts default behavior when stream is missing
awk 'NR>=120 && NR<=210 {printf "%6d\t%s\n", NR, $0}' test/testcases/restful_api/test_openai_compatible.py
rg -n "defaults_to_nonstream_when_stream_is_missing" test/testcases/restful_api/test_openai_compatible.py
sed -n '130,180p' test/testcases/restful_api/test_openai_compatible.py
# Inspect the client note about server defaults to stream=True
rg -n "server defaults to stream=True|stream parameter is not sent" admin/client/ragflow_client.py
sed -n '1200,1250p' admin/client/ragflow_client.py
# Inspect docs lines that mention default streaming behavior
rg -n -i "\"stream\".*default|stream.*default|true.*Enable streaming.*default|\"false\".*default" docs/references/http_api_reference.md
sed -n '4110,4165p' docs/references/http_api_reference.mdRepository: infiniflow/ragflow
Length of output: 15281
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect logging usage in openai_api.py around openai_chat_completions
rg -n "logging\.|logger\.|loguru|getLogger" api/apps/restful_apis/openai_api.py
rg -n "openai_chat_completions|stream_mode|req\.get\(\"stream\"" api/apps/restful_apis/openai_api.py
# Show the beginning of openai_chat_completions for context (avoid huge output)
sed -n '70,220p' api/apps/restful_apis/openai_api.py | head -n 170
# Check docs for the OpenAI-compatible endpoint stream default wording
rg -n "openai/.*/chat/completions|Create chat completion|\"stream\".*(default|false)" docs/references/http_api_reference.md -n
sed -n '5130,5195p' docs/references/http_api_reference.mdRepository: infiniflow/ragflow
Length of output: 8892
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Search for logging related to streaming path
rg -n "stream_mode|SSE|event-stream|chat\.completion\.chunk|\\[DONE\\]|stream\\b" api/apps/restful_apis/openai_api.py
# Find the "Create chat completion" section in docs and show the stream parameter docs around it
rg -n "Create chat completion|/openai/\\{chat_id\\}/chat/completions" docs/references/http_api_reference.md
# show a nearby window around the request parameters where stream is documented
sed -n '5600,5750p' docs/references/http_api_reference.md | head -n 220
# Also print around the earlier "stream" default hit to confirm endpoint context
sed -n '5140,5185p' docs/references/http_api_reference.mdRepository: infiniflow/ragflow
Length of output: 4704
Clarify stream default for OpenAI-compatible chat completions (/openai/{chat_id}/chat/completions)
api/apps/restful_apis/openai_api.py defaults stream to false when omitted (stream_mode = bool(req.get("stream", False))), matching OpenAI’s spec; the repo also has coverage asserting “defaults_to_nonstream_when_stream_is_missing” and docs that "stream" is "false" by default (single JSON response). Clients that want SSE streaming must send "stream": true, so this should be framed as matching the OpenAI request contract (not a non-breaking bug fix).
🤖 Prompt for 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.
In `@api/apps/restful_apis/openai_api.py` at line 165, The current line setting
stream_mode = bool(req.get("stream", False)) is correct per OpenAI's contract
but needs to be explicitly documented as intentional: update the comment or
docstring near stream_mode (and any nearby handler for
/openai/{chat_id}/chat/completions) to state that when "stream" is omitted it
intentionally defaults to false (single JSON response) to match OpenAI, and
ensure related test name/description
("defaults_to_nonstream_when_stream_is_missing") and docs reflect this as
expected behavior rather than a bug.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15394 +/- ##
=======================================
Coverage 93.16% 93.16%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 668 668
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
|
LGTM |
What problem does this PR solve?
default OpenAI chat completions to non-stream when
streamis omitted#15356
Type of change