Skip to content

feat(litellm): forward reasoning effort to Grok - #2530

Closed
Kyzcreig wants to merge 2 commits into
The-PR-Agent:mainfrom
Kyzcreig:feature/grok-reasoning-effort
Closed

Kyzcreig wants to merge 2 commits into
The-PR-Agent:mainfrom
Kyzcreig:feature/grok-reasoning-effort

Conversation

@Kyzcreig

Copy link
Copy Markdown
Contributor

Summary

  • add a default-off config.enable_grok_reasoning_effort compatibility flag
  • forward xAI-supported low, medium, and high effort values to bare and provider-prefixed Grok models, plus xhigh for grok-4.20-multi-agent
  • include LiteLLM's allowed_openai_params=["reasoning_effort"] opt-in when forwarding the field
  • preserve the caller's temperature because xAI documents other incompatible sampling fields, but not temperature
  • use medium with a warning for values outside Grok 4.5's documented effort set

Compatibility

The feature is disabled by default. Grok requests remain unchanged unless an operator explicitly enables enable_grok_reasoning_effort.

xAI's reasoning contract documents low/medium/high for Grok 4.5 and adds xhigh for grok-4.20-multi-agent: https://docs.x.ai/developers/model-capabilities/text/reasoning

Testing

  • focused Grok/GPT-5/OpenRouter reasoning tests: 52 passed
  • full unit suite: 1346 passed, 1 skipped, 1 xfailed
  • new test file passes Ruff and Flake8 (--max-line-length=120)
  • changed-file Ruff/Flake8 results introduce no violations relative to clean upstream main

@github-actions github-actions Bot added the feature 💡 label Jul 18, 2026
@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

PR Summary by Qodo

Forward reasoning_effort to Grok behind opt-in compatibility flag

✨ Enhancement 🧪 Tests ⚙️ Configuration changes 🕐 20-40 Minutes

Grey Divider

AI Description

• Add default-off flag to forward reasoning_effort to Grok models.
• Validate Grok effort values and fall back to medium with warnings.
• Add focused unit tests for Grok reasoning forwarding and temperature preservation.
Diagram

graph TD
  caller["Caller"] --> handler["LiteLLM handler"] --> decide{"Model family?"}
  decide --> gpt5["GPT-5 reasoning"] --> call["LiteLLM acompletion"]
  decide --> grok["Grok reasoning (opt-in)"] --> call
  handler --> cfg["Settings/config"]
  cfg --> gpt5
  cfg --> grok
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Unify under existing support_reasoning_models path
  • ➕ Centralizes reasoning_effort handling in one place.
  • ➕ Reduces special-case branching for specific model families.
  • ➖ Doesn’t naturally cover GPT-5’s temperature-drop behavior (LiteLLM param incompatibility).
  • ➖ Still needs provider-specific allowlists (allowed_openai_params) and per-model validation.
2. Capability-driven provider/model map
  • ➕ Makes per-provider constraints explicit (valid efforts, temperature compatibility, allowlists).
  • ➕ Scales better as more providers add reasoning knobs.
  • ➖ More upfront design/maintenance cost than a targeted compatibility flag.
  • ➖ Risk of over-engineering for a small set of current models.

Recommendation: Current approach is appropriate: it keeps the behavior default-off, limits Grok matching to the model basename, and cleanly separates GPT-5’s stricter sampling-parameter constraints (dropping temperature) from Grok’s documented allowance (preserving temperature). Consider a capability map only if additional provider-specific reasoning controls continue to accumulate.

Files changed (3) +133 / -5

Enhancement (1) +28 / -5
litellm_ai_handler.pyOpt-in Grok reasoning_effort forwarding with model-specific validation +28/-5

Opt-in Grok reasoning_effort forwarding with model-specific validation

• Introduces a shared reasoning_kwargs mechanism and adds an opt-in branch for Grok models (based on basename) to forward reasoning_effort with LiteLLM’s allowed_openai_params allowlist. Keeps temperature for Grok but continues to drop temperature for GPT-5 when reasoning_effort is set, and logs warnings for invalid configured effort values.

pr_agent/algo/ai_handlers/litellm_ai_handler.py

Tests (1) +102 / -0
test_litellm_grok_reasoning_effort.pyAdd unit coverage for Grok reasoning_effort forwarding and edge cases +102/-0

Add unit coverage for Grok reasoning_effort forwarding and edge cases

• Adds async tests verifying opt-in behavior, provider-prefixed model handling, invalid-effort fallback to medium, xhigh support only for grok-4.20-multi-agent, and prevention of overmatching non-Grok basenames.

tests/unittest/test_litellm_grok_reasoning_effort.py

Other (1) +3 / -0
configuration.tomlAdd enable_grok_reasoning_effort compatibility flag (default false) +3/-0

Add enable_grok_reasoning_effort compatibility flag (default false)

• Documents and adds a default-off configuration toggle controlling whether configured reasoning_effort values are forwarded to Grok-family models.

pr_agent/settings/configuration.toml

@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (1) 📜 Skill insights (0)

Grey Divider


Action required

1. Grok reasoning injected broadly 📘 Rule violation ⛨ Security
Description
The new Grok branch injects reasoning_effort/allowed_openai_params based only on the model
basename, so any provider-prefixed model ending with grok-* (including OpenRouter-routed models)
can incorrectly receive Grok-specific kwargs. This risks cross-provider configuration leakage and
can cause unexpected request behavior/failures, including overriding OpenRouter’s separate reasoning
configuration by sourcing from config.reasoning_effort instead of openrouter.reasoning_effort.
Code

pr_agent/algo/ai_handlers/litellm_ai_handler.py[R483-486]

+                grok_model = model.rsplit('/', 1)[-1]
                if model_base.startswith('gpt-5'):
                    # Use configured reasoning_effort or default to MEDIUM
                    config_effort = get_settings().config.reasoning_effort
Evidence
PR Compliance ID 20 requires determining provider identity and only injecting provider-specific
kwargs for the matching provider, but the added logic derives grok_model via `model.rsplit('/',
1)[-1] and applies Grok forwarding whenever that basename starts with grok-`, without verifying
that the provider prefix is actually xAI/Grok. Because of this basename-only check, models like
openrouter/.../grok-* will also match and receive top-level
reasoning_effort/allowed_openai_params; meanwhile, the OpenRouter-specific block configures
reasoning separately through extra_body["reasoning"] using openrouter.reasoning_effort and does
not reference config.reasoning_effort, so enabling the Grok flag globally changes OpenRouter
request kwargs and shifts the configuration source for OpenRouter-routed Grok models.

pr_agent/algo/ai_handlers/litellm_ai_handler.py[483-535]
pr_agent/algo/ai_handlers/litellm_ai_handler.py[437-588]
pr_agent/algo/ai_handlers/litellm_ai_handler.py[625-684]
Best Practice: Learned patterns

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`enable_grok_reasoning_effort` currently injects Grok-specific `reasoning_kwargs` (including `reasoning_effort` and `allowed_openai_params`) whenever the model’s basename starts with `grok-`, regardless of the actual provider indicated by the model prefix. This can leak Grok-only kwargs into non-xAI providers (notably `openrouter/.../grok-*`), altering OpenRouter requests and conflicting with OpenRouter’s dedicated reasoning configuration.

## Issue Context
- Compliance requires computing/using provider identity before injecting provider-specific kwargs, and only applying those kwargs when the resolved provider matches.
- Current Grok detection is basename-based (`model.rsplit('/', 1)[-1]`), so provider-prefixed models ending in `grok-*` also match.
- OpenRouter already configures reasoning via its own block (using `openrouter.reasoning_effort` and `extra_body["reasoning"]`), so adding top-level `reasoning_effort` sourced from `config.reasoning_effort` changes behavior for OpenRouter-routed Grok models.
- Suggested direction: make the Grok condition provider-aware (e.g., skip when `model.startswith("openrouter/")` or reuse an existing `is_openrouter` flag), so OpenRouter-routed Grok models are controlled only by the OpenRouter block.

## Fix Focus Areas
- pr_agent/algo/ai_handlers/litellm_ai_handler.py[450-536]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

2. Grok tests inherit environment 🐞 Bug ☼ Reliability
Description
The new Grok reasoning_effort unit tests instantiate LiteLLMAIHandler without clearing environment
variables that change its __init__ behavior (e.g., AWS_USE_IMDS triggers boto3 credential
resolution). This makes test runtime/behavior dependent on CI or developer-machine environment
state.
Code

tests/unittest/test_litellm_grok_reasoning_effort.py[R35-44]

+async def _run_completion(monkeypatch, model, reasoning_effort="medium", enabled=False):
+    monkeypatch.setattr(litellm_handler, "get_settings", lambda: _settings(reasoning_effort, enabled))
+    with patch(
+        "pr_agent.algo.ai_handlers.litellm_ai_handler.acompletion",
+        new_callable=AsyncMock,
+    ) as completion:
+        completion.return_value = _response()
+        handler = LiteLLMAIHandler()
+        await handler.chat_completion(model=model, system="sys", user="usr")
+        return completion.call_args.kwargs
Evidence
The new tests create LiteLLMAIHandler instances without any env cleanup. LiteLLMAIHandler.__init__
explicitly changes behavior based on env vars like AWS_USE_IMDS and performs boto3 credential
resolution when enabled, so these tests can become environment-dependent.

tests/unittest/test_litellm_grok_reasoning_effort.py[35-45]
pr_agent/algo/ai_handlers/litellm_ai_handler.py[51-97]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The new Grok tests construct `LiteLLMAIHandler()` without clearing env vars that influence initialization paths (notably AWS credential handling). This can cause tests to run slower or behave differently depending on the runner environment.

## Issue Context
`LiteLLMAIHandler.__init__` branches on `os.environ.get("AWS_USE_IMDS", ...)` and, when set, imports boto3 and calls `session.get_credentials()`.

## Fix Focus Areas
- tests/unittest/test_litellm_grok_reasoning_effort.py[35-45]
- pr_agent/algo/ai_handlers/litellm_ai_handler.py[51-97]

### Suggested change
In `_run_completion`, clear the same env vars the existing reasoning_effort tests clear (e.g., `AWS_USE_IMDS`, `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN`, `AWS_REGION_NAME`, `OPENAI_API_KEY`) via `monkeypatch.delenv(..., raising=False)` before constructing `LiteLLMAIHandler()`.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

ⓘ  1 issues published inline · 2 in summary

  • Author self-review: I have reviewed the code review findings, and addressed the relevant ones.

Qodo Logo

Comment on lines +483 to 486
grok_model = model.rsplit('/', 1)[-1]
if model_base.startswith('gpt-5'):
# Use configured reasoning_effort or default to MEDIUM
config_effort = get_settings().config.reasoning_effort

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.

Action required

1. Grok reasoning injected broadly 📘 Rule violation ⛨ Security

The new Grok branch injects reasoning_effort/allowed_openai_params based only on the model
basename, so any provider-prefixed model ending with grok-* (including OpenRouter-routed models)
can incorrectly receive Grok-specific kwargs. This risks cross-provider configuration leakage and
can cause unexpected request behavior/failures, including overriding OpenRouter’s separate reasoning
configuration by sourcing from config.reasoning_effort instead of openrouter.reasoning_effort.
Agent Prompt
## Issue description
`enable_grok_reasoning_effort` currently injects Grok-specific `reasoning_kwargs` (including `reasoning_effort` and `allowed_openai_params`) whenever the model’s basename starts with `grok-`, regardless of the actual provider indicated by the model prefix. This can leak Grok-only kwargs into non-xAI providers (notably `openrouter/.../grok-*`), altering OpenRouter requests and conflicting with OpenRouter’s dedicated reasoning configuration.

