Skip to content

Fix: /openai/<chat_id>/chat/completions not aware of session_id - #15155

Merged
wangq8 merged 1 commit into
infiniflow:mainfrom
wangq8:bugfix/fix-openapi-chat-not-aware-session_id
May 22, 2026
Merged

wangq8 merged 1 commit into
infiniflow:mainfrom
wangq8:bugfix/fix-openapi-chat-not-aware-session_id

Conversation

@wangq8

@wangq8 wangq8 commented May 22, 2026 •

Copy link
Copy Markdown
Collaborator

What problem does this PR solve?

Fix: /openai/<chat_id>/chat/completions not aware of session_id

Type of change

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

@coderabbitai

coderabbitai Bot commented May 22, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The PR extends the OpenAI chat completions endpoint with optional session persistence via session_id. It adds helpers to validate sessions, build model-ready messages from stored conversations, and structure final answers within session context. Both streaming and non-streaming paths now optionally save enriched conversations and echo the session identifier in responses. Two tests verify correct behavior for valid and invalid session identifiers.

Changes

Session Persistence in OpenAI Chat Completions

Layer / File(s) Summary
Imports and session preparation helpers
api/apps/restful_apis/openai_api.py
Reorganizes imports and introduces _prepare_session to load/validate session state with conversation cleanup, and _build_chat_messages to derive model-ready messages from stored or live conversations. Adds request validation for session_id normalization and type-checking with error handling for missing or invalid sessions.
Message construction with session support
api/apps/restful_apis/openai_api.py
Refactors the message-filtering loop to use _build_chat_messages, capturing both prepared messages and a message_id for later answer enrichment within sessions.
Streaming response session integration
api/apps/restful_apis/openai_api.py
Updates the SSE streaming generator to optionally attach session_id to response chunks, wraps streamed final answers via structure_answer when a session is present, and persists the updated conversation after streaming completes. Adjusts final payload construction to compute final_content from final_answer or accumulated content.
Non-streaming response session integration
api/apps/restful_apis/openai_api.py
In non-streaming mode, structures the final answer with session context when a session exists, persists the updated conversation, and includes session_id in the response payload when provided.
Session persistence tests
test/testcases/restful_api/test_openai_compatible.py
Adds test coverage for non-streaming requests with valid session_id (verifying response echoes the session identifier and persists user/assistant messages) and invalid session_id (verifying error response with "Session not found!" message).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • infiniflow/ragflow#14380: Modifies the same OpenAI chat completions endpoint (/openai/<chat_id>/chat/completions) with request/stream handling logic; this PR extends it with session_id-based conversation persistence.

Suggested labels

🐞 bug, 🐖api, size:L

Suggested reviewers

  • buua436

Poem

🐰 A rabbit hops through conversations long,
With sessions saved and messages strong,
Each final answer finds its place,
In stored dialogue's embrace,
The chat persists—no words are wrong! 🌱

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is incomplete. It restates the title but lacks detailed explanation of the problem, solution, and testing approach expected in the template. Expand the description with context about why session_id support is needed, what behavior changed, and how it was tested. Consider adding a brief summary of implementation details.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately reflects the main change: adding session_id awareness to the OpenAI chat completions endpoint.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.

@wangq8
wangq8 requested a review from buua436 May 22, 2026 09:40
@wangq8 wangq8 added the ci Continue Integration label May 22, 2026
@wangq8
wangq8 marked this pull request as ready for review May 22, 2026 09:41
@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label May 22, 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)

182-190: ⚡ Quick win

Add a request timeout to avoid hanging CI tests.

This test is the only new OpenAI POST case here without a timeout, which can stall the suite under transient backend issues.

Proposed fix
     res = rest_client.post(
         f"/openai/{chat_id}/chat/completions",
         json={
             "model": "model",
             "messages": [{"role": "user", "content": "hello"}],
             "stream": False,
             "session_id": "invalid_session",
         },
+        timeout=60,
     )
🤖 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 182 - 190,
The POST call using rest_client.post to f"/openai/{chat_id}/chat/completions"
(the request with json including "session_id": "invalid_session") needs a
request timeout to prevent CI hangs; modify the rest_client.post invocation in
this test to include a timeout parameter (for example timeout=5) so the request
fails fast on network/backend stalls instead of hanging the test suite.
api/apps/restful_apis/openai_api.py (1)

95-116: ⚡ Quick win

Add logs around session hydration and validation.

These branches rewrite the request from persisted state and can reject session_id, but there is no visibility when lookup fails or when a request is converted to session-backed messages. Add at least debug/warning logs around _prepare_session() and _build_chat_messages().

📍Possible shape
+logger = logging.getLogger(__name__)
+
 def _build_chat_messages(messages, conv=None):
     if conv is not None:
         if not conv.message:
+            logger.debug("Initializing empty message list for session %s", conv.id)
             conv.message = []
         user_message = dict(messages[-1])
         user_message.setdefault("id", str(uuid4()))
         user_message.setdefault("created_at", time.time())
