Skip to content

fix(model_metadata): add xAI Grok context length fallbacks#7039

Closed
Julientalbot wants to merge 1 commit into
NousResearch:mainfrom
Julientalbot:fix/xai-grok-context-length-fallbacks
Closed

fix(model_metadata): add xAI Grok context length fallbacks#7039
Julientalbot wants to merge 1 commit into
NousResearch:mainfrom
Julientalbot:fix/xai-grok-context-length-fallbacks

Conversation

@Julientalbot

Copy link
Copy Markdown
Contributor

Problem

xAI's /v1/models endpoint does not return context_length metadata for any Grok model. When a user configures a custom provider pointing at https://api.x.ai/v1, Hermes falls through every detection step in get_model_context_length() and lands on the 128k probe-down default:

INFO agent.model_metadata: Could not detect context length for model
'grok-4.20-0309-reasoning' at https://api.x.ai/v1 — defaulting to
128,000 tokens (probe-down). Set model.context_length in config.yaml
to override.

This forces every xAI user to manually override model.context_length in config.yaml or lose 93% of the usable window (128k out of 2M for the Grok 4.x family).

Solution

Add DEFAULT_CONTEXT_LENGTHS entries for the Grok family so the hardcoded fallback lookup resolves to the correct value. This matches the existing pattern used for Claude, Gemma, MiniMax, Kimi, and GLM entries in the same dict.

Values sourced from models.dev (2026-04) and cross-checked against the live xAI /v1/models listing:

Entry Context Matches
grok-4.20 2,000,000 grok-4.20-0309-reasoning, -non-reasoning, -multi-agent-0309
grok-4-1-fast 2,000,000 grok-4-1-fast-reasoning, -non-reasoning
grok-4-fast 2,000,000 grok-4-fast-reasoning, -non-reasoning
grok-4 256,000 grok-4, grok-4-0709
grok-code-fast 256,000 grok-code-fast-1
grok-3 131,072 grok-3, grok-3-mini, grok-3-fast, grok-3-mini-fast
grok-2-vision 8,192 grok-2-vision, -1212, -latest
grok-2 131,072 grok-2, -1212, -latest
grok 131,072 catch-all (grok-beta, unknown grok-*)

Keys are ordered longest-first so specific variants match before the catch-all, consistent with how the dict is consumed in get_model_context_length() (sorted(..., key=len, reverse=True)).

Testing

Two new tests in TestDefaultContextLengths:

  • test_grok_models_context_lengths — pins the raw dict values
  • test_grok_substring_matching — verifies the full get_model_context_length() lookup path resolves every public Grok model ID to the correct fallback (17 cases)
$ pytest tests/agent/test_model_metadata.py
77 passed in 0.60s

Impact

  • Zero config required for users pointing at https://api.x.ai/v1 — they get the real context window automatically
  • No regression: fallbacks only fire when models.dev + OpenRouter + Anthropic catalogs all miss (which they do for direct xAI)
  • Complements the existing xAI integration (x-grok-conv-id prompt caching, Grok in TOOL_USE_ENFORCEMENT_MODELS)
  • No behavior change for other providers

xAI /v1/models does not return context_length metadata, so Hermes
probes down to the 128k default whenever a user configures a custom
provider pointing at https://api.x.ai/v1. This forces every xAI user
to manually override model.context_length in config.yaml (2M for
Grok 4.20 / 4.1-fast / 4-fast) or lose most of the usable context
window.

Add DEFAULT_CONTEXT_LENGTHS entries for the Grok family so the
fallback lookup returns the correct value via substring matching.
Values sourced from models.dev (2026-04) and cross-checked against
the xAI /v1/models listing:

  - grok-4.20-*          2,000,000  (reasoning, non-reasoning, multi-agent)
  - grok-4-1-fast-*      2,000,000
  - grok-4-fast-*        2,000,000
  - grok-4 / grok-4-0709   256,000
  - grok-code-fast-1       256,000
  - grok-3*                131,072
  - grok-2 / latest        131,072
  - grok-2-vision*           8,192
  - grok (catch-all)       131,072

Keys are ordered longest-first so that specific variants match before
the catch-all, consistent with the existing Claude/Gemma/MiniMax entries.

Add TestDefaultContextLengths.test_grok_models_context_lengths and
test_grok_substring_matching to pin the values and verify the full
lookup path. All 77 tests in test_model_metadata.py pass.
Julientalbot pushed a commit to Julientalbot/hermes-agent that referenced this pull request Apr 10, 2026
xAI is listed in models.dev (`id: xai`, `env: [XAI_API_KEY]`) but without
an `api` field, so `get_provider("xai")` returned a ProviderDef with
an empty base_url. Users had to configure xAI via `provider: custom`
and manually set `base_url: https://api.x.ai/v1`, losing the ergonomics
of a first-class provider (no `hermes model --provider xai`, no
auto-detection from `XAI_API_KEY`, no label, etc.).

Add xAI as a native api_key provider alongside zai, kimi-coding, minimax,
deepseek, and friends:

- `hermes_cli/auth.py` — register PROVIDER_REGISTRY["xai"] with
  inference_base_url=https://api.x.ai/v1, api_key_env_vars=(XAI_API_KEY,),
  base_url_env_var=XAI_BASE_URL.
- `hermes_cli/providers.py` — add HERMES_OVERLAYS["xai"] with
  base_url_override, register `x-ai` and `x.ai` as aliases, and add
  "xAI" to the LABELS dict.
- `hermes_cli/models.py` — populate _PROVIDER_MODELS["xai"] with the
  11 public Grok text models (grok-4.20-*, grok-4-1-fast-*, grok-4-fast-*,
  grok-4, grok-4-0709, grok-code-fast-1, grok-3, grok-3-mini) so that
  `hermes model --provider xai` and `curated_models_for_provider("xai")`
  return a usable catalog.
- `agent/model_metadata.py` — add `api.x.ai` to _URL_TO_PROVIDER so that
  users who keep the legacy `provider: custom` + `base_url: https://api.x.ai/v1`
  configuration still get correct context-length resolution via models.dev
  (`_infer_provider_from_url` resolves to "xai" and lookup_models_dev_context
  returns the real 2M/256k/131k values per model).
- Tests: add `xai` to the existing TestProviderRegistry.test_provider_registered
  parametrize, and add a dedicated test_xai_env_vars assertion pinning
  the env var names and default base URL.

After this change, users on xAI direct can configure:

  model:
    default: grok-4.20-0309-reasoning
    provider: xai

instead of the current workaround:

  model:
    default: grok-4.20-0309-reasoning
    provider: custom
    base_url: https://api.x.ai/v1

Auto-detection from XAI_API_KEY, `hermes model` catalog listing, and
credential-pool integration all work as they do for the other api_key
providers. Complements the existing xAI integration (`x-grok-conv-id`
prompt caching, `"grok"` in TOOL_USE_ENFORCEMENT_MODELS) and
the context-length fallbacks in NousResearch#7039. Supersedes the earlier draft
PR NousResearch#6238 which proposed a narrower and incomplete fix.

21/21 tests pass on TestProviderRegistry.
Julientalbot pushed a commit to Julientalbot/hermes-agent that referenced this pull request Apr 10, 2026
The auxiliary client resolution chain (compression, session_search,
vision, web_extract, etc.) had no direct xAI support. Users with
XAI_API_KEY had to rely on either the main provider fallback
(only if they were also on xAI as main) or routing through OpenRouter,
which defeats the purpose of using xAI direct for cheap/fast side tasks.

In particular, the vision auto-detection order was limited to OpenRouter
and Nous, meaning users with both XAI_API_KEY and OPENROUTER_API_KEY
saw every vision analysis routed through OpenRouter even if their main
provider was xai — burning OpenRouter credits and adding latency while
ignoring Grok 4's native vision support.

Add xAI as a first-class auxiliary backend:

- `_try_xai()` — new helper following the same pattern as `_try_openrouter()`
  and `_try_nous()`. Reads the credential pool first, then falls back to
  `XAI_API_KEY`. Returns a default model that is both vision-capable and
  cheap: `grok-4-1-fast-non-reasoning` (text+image input, fast, ~$0.20/$0.50
  per M tokens, no reasoning overhead — ideal for side tasks).

- `_XAI_DEFAULT_BASE_URL` and `_XAI_AUX_MODEL` constants next to the
  existing `_NOUS_*` and `_ANTHROPIC_*` constants.

- `_PROVIDER_ALIASES` gains `x-ai` and `x.ai` -> `xai` so users can
  spell the provider any of the three common ways.

- `_API_KEY_PROVIDER_AUX_MODELS["xai"] = "grok-4-1-fast-non-reasoning"`
  so the api-key provider fallback path picks the same default.

- `resolve_provider_client("xai")` gets an explicit case so text
  auxiliary tasks with `provider: xai` work without depending on
  the PROVIDER_REGISTRY lookup (PR NousResearch#7050 adds the registry entry too,
  but this PR stands alone).

- `_VISION_AUTO_PROVIDER_ORDER` gains `"xai"` at the end so users
  without OpenRouter or Nous get xAI vision automatically. Back-compat
  preserved for users who have OpenRouter — they keep the current behavior.

- `_resolve_strict_vision_backend("xai")` gets the matching case so
  explicit `auxiliary.vision.provider: xai` in config.yaml resolves to
  the xAI backend (no silent OpenRouter override).

Tests (4 new):

- test_explicit_xai — resolve_provider_client("xai") picks up
  XAI_API_KEY and returns the default aux model.
- test_explicit_xai_alias_x_ai — the x-ai alias normalises to xai.
- test_vision_uses_xai_when_no_openrouter_no_nous — vision auto chain
  falls back to xAI when nothing else is available.
- test_vision_forced_xai_uses_xai_backend — explicit config override
  routes vision to xAI even when OpenRouter is available. Verifies the
  api.x.ai base URL is used (not OpenRouter).

100/100 tests pass on tests/agent/test_auxiliary_client.py.

Complements the existing xAI integration (x-grok-conv-id prompt caching,
"grok" in TOOL_USE_ENFORCEMENT_MODELS) and the native provider
registration in NousResearch#7050 / context length fallbacks in NousResearch#7039.
@teknium1

Copy link
Copy Markdown
Contributor

Merged via #7093 — your commit was cherry-picked onto current main with your authorship preserved in git log. Thanks for the thorough PR!

Note: xAI is also working on a PR to add themselves as a first-class native provider, which will complement these fallbacks nicely.

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.

3 participants