## Issue Context
- Compliance requires computing/using provider identity before injecting provider-specific kwargs, and only applying those kwargs when the resolved provider matches.
- Current Grok detection is basename-based (`model.rsplit('/', 1)[-1]`), so provider-prefixed models ending in `grok-*` also match.
- OpenRouter already configures reasoning via its own block (using `openrouter.reasoning_effort` and `extra_body["reasoning"]`), so adding top-level `reasoning_effort` sourced from `config.reasoning_effort` changes behavior for OpenRouter-routed Grok models.
- Suggested direction: make the Grok condition provider-aware (e.g., skip when `model.startswith("openrouter/")` or reuse an existing `is_openrouter` flag), so OpenRouter-routed Grok models are controlled only by the OpenRouter block.

## Fix Focus Areas
- pr_agent/algo/ai_handlers/litellm_ai_handler.py[450-536]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

@IsmaelMartinez IsmaelMartinez left a comment

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.

Changes needed, and an apology first: five weeks with no maintainer reply on this is too long, and that one is ours.

The mechanism and the tests both hold up, but the gate is too broad. With the flag on, openrouter/x-ai/grok-4 picks up reasoning_effort from [config] on top of the extra_body.reasoning the OpenRouter block already set from [openrouter]. Suggestion inline.

allowed_openai_params also pushes the field past litellm's own capability check, so xai/grok-2 and xai/grok-3 receive it too. MAX_TOKENS has no xai/ Grok past 3, so grok-4.5 and grok-4.20-multi-agent raise before a request is built unless custom_model_max_tokens is set. Their entries belong in this PR.

configuration.toml needs a rebase, and CI has not run on this head yet.

Comment on lines +516 to +517
elif grok_model.startswith('grok-') and get_settings().config.get(
"enable_grok_reasoning_effort", False):

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.

grok_model is the basename, so openrouter/x-ai/grok-4 lands here too and gets reasoning_effort from [config] while the OpenRouter block below is already setting extra_body.reasoning from [openrouter].reasoning_effort. is_openrouter is already computed above.

Suggested change
elif grok_model.startswith('grok-') and get_settings().config.get(
"enable_grok_reasoning_effort", False):
elif (grok_model.startswith('grok-') and not is_openrouter
and get_settings().config.get("enable_grok_reasoning_effort", False)):

)
reasoning_kwargs = {
"reasoning_effort": effort,
"allowed_openai_params": ["reasoning_effort"],

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.

On the pinned litellm 1.98 this is doing more than it looks: grok-2 and grok-3 have reasoning_effort dropped without the allowlist and included with it, and those are the only xai/ Grok families MAX_TOKENS covers today. grok-4.5 does not need the allowlist at all; grok-4.20-multi-agent genuinely does. Worth narrowing it to the models that need it, and adding the Grok 4.x MAX_TOKENS entries so the documented models can actually run.

return response


async def _run_completion(monkeypatch, model, reasoning_effort="medium", enabled=False):

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.

Qodo's second finding applies here: test_litellm_reasoning_effort.py deletes AWS_USE_IMDS and the AWS/OPENAI vars before constructing the handler, because __init__ branches on them. Worth matching.

Kyzcreig and others added 2 commits August 30, 2026 07:25
Add opt-in model-supported reasoning_effort forwarding for bare and provider-prefixed Grok models without changing temperature.

Tests: 1346 passed, 1 skipped, 1 xfailed.
…dels

Addresses @IsmaelMartinez's review on The-PR-Agent#2530. All three findings verified against
the code and reproduced before fixing.

1. OpenRouter double-configuration. He wrote: "grok_model is the basename, so
   openrouter/x-ai/grok-4 lands here too and gets reasoning_effort from [config]
   while the OpenRouter block below is already setting extra_body.reasoning from
   [openrouter]." Reproduced exactly -- with the flag on,
   openrouter/x-ai/grok-4.5 came out with BOTH top-level reasoning_effort='high'
   (from [config]) and extra_body.reasoning={'effort':'high'} (from [openrouter]).
   Adopted his inline `not is_openrouter` suggestion; the OpenRouter block is now
   the sole owner of that path.

2. allowed_openai_params too broad. He wrote: "grok-2 and grok-3 have
   reasoning_effort dropped without the allowlist and included with it ...
   grok-4.5 does not need the allowlist at all; grok-4.20-multi-agent genuinely
   does." Confirmed against the pinned litellm: get_supported_openai_params
   reports reasoning_effort for xai/grok-4.5 and xai/grok-4.20-multi-agent but not
   for xai/grok-3. The allowlist is now added only when litellm does not already
   report the param, mirroring how main does it for its own Grok path.

3. MAX_TOKENS entries. Added xai/grok-4.20-multi-agent (main's The-PR-Agent#2871, merged
   today, added the 4.5/4.6 entries but not this one), so the documented
   xhigh-capable model can actually run without custom_model_max_tokens.

Also, and this narrows the PR substantially: main gained native always-on Grok
4.5/4.6 reasoning support in The-PR-Agent#2871 while this sat. The opt-in branch now also
skips any model main already covers via GROK_REASONING_EFFORT_LEVELS, so it no
longer overrides main's clamping. The residual scope is xAI-direct Grok families
main does not cover.

Rebased onto main (a64730a); the configuration.toml conflict he flagged is
resolved (kept main's add_user_to_requests + "max" effort alongside our flag).

Tests: adds the OpenRouter-isolation regression, an allowlist-narrowing test, and
a test that natively-supported models are left to main. Adopts the
_restore_litellm_globals autouse fixture per his third note.
tests/unittest: 2702 passed, 1 pre-existing failure
(TestLiteLLMReasoningEffortGrok::...[grok-4.6-xhigh-False]) that reproduces
identically on pristine upstream/main and is untouched by this branch.

Co-authored-by: IsmaelMartinez <IsmaelMartinez@users.noreply.github.com>
@Kyzcreig
Kyzcreig force-pushed the feature/grok-reasoning-effort branch from 11c7a1b to 7719da2 Compare August 30, 2026 14:32
@qodo-code-review

qodo-code-review Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Code Review by Qodo

Grey Divider

Sorry, something went wrong

We weren't able to complete the code review on our side. Please try again manually by commenting /agentic_review on this PR.

Grey Divider

Qodo Logo

@Kyzcreig

Copy link
Copy Markdown
Contributor Author

@IsmaelMartinez — rebased and all three findings fixed at head 7719da2c. mergeable: MERGEABLE (was CONFLICTING). And no apology needed for the five weeks; the review you eventually gave found more than the delay cost.

1. The OpenRouter double-config — reproduced exactly as you described.

grok_model is the basename, so openrouter/x-ai/grok-4 lands here too and gets reasoning_effort from [config] while the OpenRouter block below is already setting extra_body.reasoning from [openrouter].

Built a probe over the real handler rather than reading the diff, and the doubled request is exactly what came out:

model                       flag=off                          flag=on (before your fix)
openrouter/x-ai/grok-4.5    extra_body.reasoning={'high'}     reasoning_effort='high'
                                                            + extra_body.reasoning={'high'}

Took your inline not is_openrouter suggestion verbatim. Same probe after: the flag=on row is now identical to the flag=off row.

2. allowed_openai_params — you were right, and it was worse than "too broad".

grok-2 and grok-3 have reasoning_effort dropped without the allowlist and included with it ... grok-4.5 does not need the allowlist at all; grok-4.20-multi-agent genuinely does.

Checked each against the pinned litellm's own get_supported_openai_params:

xai/grok-4.5                 reasoning_effort supported: True   -> allowlist unnecessary
xai/grok-4.20-multi-agent    reasoning_effort supported: True   -> also unnecessary on 1.98
xai/grok-3                   reasoning_effort supported: False  -> allowlist was FORCING it

So the unconditional allowlist was pushing the param onto grok-3, which litellm drops deliberately. It's now added only when litellm doesn't already report the param — the same shape main uses for its own Grok path.

3. MAX_TOKENS — added, and the picture changed underneath us.

While this sat, #2871 merged (today) and added native always-on Grok 4.5/4.6 support: GROK_REASONING_EFFORT_LEVELS, _clamp_grok_reasoning_effort, and the xai/grok-4.5 / 4.6 MAX_TOKENS entries you asked for. That absorbs most of what this PR did. Three of my own tests went red on the rebase for exactly that reason — main now handles those models without the flag.

Rather than let this PR fight main, I narrowed it: the opt-in branch now also skips any model main already covers, so it can't override main's clamping. xai/grok-4.20-multi-agent was still missing from MAX_TOKENS after #2871, so that entry is here.

This leaves the PR much smaller than when you reviewed it, and that's worth your explicit call: the residual is an opt-in flag for xAI-direct Grok families that main doesn't natively cover. If you'd rather see Grok models simply added to SUPPORT_REASONING_EFFORT_MODELS / GROK_REASONING_EFFORT_LEVELS as #2871 does — and this flag dropped entirely — say so and I'll close this in favour of that. I don't think the flag is worth carrying on its own if the registry approach covers the models people actually use.

configuration.toml needs a rebase

Done — kept main's add_user_to_requests and the "max" effort value alongside the new flag.

Tests: adds regressions for the OpenRouter isolation, the allowlist narrowing (both directions), and native-model deference; adopts the env/globals fixture per your third comment. tests/unittest: 2702 passed, with one failure — TestLiteLLMReasoningEffortGrok::test_xai_grok_litellm_reasoning_param_support[grok-4.6-xhigh-False] — that I want to flag rather than bury: it reproduces identically on pristine upstream/main, so it's pre-existing and not from this branch, but it is red on main right now and may be worth its own issue.

Credit is in the commit trailer.

import openai
import pytest

import pr_agent.algo.ai_handlers.litellm_ai_handler as litellm_handler
@IsmaelMartinez

Copy link
Copy Markdown
Collaborator

Thanks for the rebase, and for the honest read on scope: I think you called it right. With #2871 in, the registry route covers the models people actually use, so I will close this in favour of that and open the follow-up adding the grok-4.20* and grok-4.3* ids plus their missing MAX_TOKENS entries.

On the failure you flagged, it is not main. test_xai_grok_litellm_reasoning_param_support[grok-4.6-xhigh-False] passes on a64730af with litellm 1.98.0, and fails only on 1.93.0 where xai/grok-4.6 is absent from the bundled cost map. The test is a version canary doing its job, so no issue needed. Same story as the counts on #2531.

@IsmaelMartinez

Copy link
Copy Markdown
Collaborator

Correction on the version I named: it is not specific to 1.93.0. xai/grok-4.6 only enters litellm's bundled cost map at 1.98.0, which I checked on 1.97.0 directly, so any earlier version reds that test. The conclusion is unchanged, it is the pin canary rather than a bug in main.

@IsmaelMartinez

Copy link
Copy Markdown
Collaborator

Closing in favour of the registry route, as agreed. Thanks again for the rebase and for calling the scope honestly; the follow-up will carry the grok-4.20 and 4.3 ids with credit to you.

@IsmaelMartinez

Copy link
Copy Markdown
Collaborator

Follow-up is up as #2890, with you as co-author. One narrowing worth flagging: I dropped the grok-4.20 ids from it. xai/grok-4.20-multi-agent is absent from litellm 1.98.0's bundled cost map and only appears in the map litellm fetches at import, so its capability answer depends on whether the process reached the network. Your PR's flagship model would have been the fragile one. 4.3 is clean, so that is what went in.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants