Skip to content

fix(api): forward vendor fields on chat messages and completions - #833

Open
paultranvan wants to merge 3 commits into
developfrom
fix/forward-vendor-fields-chat-schemas
Open

fix(api): forward vendor fields on chat messages and completions#833
paultranvan wants to merge 3 commits into
developfrom
fix/forward-vendor-fields-chat-schemas

Conversation

@paultranvan

@paultranvan paultranvan commented Jul 28, 2026

Copy link
Copy Markdown
Collaborator

Ported from a production hotfix: OpenRag was silently dropping OpenAI fields it
did not declare, so they never reached the downstream LLM.

OpenAIMessage

An OpenAI message is more than role/contentname, tool_calls,
function_call, tool_call_id. Pydantic's default extra="ignore" dropped all
of them at parse time, before the router dumped the payload, so the history
forwarded to the model was silently truncated.

OpenAIChatCompletionRequest already carries extra="allow" with the comment
"Accept and forward vendor-specific OpenAI params" — this applies the same policy
one level down, where the vendor fields actually live.

Concretely, QueryService._sanitize_messages already branches on
msg.get("tool_calls") / msg.get("function_call") to leave a content-free
assistant turn alone. Those branches were unreachable: the schema stripped the
fields before the sanitizer ever saw them.

OpenAICompletionRequest

Same passthrough on the legacy /completions endpoint, for consistency.
extra="allow" only admits undeclared keys, so the deliberate n / best_of
bounds (resource-exhaustion guard) still validate — covered by a test.

Tests

Three unit tests in tests/unit/api/schemas/test_api_schema_imports.py:

  • extra message fields (name, tool_calls) survive model_dump
  • _sanitize_messages preserves a tool_calls assistant turn end-to-end
  • /completions forwards suffix/user while still rejecting n=9

Full unit suite: no new failures (2204 → 2207 passing).

Summary by CodeRabbit

  • New Features

    • Preserves vendor-specific parameters and message metadata in OpenAI-compatible requests.
    • Supports tool and developer message roles.
    • Supports tool-call messages without text content, including multi-turn conversations.
    • Adds options to control retrieved source inclusion and response behavior.
  • Bug Fixes

    • Prevents valid tool-related fields and custom completion parameters from being discarded.
    • Handles empty or content-free system messages safely.
    • Maintains validation for existing bounded parameters.

@coderabbitai

coderabbitai Bot commented Jul 28, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 964c73d5-05b6-4967-a4ee-98c7f819a8fc

📥 Commits

Reviewing files that changed from the base of the PR and between 7e6349c and c6a706e.

📒 Files selected for processing (1)
  • openrag/services/orchestrators/query_service.py

Included review availability: Your plan provides up to 2 included reviews per hour; 1 remains after this review.


📝 Walkthrough

Walkthrough

Changes

OpenAI compatibility

Layer / File(s) Summary
Update OpenAI schema contracts
openrag/api/schemas/user/chat.py
OpenAIMessage accepts tool and developer roles, nullable content, and extra OpenAI fields. Chat and completion requests expose retrieval-source metadata. Completion requests preserve vendor parameters.
Validate message and request passthrough
tests/unit/api/schemas/test_api_schema_imports.py
Tests cover tool-call fields, nullable content, message replay, developer and tool roles, vendor parameters, and bounds validation.
Handle missing message content
openrag/services/orchestrators/query_service.py, tests/unit/services/orchestrators/test_query_service.py
Query-history rendering and leading system-prompt extraction handle missing or null content. Tests cover tool-call turns and empty system messages.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Merge Risk: ⚪ Minimal · up to c6a70

This localized change forwards vendor-specific fields while preserving existing validation behavior, with unit-test coverage for the affected paths; no actionable merge-blocking risk remains after normal checks and review.

Suggested reviewers: ahmath-gadji, ewan102

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: forwarding vendor-specific fields for chat messages and completion requests.
Docstring Coverage ✅ Passed Docstring coverage is 82.35% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 17 functions across 4 files.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/forward-vendor-fields-chat-schemas

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 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 `@openrag/api/schemas/user/chat.py`:
- Around line 7-13: Update the chat router’s request logging to avoid
serializing full request.messages now that UserMessage allows extras via
model_config. In the logging path using truncate(str(request.messages)), log
only safe message metadata or explicitly redact extra fields, while preserving
passthrough of fields needed by downstream LLM processing.
- Around line 7-15: Update the message schema’s role declaration in the model
containing model_config to accept "tool" alongside the existing roles, allowing
tool-result messages with tool_call_id to validate and pass through. Add a
regression test covering a role="tool" message that includes tool_call_id.

In `@tests/unit/api/schemas/test_api_schema_imports.py`:
- Around line 117-137: Extend
test_chat_message_passes_through_extra_openai_fields to assert preservation of
tool_calls[0].function.name and function.arguments, plus tool_call_id and
function_call using the corresponding message fixtures. Keep the existing name
and tool-call ID assertions, and ensure nested OpenAI fields are verified after
model_dump(exclude_none=True).
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 939bd10a-b875-4e34-bfa5-f0515a6e396b

📥 Commits

Reviewing files that changed from the base of the PR and between db3482c and 4b081d3.

📒 Files selected for processing (2)
  • openrag/api/schemas/user/chat.py
  • tests/unit/api/schemas/test_api_schema_imports.py

Comment thread openrag/api/schemas/user/chat.py Outdated
Comment thread openrag/api/schemas/user/chat.py Outdated
Comment thread tests/unit/api/schemas/test_api_schema_imports.py
@paultranvan
paultranvan marked this pull request as draft July 29, 2026 07:03
@paultranvan
paultranvan force-pushed the fix/forward-vendor-fields-chat-schemas branch 2 times, most recently from 95b9993 to fc2d87c Compare August 26, 2026 08:09
@paultranvan
paultranvan force-pushed the fix/forward-vendor-fields-chat-schemas branch from fc2d87c to 85e3757 Compare August 26, 2026 08:58
@paultranvan
paultranvan marked this pull request as ready for review August 26, 2026 09:03
@Ahmath-Gadji Ahmath-Gadji self-assigned this Aug 26, 2026
i = 0
while i < len(raw_messages) and raw_messages[i]["role"] == "system":
parts.append(raw_messages[i]["content"])
content = raw_messages[i].get("content")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same defensive-read pattern is missing at query_service.py:363 (generate_query):

chat_history = "".join(f"{m['role']}: {m['content']}\n" for m in messages)

m['content'] is unguarded there. Since content can now be absent (assistant tool_calls turn, dropped by exclude_none=True), and default rag.mode is ChatBotRag (not SimpleRag), a tool-call-replay history 500s with KeyError: 'content'. Verified against this branch's actual generate_query. Suggest m.get('content') or '' there too.

@paultranvan
paultranvan force-pushed the fix/forward-vendor-fields-chat-schemas branch from 85e3757 to 7e6349c Compare August 26, 2026 14:59
@paultranvan
paultranvan force-pushed the fix/forward-vendor-fields-chat-schemas branch from 7e6349c to c6a706e Compare August 26, 2026 16:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants