Skip to content

Fix: default OpenAI chat completions to non-stream - #15394

Merged
yingfeng merged 1 commit into
infiniflow:mainfrom
buua436:codex/openai-stream-default
May 29, 2026
Merged

yingfeng merged 1 commit into
infiniflow:mainfrom
buua436:codex/openai-stream-default

Conversation

@buua436

@buua436 buua436 commented May 29, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

default OpenAI chat completions to non-stream when stream is omitted
#15356

Type of change

  • Bug Fix (non-breaking change which fixes an issue)

@coderabbitai

coderabbitai Bot commented May 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The OpenAI-compatible chat completions endpoint default behavior changed: when the stream request parameter is omitted, responses now default to non-streaming JSON instead of SSE streaming. A test case validates this new default by posting without a stream field and asserting a JSON response with proper completion metadata.

Changes

Stream Default Behavior

Layer / File(s) Summary
Stream default behavior and validation
api/apps/restful_apis/openai_api.py, test/testcases/restful_api/test_openai_compatible.py
stream_mode default changed from True to False when stream is omitted; new test validates the endpoint returns non-streaming JSON with finish_reason == "stop" when stream field is absent.

🎯 1 (Trivial) | ⏱️ ~3 minutes

Possibly related issues

Possibly related PRs

  • infiniflow/ragflow#14380: Also touches the OpenAI-compatible openai_chat_completions handler in api/apps/restful_apis/openai_api.py and modifies stream handling logic.

Suggested labels

🐞 bug, 🐖api

Suggested reviewers

  • wangq8
  • cike8899

Poem

A streaming default once set too high,
Now gentle JSON flows by and by,
When stream is missing, the response flows free,
Non-streaming JSON, as intended to be! 🐰✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: defaulting OpenAI chat completions to non-streaming behavior when the stream parameter is omitted.
Description check ✅ Passed The description includes both required template sections: problem statement with issue reference and type of change selection, though somewhat minimal in detail.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@buua436 buua436 changed the title [codex] default OpenAI chat completions to non-stream Fix: default OpenAI chat completions to non-stream May 29, 2026
@buua436 buua436 added the ci Continue Integration label May 29, 2026
@buua436
buua436 marked this pull request as ready for review May 29, 2026 07:10
@dosubot dosubot Bot added size:XS This PR changes 0-9 lines, ignoring generated files. 🌈 python Pull requests that update Python code 🐖api The modified files are located under directory 'api/apps/sdk' 🐞 bug Something isn't working, pull request that fix bug. labels May 29, 2026

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 1

🧹 Nitpick comments (2)
test/testcases/restful_api/test_openai_compatible.py (1)

143-161: 💤 Low value

Consider 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:

  1. Adding the full validation checks (usage tokens, message structure, etc.) to ensure the default behavior is identical to explicit stream=False, or
  2. 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 value

Consider adding logging for the default streaming behavior.

When the stream parameter 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

📥 Commits

Reviewing files that changed from the base of the PR and between b79f79d and 0704aee.

📒 Files selected for processing (2)
  • api/apps/restful_apis/openai_api.py
  • test/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))

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

🧩 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 -ba

Repository: 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.md

Repository: 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.md

Repository: 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.md

Repository: 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

codecov Bot commented May 29, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (b79f79d) to head (0704aee).

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@xugangqiang

Copy link
Copy Markdown
Contributor

LGTM

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

Labels

🐖api The modified files are located under directory 'api/apps/sdk' 🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration 🌈 python Pull requests that update Python code size:XS This PR changes 0-9 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants