Skip to content

Fix: Chat completion generation parameter overrides - #15389

Merged
yingfeng merged 8 commits into
infiniflow:mainfrom
bitloi:fix/15388-chat-completion-generation-params
Jun 3, 2026
Merged

yingfeng merged 8 commits into
infiniflow:mainfrom
bitloi:fix/15388-chat-completion-generation-params

Conversation

@bitloi

@bitloi bitloi commented May 29, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Closes #15388.

Chat completion routes did not reliably honor per-request generation settings:

  • /api/v1/chat/completions copied generation settings with a truthiness check, so valid zero values such as temperature: 0, top_p: 0, frequency_penalty: 0, presence_penalty: 0, and max_tokens: 0 were dropped.
  • /api/v1/openai/{chat_id}/chat/completions did not forward standard generation settings into the request-specific dialog LLM settings before calling async_chat.

This PR preserves explicitly supplied generation parameters, including zero values, and merges request-level overrides into existing dialog settings where appropriate.

The supported generation parameter keys and merge behavior live in a shared REST API helper to keep both completion routes aligned.

Validation:

  • git diff --check
  • python3 -m py_compile api/apps/restful_apis/_generation_params.py api/apps/restful_apis/chat_api.py api/apps/restful_apis/openai_api.py test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py
  • uv run ruff check api/apps/restful_apis/_generation_params.py api/apps/restful_apis/chat_api.py api/apps/restful_apis/openai_api.py test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py
  • ZHIPU_AI_API_KEY=dummy uv run pytest test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py -q -k generation_params

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

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds a generation-parameter helper module and uses it in chat and OpenAI completion endpoints to extract/pop and merge request-provided generation settings into dialog.llm_setting (preserving explicit zero values and merging into existing settings). Adds unit tests covering forwarding, zero preservation, and merge semantics.

Changes

Generation Parameter Preservation Across Completion APIs

Layer / File(s) Summary
Generation config helpers
api/apps/restful_apis/_generation_params.py
Adds GENERATION_CONFIG_KEYS, extract_generation_config(req), pop_generation_config(req), and merge_generation_config(dialog, generation_config) to centralize extraction, popping, and merging of request generation parameters.
Session completion endpoint refactor
api/apps/restful_apis/chat_api.py
Replaces inline truthiness-based construction with pop_generation_config(req) and calls merge_generation_config(dia, chat_model_config) so existing dia.llm_setting is updated rather than overwritten.
OpenAI endpoint generation parameter support
api/apps/restful_apis/openai_api.py
Imports and applies merge_generation_config(dia, extract_generation_config(req)) after dia.llm_id resolution so OpenAI-style completion requests forward generation params into the dialog before calling async_chat.
Unit test coverage & test mocks
test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py
Adds tests for OpenAI non-stream forwarding of generation params, preserving explicit zero-valued generation parameters, and merging request parameters into an existing dialog llm_setting while keeping unrelated fields and not mutating the original object; updates test mocks for tenant model service helpers and TenantService.get_by_id return.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant chat_api.session_completion
  participant openai_api.openai_chat_completions
  participant _generation_params.pop_generation_config
  participant _generation_params.extract_generation_config
  participant _generation_params.merge_generation_config
  Client->>chat_api.session_completion: POST /api/v1/chat/completions (req)
  chat_api.session_completion->>_generation_params.pop_generation_config: pop_generation_config(req)
  chat_api.session_completion->>_generation_params.merge_generation_config: merge_generation_config(dia, config)
  Client->>openai_api.openai_chat_completions: POST /api/v1/openai/{chat_id}/chat/completions (req)
  openai_api.openai_chat_completions->>_generation_params.extract_generation_config: extract_generation_config(req)
  openai_api.openai_chat_completions->>_generation_params.merge_generation_config: merge_generation_config(dia, config)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

ci

Suggested reviewers

  • buua436

Poem

I'm a rabbit nudging zeros through the gate,
I keep your temps and tops from meeting fate,
Helpers pop and merge each careful key,
Dialogs keep what you intend to be,
Tests hop by — now generation params are straight. 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 18.18% 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: fixing chat completion APIs to reliably handle generation parameter overrides, which is the core objective of this PR.
Linked Issues check ✅ Passed All primary objectives from issue #15388 are met: the PR preserves zero values by replacing truthiness checks with presence checks [#15388], forwards generation parameters to the OpenAI route [#15388], and centralizes merge behavior in a shared helper [#15388].
Out of Scope Changes check ✅ Passed All changes are directly aligned with fixing the generation parameter issues identified in #15388. The new module, endpoint modifications, and test additions all target the stated bugs without introducing unrelated modifications.
Description check ✅ Passed The PR description fully addresses the template requirements, clearly explaining the problem solved and identifying the change type as a bug fix.

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

