Repository navigation
Add support for mistral AI provider - #796
NeroReflex wants to merge 9 commits into
Conversation
Sashiko reviewCommit 1/8 —
|
|
Thanks for the PR! Please, rebase and address Sashiko's comments. Thanks |
|
Sure thing! Together with friend of mine we identified a problem with caching I am solving. Will jump on findings after, thank you! |
Sashiko review — v2Commit 1/9 —
|
Add provider = "mistral" for the Mistral chat completions API and Mistral-shaped gateways, keyed off MISTRAL_API_KEY (or LLM_API_KEY). The API is close to the OpenAI one but not close enough for the generic compatible client: replies carry the assistant text as an array of typed content blocks, where the chain of thought arrives as thinking blocks next to text blocks instead of a reasoning_content string. The provider parses every reply shape: plain strings, typed content blocks, null, and anything it does not recognize, which it drops instead of failing the reply. Thinking blocks map to the response thought, and the chain of thought stays in the conversation across tool rounds without per-provider settings. Requests use plain string content for every role, tool results travel as role "tool" with tool_call_id, and JSON mode reuses the json_object response_format with a "Respond in JSON format." nudge appended when a prompt does not name JSON. reasoning_effort follows a stage's own request and falls back to [ai.mistral] effort. The context window defaults to 1M tokens for the hosted zai-glm-*/glm-* models and 128k otherwise; 429, auth failures, and 5xx classify through the shared retry machinery. The cache identity includes max_tokens, base_url, and the configured effort: a call that hit the output cap comes back empty with finish_reason "length", and raising the cap has to miss that entry rather than replay it. [ai.mistral] accepts base_url, max_tokens, context_window_size, and effort; base_url accepts the API host, any .../v1 root, or the full chat completions URL and rejects every other path at startup. Signed-off-by: Denis Benato <denis.benato@linux.dev> # Conflicts: # docs/llm-providers.md
Sashiko review — v3Commit 3/9 —
|
A newer clippy flags the hand-rolled comparators and the loop-around- let-else pop patterns that this tree used so far, and make check-pr builds with -D warnings fail on them. Sorting by key states the ordering directly, and while let with a block scrutinee is the pop loop clippy asks for; on edition 2024 the block drops its lock guard before the body runs, so the queue is never held across a review job. Signed-off-by: Denis Benato <denis.benato@linux.dev>
The stage-1 self-review of a48379e flagged that thinking blocks were parsed out of replies but never re-sent, contradicting the documented behavior. An assistant turn that carries a kept chain of thought now re-emits it as a thinking content block ahead of the answer text; the Mistral chat completions schema accepts that shape for request assistant messages. Also from the review: - refuse an API key that cannot form a valid HTTP header value at construction instead of silently degrading to unauthenticated requests; a missing key still builds for keyless gateways but logs a warning naming MISTRAL_API_KEY - attribute the post_request error and rate-limit log lines to the patch and stage via the shared log prefix - cover the HTTP failure paths (429 with and without Retry-After, 401, 5xx, malformed 2xx body, transport failure) with stub-server tests Fixes: a48379e ("ai: add a native Mistral provider") Signed-off-by: Denis Benato <denis.benato@linux.dev>
The stage-1 self-review of the chain-of-thought fix flagged two leftovers. The Mistral transport and body-read failures log plain Display strings for the underlying reqwest error, dropping the cause chain that the Claude and Gemini providers preserve with anyhow alternate formatting; both sites now match that convention. The round-trip test now also sends the reply back as a follow-up turn and asserts the captured request re-emits the chain of thought as thinking blocks shaped exactly like the blocks the API emits in replies. The request-side shape is additionally verified against the live chat completions endpoint: an assistant message carrying a thinking block plus a text block is accepted with HTTP 200 by both mistral-small-latest and magistral-small-latest. Fixes: a48379e ("ai: add a native Mistral provider") Signed-off-by: Denis Benato <denis.benato@linux.dev>
The final stage-1 self-review pass over the two provider commits flagged three findings and two provider concerns; all are addressed here. - A MISTRAL_API_KEY set to the empty string shadowed a valid LLM_API_KEY and the new warning named the wrong cause; an empty value now falls through to the shared key and the warning says "not set or is empty". - Builder and redirect transport failures are permanent, so they now fail fast as a fatal PermanentError instead of climbing the backoff ladder like retryable failures; connection refused and other retryable causes stay transient. - The tool-round wire shape (block-form content next to tool_calls on one assistant turn) is now pinned by a unit test, and the per-response token log line carries the shared patch/stage attribution prefix. - The transport-failure test connects to loopback port 1 instead of racing concurrent binds for a dropped ephemeral port. The uncapped response body read matches the openai and gemini providers and is left for a cross-provider follow-up; the GitLab webhook replay-timestamp concern is a pre-existing forge issue outside this series. Fixes: a48379e ("ai: add a native Mistral provider") Signed-off-by: Denis Benato <denis.benato@linux.dev>
The Mistral client resolved its API key inline in the constructor, and two behaviors existed only as untested code paths: a MISTRAL_API_KEY set to the empty string must fall through to LLM_API_KEY instead of shadowing it, and a self-redirecting endpoint must exhaust reqwest's redirect budget into the permanent fast-fail arm of post_request instead of climbing the backoff ladder. Key resolution moves into a pure resolve_api_key helper whose rules a unit test pins, keeping process-global environment mutation out of the parallel suite, and the redirect loop is exercised end to end against a self-redirecting stub server. The per-request info log line now carries the shared patch/stage attribution prefix, matching the response lines. Signed-off-by: Denis Benato <denis.benato@linux.dev>
Stage outputs from weaker models fail strict JSON parsing on unescaped double quotes inside string values (serde reports 'expected , or ]' right after an inner quote ends the string early) and on trailing commas. Three validation retries cannot fix what the model keeps rewriting the same way, so a parallel stage dies under BestEffort and its findings are lost. Add utils::repair_json_candidates: quotes are escaped as content unless the next non-whitespace character is a structural token, and commas directly before } or ] are dropped. A quote followed by a comma or colon is ambiguous - it separates real elements but also appears inside quoted prose - and no local rule tells them apart, so two readings are produced. In the prose reading the first syntax error localizes the derailment and comma- or colon-preceded quotes at or after it are escaped as content, while in the structural reading every such quote terminates its string and keeps the fields after it intact; the prose reading can swallow those fields into the derailed value, so the structural reading is preferred whenever it strictly parses and the prose reading covers the inputs where terminating quotes cannot parse at all, such as prose that embeds key-colon pairs. parse_json_from_text applies the variants only after the strict parse, the raw text, and the brace-candidate extraction all failed, and only accepts a variant when a strict parse of it succeeds, so an unrepaired or still-broken output surfaces the original error instead of silently misreading the input. The repair runs on the raw text and clean_json_string escapes control characters on each repaired variant: the cleaner tracks string state by quote count, so an odd unescaped quote would flip it and turn the structural newlines between fields into literal \n sequences outside strings that survive no repair. Signed-off-by: Denis Benato <denis.benato@linux.dev>
A parallel analysis stage that emits a dismissed_concerns entry without description or reasoning fails validate_concerns_output, and after three validation attempts the whole stage dies under BestEffort, losing every real concern it reported. Seen reviewing HID: asus gamepad configuration with a flash model at low effort: the model kept emitting the same stub until the retry budget ran out and the resources and hardware stages failed. A contentless dismissal asserts nothing about why the candidate concern fails to apply, so dropping it is lossless: downstream stages keep treating the candidate as unresolved, which is the conservative outcome. Skip such entries in the four per-project validators and filter them in the shared reducer so they never reach review state or threads. Dismissals that carry content are still required to prove themselves with verbatim locations. Fixes: 3c83b32 ("workflows: require concrete code proof for dismissed concerns") Signed-off-by: Denis Benato <denis.benato@linux.dev>
Mistral chat completions route prompt caching by a client-chosen prompt_cache_key: requests carrying the same key land where their shared prefix is already cached, and the cached prefix bills at 10% of the input token price. The Mistral provider never sent one, so every tool round of a review session re-billed the whole conversation prefix at full input price, and costs exploded relative to the sibling providers, whose prompt caching defaults on. The key is a SHA-256 digest of the model, the system prompt, and the tool definitions: the part of the prompt every tool round of a session repeats and every session of a review stage repeats across patchsets. Patch text and kept chains of thought stay out of it, so keys do not churn per round, and the value is a digest, so no prompt content travels inside it. The key is derived at translate time, so the local response cache key and the cache identity are untouched, matching how Claude keeps prompt_caching out of its identity. Caching defaults on like the sibling providers; [ai.mistral] prompt_caching = false drops the field from the wire entirely for gateways that reject it. MistralSettings loses its derived Default so a constructed settings value cannot quietly disagree with the serde default on the new knob, the way Gemini keeps its explicit default consistent on both paths. Fixes: a48379e ("ai: add a native Mistral provider") Signed-off-by: Denis Benato <denis.benato@linux.dev>
Sashiko review — v4Commit 1/9 —
|
|
Please, rebase and address sashiko's comments. Thanks |
Hi all,
I borrowed an API key for Mistral vibecode plan from friend of mine at OGC to review a large driver.
I have set out my glm to fix the issue about theirs response being incompatible with the format expected by the openai-compatible provider and now it works.
WARNING: Everything in here is fully AI written and only runtime tested (it did in fact review my driver and the review found real issues); that is I haven't looked at a single line with the intention of checking it beside making sure it didn't made others provided stopped working and checking for things too stupid to be proposed... so don't merge it.
If you say this is something you consider adding (done the right way) and you tell me what is the expectation to add support for this provider I will be available for implementing this the proper way.
Thank you!