Skip to content

fix(llm): strip non-generation keys from gen_conf for LiteLLM providers (#15427) - #15432

Merged
wangq8 merged 2 commits into
infiniflow:mainfrom
nickmopen:fix/litellm-strip-non-generation-gen-conf
Jun 2, 2026
Merged

wangq8 merged 2 commits into
infiniflow:mainfrom
nickmopen:fix/litellm-strip-non-generation-gen-conf

Conversation

@nickmopen

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Fixes #15427.

All LiteLLM-routed chats fail with:

  • Anthropic: litellm.BadRequestError: AnthropicException - {"type":"invalid_request_error","message":"model_type: Extra inputs are not permitted"}
  • OpenAI: litellm.BadRequestError: OpenAIException - Unknown parameter: 'model_type'

This is a regression from v0.25.4.

Root cause

A chat assistant's llm_setting is forwarded to the model as gen_conf. llm_setting can legitimately carry RAGFlow-internal metadata such as model_type (the chat REST APIs in api/apps/restful_apis/ read it back out of llm_setting), so that key ends up inside gen_conf.

Base._clean_conf (OpenAI-compatible providers) already whitelists the keys it forwards, so direct-OpenAI providers were unaffected. LiteLLMBase._clean_conf only dropped max_tokens and passed everything else straight through to litellm.acompletion, which forwarded model_type to the upstream provider — and Anthropic / OpenAI reject it. Because both Claude and GPT route through LiteLLM, every chat broke.

Fix

  • Extract the allowed-key set into a shared ALLOWED_GEN_CONF_KEYS constant and reuse it in Base._clean_conf.
  • Apply the same whitelist in LiteLLMBase._clean_conf, plus the LiteLLM-specific reasoning params (thinking, reasoning_effort, extra_body) that the model-family policies inject for reasoning models.

This covers all four LiteLLM completion paths (async_chat, async_chat_streamly, async_chat_with_tools, async_chat_streamly_with_tools), since they all route through _clean_conf.

Tests

Adds test/unit_test/rag/llm/test_clean_conf_whitelist.py covering both backends: model_type (and other stray keys) are dropped, genuine generation params and thinking survive, max_tokens is removed, and the whitelist invariants hold.

Type of change

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

…rs (infiniflow#15427)

A chat assistant's llm_setting is forwarded to the model as gen_conf.
llm_setting can carry RAGFlow-internal metadata such as model_type (the
chat REST APIs read it back out), so that key ends up in gen_conf.

Base._clean_conf already whitelisted the keys it forwards, so OpenAI-
compatible providers were unaffected. LiteLLMBase._clean_conf only dropped
max_tokens and passed everything else through to litellm.acompletion, which
forwarded model_type to the upstream provider. Anthropic rejected it with
"model_type: Extra inputs are not permitted" and OpenAI with "Unknown
parameter: 'model_type'", breaking all LiteLLM-routed chats (regression
from v0.25.4).

Extract the allowed-key set into a shared ALLOWED_GEN_CONF_KEYS constant,
reuse it in Base._clean_conf, and apply the same whitelist in
LiteLLMBase._clean_conf (plus LiteLLM reasoning params such as thinking /
reasoning_effort that the model-family policies inject).

Adds unit tests covering both backends.
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. 🌈 python Pull requests that update Python code 🐞 bug Something isn't working, pull request that fix bug. 🧪 test Pull requests that update test cases. labels May 29, 2026
@coderabbitai

coderabbitai Bot commented May 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 0a7b4353-55f7-49ee-8e91-5965912f8229

📥 Commits

Reviewing files that changed from the base of the PR and between eaa6821 and 1a0fc8e.

📒 Files selected for processing (1)
  • test/unit_test/rag/graphrag/conftest.py

📝 Walkthrough

Walkthrough

Centralizes generation-parameter allowlists in rag/llm/chat_model.py and updates Base._clean_conf and LiteLLMBase._clean_conf to filter forwarded gen_conf; adds regression tests and a guarded test stub change for Graphrag.

Changes

Generation Config Sanitization

Layer / File(s) Summary
Generation parameter allowlists and sanitization
rag/llm/chat_model.py
Adds ALLOWED_GEN_CONF_KEYS and LITELLM_ALLOWED_GEN_CONF_KEYS and updates Base._clean_conf and LiteLLMBase._clean_conf to filter gen_conf against these allowlists instead of inline sets.
Regression tests for generation config filtering
test/unit_test/rag/llm/test_clean_conf_whitelist.py
Adds tests verifying model_type and arbitrary internal keys are dropped, known generation params and LiteLLM thinking are preserved, max_tokens is dropped, and whitelist invariants hold; includes helper concrete classes for testing.
Test stub guard for Graphrag
test/unit_test/rag/graphrag/conftest.py
Conditionally assigns the test stub Base = object only when rag.llm.chat_model is a MagicMock, avoiding unconditional replacement of the real Base class.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 A stray model_type caused chats to stall,
I hopped in, filtered keys, and fixed it all.
Frozenset guards keep params neat,
Tests verify nothing slips past the beat.
Hooray — clean configs, tidy and small.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 6.67% 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 PR title accurately and specifically describes the main fix: stripping non-generation keys from gen_conf for LiteLLM providers, directly addressing the regression issue #15427.
Description check ✅ Passed The PR description is comprehensive, clearly explaining the root cause (model_type in gen_conf), the fix approach, test coverage, and includes the required type-of-change checkboxes from the template.
Linked Issues check ✅ Passed The PR fully addresses issue #15427: it prevents RAGFlow-internal keys (model_type) from being forwarded in gen_conf by implementing whitelisting for both Base and LiteLLMBase._clean_conf methods, restoring chat functionality for Anthropic and OpenAI providers.
Out of Scope Changes check ✅ Passed All changes directly support the PR objectives: modifications to chat_model.py implement whitelisting, new test file verifies the fix, and conftest.py change resolves test isolation issues caused by mock conflicts.

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

@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.

🧹 Nitpick comments (1)
test/unit_test/rag/llm/test_clean_conf_whitelist.py (1)

69-72: 💤 Low value

Consider adding pytest priority markers for test categorization.

Per coding guidelines, backend tests should use priority markers. These regression tests for a critical bug fix would benefit from @pytest.mark.p1 or @pytest.mark.p2 markers to ensure they run in priority test suites.

Example marker application
+@pytest.mark.p1
 def test_litellm_drops_model_type():
     cleaned = _make_litellm()._clean_conf({"temperature": 0.5, "model_type": "chat"})

As per coding guidelines: test/**/*.py: Use pytest with priority markers (p1/p2/p3) for Python backend tests.

🤖 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/unit_test/rag/llm/test_clean_conf_whitelist.py` around lines 69 - 72,
The test function test_litellm_drops_model_type should be marked with the
appropriate pytest priority marker per backend guidelines; add a decorator like
`@pytest.mark.p1` (or `@pytest.mark.p2` as appropriate) above the function and
ensure pytest is imported in the test module (e.g., add "import pytest" if
missing) so the test runs in the prioritized test suite and remains unchanged
otherwise; locate the test by the function name test_litellm_drops_model_type in
the test file and apply the marker decorator directly above it.
🤖 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.

Nitpick comments:
In `@test/unit_test/rag/llm/test_clean_conf_whitelist.py`:
- Around line 69-72: The test function test_litellm_drops_model_type should be
marked with the appropriate pytest priority marker per backend guidelines; add a
decorator like `@pytest.mark.p1` (or `@pytest.mark.p2` as appropriate) above the
function and ensure pytest is imported in the test module (e.g., add "import
pytest" if missing) so the test runs in the prioritized test suite and remains
unchanged otherwise; locate the test by the function name
test_litellm_drops_model_type in the test file and apply the marker decorator
directly above it.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 70759101-018f-4845-8135-a99147fadd34

📥 Commits

Reviewing files that changed from the base of the PR and between cd18cfa and eaa6821.

📒 Files selected for processing (2)
  • rag/llm/chat_model.py
  • test/unit_test/rag/llm/test_clean_conf_whitelist.py

@nickmopen

Copy link
Copy Markdown
Contributor Author

@yingfeng , I'd really appreciate it if you could take a look and review this when you have some time. Thanks!

@nickmopen

Copy link
Copy Markdown
Contributor Author

@buua436 , Could you take a look at this one as well?

@wangq8 wangq8 added the ci Continue Integration label Jun 1, 2026
@wangq8
wangq8 marked this pull request as draft June 1, 2026 09:53
@wangq8
wangq8 marked this pull request as ready for review June 1, 2026 09:53
@wangq8

wangq8 commented Jun 1, 2026

Copy link
Copy Markdown
Collaborator

@nickmopen please fix the UT.

rag/graphrag/conftest.py mocks heavy deps at import time by mutating the
global sys.modules. It guarded module *creation* (`if name not in
sys.modules`) but then unconditionally assigned
`sys.modules["rag.llm.chat_model"].Base = object`.

rag/graphrag/ is collected before rag/llm/, and earlier test packages
(e.g. api/db/services) already import the real chat_model. The
unconditional assignment overwrote the genuine `Base` class with
`object`, and that corruption leaked into the rag/llm unit tests added in
this PR, which import the real class:

    AttributeError: '_ConcreteBase' object has no attribute '_clean_conf'

(LiteLLMBase was untouched, so only the Base-path tests failed.)

Only stub `Base` when chat_model was actually mocked. graphrag uses it
purely as a type alias (`from rag.llm.chat_model import Base as
CompletionLLM`), so the real class is equally fine when already loaded.
@codecov

codecov Bot commented Jun 1, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (cd18cfa) to head (1a0fc8e).
⚠️ Report is 18 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #15432      +/-   ##
==========================================
- Coverage   94.56%   93.16%   -1.40%     
==========================================
  Files          10       10              
  Lines         717      717              
  Branches      118      118              
==========================================
- Hits          678      668      -10     
- Misses         25       29       +4     
- Partials       14       20       +6     

☔ 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 bebf6ed into infiniflow:main Jun 2, 2026
1 check passed
@coderabbitai coderabbitai Bot mentioned this pull request Jun 9, 2026
1 task done
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 🌈 python Pull requests that update Python code size:M This PR changes 30-99 lines, ignoring generated files. 🧪 test Pull requests that update test cases.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: litellm model_type error in chats

2 participants