Repository navigation
Fix: /openai/<chat_id>/chat/completions not aware of session_id - #15155
Conversation
📝 WalkthroughWalkthroughThe PR extends the OpenAI chat completions endpoint with optional session persistence via ChangesSession Persistence in OpenAI Chat Completions
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes 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)
182-190: ⚡ Quick winAdd 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 winAdd 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
📒 Files selected for processing (2)
api/apps/restful_apis/openai_api.pytest/testcases/restful_api/test_openai_compatible.py
| 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.") |
There was a problem hiding this comment.
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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
…id" (#15205) Reverts infiniflow/ragflow#15155 because this is never supported, keep it as it is.
What problem does this PR solve?
Fix: /openai/<chat_id>/chat/completions not aware of session_id
Type of change