@bitloi
bitloi marked this pull request as ready for review May 29, 2026 06:00
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. 🐞 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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
api/apps/restful_apis/chat_api.py (1)

1209-1215: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Fix overwrite of dia.llm_setting when overriding chat_model_id

chat_model_config is derived from _extract_generation_config(req) and is {} when the request doesn’t include any generation params. In the chat_model_id path, the code does dia.llm_setting = chat_model_config, wiping the existing dia.llm_setting; the else path preserves it because _merge_generation_config() early-returns when generation_config is falsy.

♻️ Proposed fix
         if chat_model_id:
             if not await thread_pool_exec(TenantLLMService.get_api_key, tenant_id=dia.tenant_id, model_name=chat_model_id):
                 return get_data_error_result(message=f"Cannot use specified model {chat_model_id}.")
             dia.llm_id = chat_model_id
-            dia.llm_setting = chat_model_config
-        else:
-            _merge_generation_config(dia, chat_model_config)
+        _merge_generation_config(dia, chat_model_config)
🤖 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/chat_api.py` around lines 1209 - 1215, When
chat_model_id is provided the code unconditionally sets dia.llm_setting =
chat_model_config which can wipe existing settings because chat_model_config
(from _extract_generation_config(req)) may be {} — instead, only overwrite or
merge when chat_model_config is truthy: check chat_model_config and if non-empty
assign or merge into dia.llm_setting (use same merging behavior as
_merge_generation_config), otherwise leave dia.llm_setting intact; update the
chat_model_id branch that calls TenantLLMService.get_api_key and sets dia.llm_id
to perform this conditional assignment/merge instead of a blind assignment.
🧹 Nitpick comments (1)
api/apps/restful_apis/openai_api.py (1)

33-45: ⚡ Quick win

Duplicated generation-config helpers.

_GENERATION_CONFIG_KEYS, _extract_generation_config, and _merge_generation_config are byte-for-byte identical to the ones added in chat_api.py. Consider extracting them into a shared utility module to avoid divergence as the supported key list evolves.

🤖 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 33 - 45, The three helpers
_GENERATION_CONFIG_KEYS, _extract_generation_config, and
_merge_generation_config are duplicated; extract them into a single shared
utility (e.g., a new module exposing _GENERATION_CONFIG_KEYS,
extract_generation_config, merge_generation_config), replace the local copies in
openai_api.py and chat_api.py to import the shared symbols, update references
(rename callers if you change function names) and ensure deepcopy and getattr
usage remains in merge_generation_config so dialog.llm_setting behavior is
preserved.
🤖 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 45-47: Add a second blank line between the two top-level function
definitions _merge_generation_config and _validate_llm_id so there are two blank
lines separating them (satisfy E302/ruff); locate the function def for
_merge_generation_config and ensure exactly two blank lines before the line
starting with def _validate_llm_id(llm_id, tenant_id, llm_setting=None).

---

Outside diff comments:
In `@api/apps/restful_apis/chat_api.py`:
- Around line 1209-1215: When chat_model_id is provided the code unconditionally
sets dia.llm_setting = chat_model_config which can wipe existing settings
because chat_model_config (from _extract_generation_config(req)) may be {} —
instead, only overwrite or merge when chat_model_config is truthy: check
chat_model_config and if non-empty assign or merge into dia.llm_setting (use
same merging behavior as _merge_generation_config), otherwise leave
dia.llm_setting intact; update the chat_model_id branch that calls
TenantLLMService.get_api_key and sets dia.llm_id to perform this conditional
assignment/merge instead of a blind assignment.

---

Nitpick comments:
In `@api/apps/restful_apis/openai_api.py`:
- Around line 33-45: The three helpers _GENERATION_CONFIG_KEYS,
_extract_generation_config, and _merge_generation_config are duplicated; extract
them into a single shared utility (e.g., a new module exposing
_GENERATION_CONFIG_KEYS, extract_generation_config, merge_generation_config),
replace the local copies in openai_api.py and chat_api.py to import the shared
symbols, update references (rename callers if you change function names) and
ensure deepcopy and getattr usage remains in merge_generation_config so
dialog.llm_setting behavior is preserved.
🪄 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: bf570d80-d74a-4789-8c2d-ebb12fa1d3b3

📥 Commits

Reviewing files that changed from the base of the PR and between ea3a5db and d9b8962.

📒 Files selected for processing (3)
  • api/apps/restful_apis/chat_api.py
  • api/apps/restful_apis/openai_api.py
  • test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py

Comment thread api/apps/restful_apis/openai_api.py Resolved
@bitloi
bitloi force-pushed the fix/15388-chat-completion-generation-params branch from d9b8962 to 31503c4 Compare May 29, 2026 06:26
@bitloi
bitloi marked this pull request as draft May 29, 2026 06:27

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
api/apps/restful_apis/chat_api.py (1)

1197-1203: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Fix dia.llm_setting overwrite when chat_model_id is set.

When chat_model_id is provided, the code assigns dia.llm_setting = chat_model_config instead of merging. Since chat_model_config comes from extract_generation_config(req) (only generation keys like temperature, top_p, max_tokens), any request that only switches llm_id (no generation params) yields {} and overwrites the dialog’s existing generation settings. The else branch correctly preserves existing settings via merge_generation_config(dia, chat_model_config) (which returns early on empty config). Prefer merging here as well so dialog generation behavior doesn’t change unexpectedly.

🐛 Proposed fix
             dia.llm_id = chat_model_id
-            dia.llm_setting = chat_model_config
+            merge_generation_config(dia, chat_model_config)
         else:
             merge_generation_config(dia, chat_model_config)
🤖 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/chat_api.py` around lines 1197 - 1203, When
chat_model_id is set the handler currently does dia.llm_setting =
chat_model_config which can clobber existing generation settings with an empty
config; change it to merge the incoming generation config into the dialog using
merge_generation_config(dia, chat_model_config) instead of direct assignment
while still setting dia.llm_id = chat_model_id and keeping the pre-check via
TenantLLMService.get_api_key; this ensures existing dia.llm_setting is preserved
when chat_model_config is empty and respects merge_generation_config's
early-return behavior.
🤖 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/chat_api.py`:
- Line 1144: The extracted generation settings returned by
extract_generation_config(req) are left in req and get forwarded into
dialog_service.async_chat via **req; remove the consumed keys (temperature,
top_p, frequency_penalty, presence_penalty, max_tokens) from req after calling
extract_generation_config and before calling async_chat so they are not leaked
into downstream kwargs—i.e., call extract_generation_config(req) to get
chat_model_config, then pop or del those specific keys from req, and then pass
chat_model_config plus the sanitized req into dialog_service.async_chat.

---

Outside diff comments:
In `@api/apps/restful_apis/chat_api.py`:
- Around line 1197-1203: When chat_model_id is set the handler currently does
dia.llm_setting = chat_model_config which can clobber existing generation
settings with an empty config; change it to merge the incoming generation config
into the dialog using merge_generation_config(dia, chat_model_config) instead of
direct assignment while still setting dia.llm_id = chat_model_id and keeping the
pre-check via TenantLLMService.get_api_key; this ensures existing
dia.llm_setting is preserved when chat_model_config is empty and respects
merge_generation_config's early-return behavior.
🪄 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: 6f4f284a-470e-4f58-b211-d3b3478a5655

📥 Commits

Reviewing files that changed from the base of the PR and between d9b8962 and 31503c4.

📒 Files selected for processing (4)
  • api/apps/restful_apis/_generation_params.py
  • api/apps/restful_apis/chat_api.py
  • api/apps/restful_apis/openai_api.py
  • test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py

Comment thread api/apps/restful_apis/chat_api.py Resolved
@bitloi
bitloi force-pushed the fix/15388-chat-completion-generation-params branch 2 times, most recently from 3b24817 to 7fd583e Compare May 29, 2026 06:36
@bitloi
bitloi marked this pull request as ready for review May 29, 2026 06:38
@bitloi bitloi changed the title Fix chat completion generation parameter overrides Fix: Chat completion generation parameter overrides May 29, 2026
@bitloi bitloi changed the title Fix: Chat completion generation parameter overrides fix: Chat completion generation parameter overrides May 29, 2026
@bitloi
bitloi marked this pull request as draft May 29, 2026 06:42
@bitloi bitloi changed the title fix: Chat completion generation parameter overrides Fix: Chat completion generation parameter overrides May 29, 2026
@bitloi
bitloi marked this pull request as ready for review May 29, 2026 06:46
@bitloi
bitloi force-pushed the fix/15388-chat-completion-generation-params branch from 27ede91 to af96847 Compare May 29, 2026 09:52
@bitloi

bitloi commented Jun 2, 2026

Copy link
Copy Markdown
Contributor Author

Hi @wangq8, @JinHai-CN, @KevinHuSh, @yingfeng, @xugangqiang, would you please review my PR and give me your feedback?

@yingfeng yingfeng added the ci Continue Integration label Jun 2, 2026
@yingfeng
yingfeng marked this pull request as draft June 2, 2026 05:05
@yingfeng
yingfeng marked this pull request as ready for review June 2, 2026 05:05
@codecov

codecov Bot commented Jun 2, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (0f6f7b3) to head (8ff1418).
⚠️ Report is 10 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15389   +/-   ##
=======================================
  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

@yingfeng
yingfeng merged commit a75ea7b into infiniflow:main Jun 3, 2026
2 of 3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. 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.

[Bug]: Chat completion APIs drop valid generation parameters such as temperature=0

3 participants