+        logger.debug("Appending user message %s to session %s", user_message["id"], conv.id)
         conv.message.append(user_message)
         source_messages = conv.message
     else:
         source_messages = messages
@@
 def _prepare_session(chat_id, session_id):
     if not session_id:
         return None

     ok, conv = ConversationService.get_by_id(session_id)
     if not ok:
+        logger.warning("Session %s not found for chat %s", session_id, chat_id)
         return "Session not found!"
     if conv.dialog_id != chat_id:
+        logger.warning("Session %s does not belong to chat %s", session_id, chat_id)
         return "Session does not belong to this chat!"

As per coding guidelines, **/*.py: Add logging for new flows.

Also applies to: 119-133

🤖 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` around lines 95 - 116, Add debug/warning
logs in _prepare_session and _build_chat_messages to show when session
hydration/validation changes the request: in _prepare_session log when a
session_id lookup fails or is rejected (include the session_id and reason) and
when a request is converted to a session-backed conversation; in
_build_chat_messages log when conv is not None (include conv.id or identifier),
when conv.message is empty and initialized, and when the function drops messages
(e.g., skipping system or leading assistant messages) and the final message_id
returned. Use the module logger consistently for debug vs warning levels.
🤖 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`:
- Around line 155-159: The current lookup uses req.get("session_id",
extra_body.get("session_id", "")) which treats an explicit null in req as
present and hides extra_body.session_id; change the logic to pick the first
non-None value: read session_id = req.get("session_id") then if session_id is
None set session_id = extra_body.get("session_id", "") (so extra_body.session_id
is used when req.session_id is null), then validate type with the existing
isinstance check and return get_error_data_result("session_id must be a
string.") if it's not a str.

---

Nitpick comments:
In `@api/apps/restful_apis/openai_api.py`:
- Around line 95-116: Add debug/warning logs in _prepare_session and
_build_chat_messages to show when session hydration/validation changes the
request: in _prepare_session log when a session_id lookup fails or is rejected
(include the session_id and reason) and when a request is converted to a
session-backed conversation; in _build_chat_messages log when conv is not None
(include conv.id or identifier), when conv.message is empty and initialized, and
when the function drops messages (e.g., skipping system or leading assistant
messages) and the final message_id returned. Use the module logger consistently
for debug vs warning levels.

In `@test/testcases/restful_api/test_openai_compatible.py`:
- Around line 182-190: The POST call using rest_client.post to
f"/openai/{chat_id}/chat/completions" (the request with json including
"session_id": "invalid_session") needs a request timeout to prevent CI hangs;
modify the rest_client.post invocation in this test to include a timeout
parameter (for example timeout=5) so the request fails fast on network/backend
stalls instead of hanging the test suite.
🪄 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: dc6b3190-55ea-4a34-ab20-2d4f706e6fea

📥 Commits

Reviewing files that changed from the base of the PR and between 7e68441 and 3d477d9.

📒 Files selected for processing (2)
  • api/apps/restful_apis/openai_api.py
  • test/testcases/restful_api/test_openai_compatible.py

Comment on lines +155 to +159
session_id = req.get("session_id", extra_body.get("session_id", ""))
if session_id is None:
session_id = ""
if not isinstance(session_id, str):
return get_error_data_result("session_id must be a string.")

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

Don't let a null top-level session_id hide extra_body.session_id.

With the current lookup order, a payload like {"session_id": null, "extra_body": {"session_id": "abc"}} falls back to stateless handling instead of using "abc". Prefer precedence based on the first non-None value.

🔧 Suggested fix
-    session_id = req.get("session_id", extra_body.get("session_id", ""))
-    if session_id is None:
-        session_id = ""
+    session_id = req.get("session_id")
+    if session_id is None:
+        session_id = extra_body.get("session_id", "")
+    if session_id is None:
+        session_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` around lines 155 - 159, The current
lookup uses req.get("session_id", extra_body.get("session_id", "")) which treats
an explicit null in req as present and hides extra_body.session_id; change the
logic to pick the first non-None value: read session_id = req.get("session_id")
then if session_id is None set session_id = extra_body.get("session_id", "") (so
extra_body.session_id is used when req.session_id is null), then validate type
with the existing isinstance check and return get_error_data_result("session_id
must be a string.") if it's not a str.

@codecov

codecov Bot commented May 22, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.12%. Comparing base (7e68441) to head (3d477d9).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15155   +/-   ##
=======================================
  Coverage   93.12%   93.12%           
=======================================
  Files          10       10           
  Lines         713      713           
  Branches      116      116           
=======================================
  Hits          664      664           
  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.

@wangq8
wangq8 merged commit e6dd397 into infiniflow:main May 22, 2026
1 check passed
wangq8 added a commit that referenced this pull request May 25, 2026
…id" (#15205)

Reverts #15155 because this is never supported, keep
it as it is.
geversite pushed a commit to geversite/ragflow that referenced this pull request Jul 3, 2026
…id" (#15205)

Reverts infiniflow/ragflow#15155 because this is never supported, keep
it as it is.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant