From 67b48e86374f1f7f40b84c4593dc02e2895aa071 Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 27 Nov 2026 18:34:13 -0600 Subject: [PATCH 1/3] feat(assistant): add Mistral provider with tool-call compatibility --- README.md | 2 +- apps/rustgis-cli/src/main.rs | 2 +- crates/assistant/src/provider.rs | 94 +++++++++++++++++++++++++++++--- crates/assistant/src/tests.rs | 77 ++++++++++++++++++++++++++ docs/cli.md | 2 +- docs/user-guide/assistant.md | 6 +- 6 files changed, 171 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index e49bfbf95c..8624df3437 100644 --- a/README.md +++ b/README.md @@ -114,7 +114,7 @@ Every screenshot is RustGIS itself, rendered offscreen by `cargo run -p rustgis- | **Imagery** | Ortho and reality mapping, pixel classification (k-means, minimum distance, a trainable neural network), mensuration, hosted imagery tiles | | **Layouts and reports** | Page layouts with map frames, legends, scale bars, grids, bar and column charts and map series; publication sheets and figures in one command, format panes, guides, snapping and element locks; reports with groups, statistics, charts and subreports; vector PDF and SVG, and GeoPDF with [supported map frames](docs/user-guide/layouts.md#layouts) georeferenced; presentations (HTML slideshow, PDF); notebooks (Jupyter in and out) | | **Sharing** | PNG export at up to 600 DPI; PDF; web map pages, OGC API Features collections, MapLibre styles, glTF and STL scenes, vector and raster PMTiles, the map view as a GeoTIFF placed on the ground (desktop), locators; the web app embedded in a page (`?embed`); project, map and mobile map packages; offline areas with sync | -| **AI Assistant** | Ask about your data or tell the map what to do in plain language, attaching pictures and letting it look at the map and layouts, with Anthropic, OpenAI (a key, or your ChatGPT plan by signing in on the desktop or command line), Gemini, OpenRouter and other gateways, Ollama or any OpenAI-compatible model; also `rustgis-cli ask`, and an [MCP server](docs/mcp.md) (`rustgis-cli mcp`) for Claude Code, Cursor, VS Code and other agents; skills; on the desktop, agents such as Claude Code and Codex started from the app, and external AI clients driving the open app; keys optionally remembered in the system keychain on the desktop (in the web app, unencrypted in the browser's storage) | +| **AI Assistant** | Ask about your data or tell the map what to do in plain language, attaching pictures and letting it look at the map and layouts, with Anthropic, OpenAI (a key, or your ChatGPT plan by signing in on the desktop or command line), Gemini, Mistral, OpenRouter and other gateways, Ollama or any OpenAI-compatible model; also `rustgis-cli ask`, and an [MCP server](docs/mcp.md) (`rustgis-cli mcp`) for Claude Code, Cursor, VS Code and other agents; skills; on the desktop, agents such as Claude Code and Codex started from the app, and external AI clients driving the open app; keys optionally remembered in the system keychain on the desktop (in the web app, unencrypted in the browser's storage) | | **Plugins** | Sandboxed WebAssembly [plugins](docs/plugins.md) add commands, tools and ribbon tabs; install them from [plugins.rustgis.app](https://plugins.rustgis.app) on the desktop, command line and web. Process plugins (desktop and command line) run as programs (with Python environments RustGIS makes), in the background or for the whole session; panels offer trees, dropdowns, date pickers and sliders | | **Python** | The [`rustgis` package](docs/python.md) on PyPI: the engine in-process, `rustgis.Map` in Jupyter and `rustgis.qt.MapWidget` in Qt applications | | **Interface** | Layers, Browser and Data Sources panes as tabs, command search (Ctrl+K), keyboard shortcuts, dark mode, custom themes (desktop) and an interface scale, a customizable ribbon and Quick Access Toolbar, linked side-by-side maps, a History pane of tool runs and the session log, autosave and crash recovery (desktop), Check for Updates (desktop), 22 languages | diff --git a/apps/rustgis-cli/src/main.rs b/apps/rustgis-cli/src/main.rs index e96873c587..db4a0c7f57 100644 --- a/apps/rustgis-cli/src/main.rs +++ b/apps/rustgis-cli/src/main.rs @@ -13,7 +13,7 @@ //! rustgis-cli run … --strict [--allow dropped.ring] # exit 3 when a command loses data (see the guide's loss codes) //! rustgis-cli run … --threads 4 # the most threads one piece of work uses (default: the cores, up to 16) //! rustgis-cli ask [--sample | --project p.rgis | --data f.geojson …] "Which cities have over 10 million people?" \ -//! [--provider anthropic|openai|chatgpt|gemini|openrouter|ollama|custom|requesty|trustedrouter|opper] [--model M] [--base-url URL] [--yes] [--save out.rgis] [--trace log.txt] +//! [--provider anthropic|openai|chatgpt|gemini|openrouter|ollama|custom|requesty|trustedrouter|opper|mistral] [--model M] [--base-url URL] [--yes] [--save out.rgis] [--trace log.txt] //! rustgis-cli ask --sample "Style the countries like this map" --image reference.png # pictures go with the request (up to 4) //! rustgis-cli ask --models [--provider P] # list the provider's models //! rustgis-cli ask --accounts | --account CLIENT_ID # list or select a saved registration diff --git a/crates/assistant/src/provider.rs b/crates/assistant/src/provider.rs index 0a701c07bd..9500a700a0 100644 --- a/crates/assistant/src/provider.rs +++ b/crates/assistant/src/provider.rs @@ -179,6 +179,20 @@ pub const PRESETS: &[Preset] = &[ key_url: "https://platform.opper.ai", login: false, }, + Preset { + id: "mistral", + description: "Mistral AI's own API, from France. Paid API requests aren't used for training by default; on a free account, turn training off under Privacy in the admin panel. Labs and Preview models may train regardless of that setting.", + label: "Mistral", + api: Api::OpenAi, + base_url: "https://api.mistral.ai/v1", + // Small 4 is generally available; Large 4 is a preview with different training terms. + model: "mistral-small-2603", + key_env: &["MISTRAL_API_KEY"], + url_env: "", + keyless: false, + key_url: "https://console.mistral.ai/api-keys", + login: false, + }, ]; /// The preset with this id. @@ -879,12 +893,25 @@ fn stream_ended(api: Api, text: &str, events: &[Value]) -> bool { /// Chat Completions chunks: content and reasoning deltas, and calls whose arguments come in /// pieces, by index. fn openai_assembled(events: &[Value]) -> Value { - let (mut content, mut reasoning, mut finish) = (String::new(), String::new(), Value::Null); + let (mut content, mut reasoning, mut finish) = (Value::Null, String::new(), Value::Null); let mut calls: Vec<(String, String, String)> = Vec::new(); for e in events { for choice in e.get("choices").and_then(Value::as_array).into_iter().flatten() { let delta = choice.get("delta").unwrap_or(&Value::Null); - content.push_str(delta.get("content").and_then(Value::as_str).unwrap_or("")); + if let Some(next) = delta.get("content").filter(|v| !v.is_null()) { + match (&mut content, next) { + (Value::String(text), Value::String(more)) => text.push_str(more), + (Value::Array(parts), Value::Array(more)) => parts.extend(more.iter().cloned()), + (Value::Array(parts), Value::String(text)) => parts.push(json!({"type":"text", "text":text})), + (Value::String(text), Value::Array(parts)) => { + let mut all = vec![json!({"type":"text", "text":text})]; + all.extend(parts.iter().cloned()); + content = json!(all); + } + (Value::Null, Value::String(_) | Value::Array(_)) => content = next.clone(), + _ => {} + } + } reasoning.push_str(delta.get("reasoning_content").and_then(Value::as_str).unwrap_or("")); for tc in delta.get("tool_calls").and_then(Value::as_array).into_iter().flatten() { let id = tc.get("id").and_then(Value::as_str).filter(|id| !id.is_empty()); @@ -917,7 +944,10 @@ fn openai_assembled(events: &[Value]) -> Value { } } } - let mut message = json!({"role": "assistant", "content": if content.is_empty() { Value::Null } else { json!(content) }}); + if content.as_str() == Some("") { + content = Value::Null; + } + let mut message = json!({"role": "assistant", "content": content}); // Slots no piece named (a stray index) are no call. calls.retain(|c| !c.1.is_empty()); if !calls.is_empty() { @@ -1077,7 +1107,7 @@ impl StreamPreview { let s = |p: &str| v.pointer(p).and_then(Value::as_str).unwrap_or("").to_string(); match self.api { Api::Responses if v.get("type").and_then(Value::as_str) == Some("response.output_text.delta") => s("/delta"), - Api::OpenAi => s("/choices/0/delta/content"), + Api::OpenAi => openai_content_text(v.pointer("/choices/0/delta/content")), Api::Anthropic if s("/delta/type") == "text_delta" => s("/delta/text"), Api::Gemini => v .pointer("/candidates/0/content/parts") @@ -1122,7 +1152,7 @@ fn header(k: &str, v: &str) -> (String, String) { // --------------------------------------------------------------------------------------------- // OpenAI Chat Completions -/// Builds the OpenAI-shaped request; the OpenRouter privacy filter travels with every turn. +/// Builds streamed Chat Completions with OpenRouter privacy filtering and Mistral call identifiers. fn openai_request(cfg: &Config, system: &str, turns: &[Turn], tools: &[ToolDef]) -> HttpRequest { let mut messages = vec![json!({"role": "system", "content": system})]; for t in turns { @@ -1134,7 +1164,16 @@ fn openai_request(cfg: &Config, system: &str, turns: &[Turn], tools: &[ToolDef]) |t| json!({"type": "text", "text": t}), |p| json!({"type": "image_url", "image_url": {"url": p.data_url()}}), )})), - Turn::Assistant { native: Some((Api::OpenAi, m)), .. } => messages.push(m.clone()), + Turn::Assistant { native: Some((Api::OpenAi, m)), .. } => { + let mut message = m.clone(); + // Mistral thinking/signature blocks are not valid assistant content for other + // compatible APIs. Keep the original turn; send only its visible text there. + if cfg.provider != "mistral" && message.get("content").is_some_and(Value::is_array) { + let text = openai_content_text(message.get("content")); + message["content"] = if text.is_empty() { Value::Null } else { json!(text) }; + } + messages.push(message); + } Turn::Assistant { text, calls, .. } => { let mut m = json!({"role": "assistant", "content": if text.is_empty() { Value::Null } else { json!(text) }}); if !calls.is_empty() { @@ -1153,6 +1192,9 @@ fn openai_request(cfg: &Config, system: &str, turns: &[Turn], tools: &[ToolDef]) } } } + if cfg.provider == "mistral" { + mistral_call_ids(&mut messages); + } let tools: Vec = tools .iter() .map(|t| json!({"type": "function", "function": {"name": t.name, "description": t.description, "parameters": t.schema}})) @@ -1183,6 +1225,29 @@ pub fn refuses_reasoning_with_tools(e: &Error) -> bool { e.status == Some(400) && (e.param.as_deref() == Some("reasoning_effort") || e.detail.to_lowercase().contains("reasoning_effort")) } +/// Mistral requires nine alphanumeric characters for call ids. Rewrite both sides only on the +/// outgoing copy, including native messages from another OpenAI-compatible provider. Picture +/// captions keep original ids as provenance; API call/result references use the mapped ids. Ordinals +/// avoid truncation/hash collisions; a request cannot hold 16^9 distinct calls in memory. +/// Format requirement: . +fn mistral_call_ids(messages: &mut [Value]) { + let mut ids = std::collections::BTreeMap::::new(); + for message in messages { + for call in message.get_mut("tool_calls").and_then(Value::as_array_mut).into_iter().flatten() { + if let Some(id) = call.get_mut("id").filter(|id| id.is_string()) { + let next = format!("{:09x}", ids.len()); + let mapped = ids.entry(id.as_str().unwrap_or_default().to_string()).or_insert(next); + *id = json!(mapped); + } + } + if let Some(id) = message.get_mut("tool_call_id").filter(|id| id.is_string()) { + let next = format!("{:09x}", ids.len()); + let mapped = ids.entry(id.as_str().unwrap_or_default().to_string()).or_insert(next); + *id = json!(mapped); + } + } +} + /// Whether the provider refused a request for the images in it (a model or server that doesn't /// read them). Asked only of a request that carried images. The error names images as a word /// (not "vision" in "revision") and says they aren't taken: not supported, or no image input @@ -1216,10 +1281,25 @@ pub fn refuses_images(e: &Error) -> bool { matches!(e.status, Some(400 | 404 | 415 | 422 | 500)) && names_images && refused && !about_one_image } +/// Visible text from Chat Completions string content or typed blocks. Thinking/signatures stay +/// in the native message for replay; they never become the displayed answer or stream preview. +fn openai_content_text(content: Option<&Value>) -> String { + match content { + Some(Value::String(text)) => text.clone(), + Some(Value::Array(parts)) => parts + .iter() + .filter(|p| p.get("type").and_then(Value::as_str) == Some("text")) + .filter_map(|p| p.get("text").and_then(Value::as_str)) + .collect(), + _ => String::new(), + } +} + +/// Reads Chat Completions, retaining native typed content for the next request. fn openai_reply(v: &Value) -> Result { let choice = v.get("choices").and_then(|c| c.get(0)).ok_or("the reply has no choices")?; let msg = choice.get("message").ok_or("the reply has no message")?; - let text = msg.get("content").and_then(Value::as_str).unwrap_or("").to_string(); + let text = openai_content_text(msg.get("content")); let calls = msg .get("tool_calls") .and_then(Value::as_array) diff --git a/crates/assistant/src/tests.rs b/crates/assistant/src/tests.rs index 22676c9263..a7fd5f6f94 100644 --- a/crates/assistant/src/tests.rs +++ b/crates/assistant/src/tests.rs @@ -5457,3 +5457,80 @@ fn openrouter_data_policy_refusal_names_the_privacy_checkbox() { assert!(matches!(a.receive(generation, Ok(response), &mut session), Step::Done)); assert!(a.transcript.iter().any(|e| matches!(e, Entry::Note(n) if n.template.contains("Check Private routing")))); } + +#[test] +fn mistral_rewrites_native_and_cross_provider_tool_call_ids_without_collisions() { + let turns = vec![ + Turn::User("hello".into(), vec![]), + Turn::Assistant { + text: String::new(), + calls: vec![], + native: Some(( + Api::OpenAi, + json!({ + "role":"assistant", "content":null, "tool_calls":[ + {"id":"call_from_another_provider", "type":"function", "function":{"name":"map_zoom", "arguments":"{}"}}, + {"id":"000000000", "type":"function", "function":{"name":"map_zoom", "arguments":"{}"}} + ] + }), + )), + }, + Turn::Results(vec![ + ToolResult { + id: "call_from_another_provider".into(), + name: "map_zoom".into(), + content: "done".into(), + error: false, + images: vec![], + }, + ToolResult { id: "000000000".into(), name: "map_zoom".into(), content: "done".into(), error: false, images: vec![] }, + ]), + ]; + let request = chat_request(&cfg("mistral"), "system", &turns, &[]); + let body: Value = serde_json::from_str(&request.body.unwrap()).unwrap(); + assert_eq!(request.url, "https://api.mistral.ai/v1/chat/completions"); + assert_eq!(body["messages"][2]["tool_calls"][0]["id"], "000000000"); + assert_eq!(body["messages"][2]["tool_calls"][1]["id"], "000000001"); + assert_eq!(body["messages"][3]["tool_call_id"], "000000000"); + assert_eq!(body["messages"][4]["tool_call_id"], "000000001"); + let original: Value = serde_json::from_str(&chat_request(&cfg("openai"), "system", &turns, &[]).body.unwrap()).unwrap(); + assert_eq!(original["messages"][2]["tool_calls"][0]["id"], "call_from_another_provider"); +} + +#[test] +fn mistral_lists_models_with_a_bearer_key() { + let req = models_request(&cfg("mistral")); + assert_eq!(req.url, "https://api.mistral.ai/v1/models"); + assert!(req.headers.contains(&("Authorization".into(), "Bearer k".into()))); +} + +#[test] +fn mistral_typed_stream_preserves_visible_text_thinking_and_signatures_for_replay() { + let thinking = json!({"type":"thinking", "thinking":[{"type":"text","text":"private thought"}], "signature":"signed"}); + let chunks = [ + json!({"choices":[{"delta":{"content":"Before "}}]}), + json!({"choices":[{"delta":{"content":[thinking.clone(), {"type":"text","text":"Hello"}]}}]}), + json!({"choices":[{"delta":{"content":" world"},"finish_reason":"stop"}]}), + ]; + let response = streamed(&chunks); + let reply = parse_reply(Api::OpenAi, &response).unwrap(); + assert_eq!(reply.text, "Before Hello world"); + assert_eq!(reply.native["content"][1], thinking); + let replay = Turn::Assistant { text: reply.text.clone(), calls: vec![], native: Some((Api::OpenAi, reply.native.clone())) }; + let request = chat_request(&cfg("openai"), "system", &[replay.clone()], &[]); + let body: Value = serde_json::from_str(&request.body.unwrap()).unwrap(); + assert_eq!(body["messages"][1]["content"], "Before Hello world"); + let request = chat_request(&cfg("mistral"), "system", &[replay], &[]); + let body: Value = serde_json::from_str(&request.body.unwrap()).unwrap(); + assert_eq!(body["messages"][1]["content"][1], thinking); + + let mut preview = StreamPreview::new(Api::OpenAi); + preview.feed(&response.body); + assert_eq!(preview.text(), "Before Hello world"); + let whole = HttpResponse { + status: 200, + headers: vec![], + body: json!({"choices":[{"message":reply.native, "finish_reason":"stop"}]}).to_string().into_bytes(), + }; + assert_eq!(parse_reply(Api::OpenAi, &whole).unwrap().text, "Before Hello world"); +} diff --git a/docs/cli.md b/docs/cli.md index e3716e0421..0da7095582 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -188,7 +188,7 @@ rustgis-cli ask --login # sign in with ChatGPT to us rustgis-cli ask --sample --provider chatgpt "Zoom to Tokyo" ``` -The provider is `--provider` (`anthropic`, `openai`, `chatgpt`, `gemini`, `openrouter`, `ollama`, `custom`, `requesty`, `trustedrouter`, `opper`), +The provider is `--provider` (`anthropic`, `openai`, `chatgpt`, `gemini`, `openrouter`, `ollama`, `custom`, `requesty`, `trustedrouter`, `opper`, `mistral`), else `RUSTGIS_ASSISTANT_PROVIDER`, else the first with a key in the environment, else the app's saved provider when `--use-saved-secrets` is set, else Ollama. ChatGPT sign-in is used only when that provider is selected. Account management and `--models` do not read saved API keys: diff --git a/docs/user-guide/assistant.md b/docs/user-guide/assistant.md index bbd4addec8..cc505cd333 100644 --- a/docs/user-guide/assistant.md +++ b/docs/user-guide/assistant.md @@ -102,6 +102,7 @@ Click the model name or the gear to open the settings. The assistant works with: | Requesty | A UK gateway to hundreds of models, which can move to another service when one fails. It logs requests up to 30 days by default; you can turn that off for each key. Some upstreams train on requests on paid plans too; Requesty may also train on free-plan requests. | `anthropic/claude-sonnet-5-5` | [app.requesty.ai](https://app.requesty.ai/api-keys), or `REQUESTY_API_KEY`; for the EU, set the **Address** to `https://router.eu.requesty.ai/v1` | | TrustedRouter | A US gateway to models from many services, run on servers whose software can be checked independently. The gateway doesn't keep request content; each service behind it follows its own policy and may keep or train on requests. | `trustedrouter/auto` | [trustedrouter.com](https://trustedrouter.com), or `TRUSTEDROUTER_API_KEY` | | Opper | A Swedish gateway to hundreds of models, built for keeping data in the EU. It doesn't store request content by default, but a model name without a route prefix may run outside the EU. | `claude-sonnet-5-5` | [platform.opper.ai](https://platform.opper.ai), or `OPPER_API_KEY` | +| Mistral | Mistral AI's own API, from France. Paid API requests aren't used for training by default; on a free account, turn training off under Privacy in the admin panel. Labs and Preview models may train regardless of that setting. | `mistral-small-2603` | [console.mistral.ai](https://console.mistral.ai/api-keys), or `MISTRAL_API_KEY`; for the EU, set **Address** to `https://api.eu.mistral.ai/v1` | Last checked: November 2026. These descriptions apply to the presets' default addresses. If **Address** is changed, the chosen service's policy applies. These summaries aren't guarantees @@ -112,7 +113,8 @@ as OpenAI documents for Codex. See the providers' own policies: [Anthropic](http [ChatGPT/Codex](https://help.openai.com/en/articles/7730893-data-controls-in-chatgpt), [Gemini](https://ai.google.dev/gemini-api/terms), [OpenRouter](https://openrouter.ai/privacy), [Requesty privacy](https://www.requesty.ai/privacy) and [training terms](https://www.requesty.ai/terms), [TrustedRouter](https://trustedrouter.com/privacy), -and [Opper](https://opper.ai/security-overview). +[Opper](https://opper.ai/security-overview), and +[Mistral](https://legal.mistral.ai/terms/commercial-terms-of-service/). The ↻ button lists the provider's models. The provider and model you last chose in the settings are used at start. Until you choose one, `RUSTGIS_ASSISTANT_PROVIDER` and @@ -422,7 +424,7 @@ can be used only once), and the keychain is read under the same lock. Plain HTTP is only used for servers on your computer or local network. In the web app, the browser calls the provider directly. Anthropic, OpenAI, Gemini, -OpenRouter, Requesty, TrustedRouter and Opper accept that; a local Ollama server must allow the page's origin +OpenRouter, Requesty, TrustedRouter, Opper and Mistral accept that; a local Ollama server must allow the page's origin (`OLLAMA_ORIGINS=https://web.rustgis.app ollama serve`). ## Retries and long conversations From 00c9c26ad232aeca8a416e5493158e8db3784f42 Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 27 Nov 2026 19:14:24 -0600 Subject: [PATCH 2/3] test(assistant): borrow replay turn in protocol regression --- crates/assistant/src/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/assistant/src/tests.rs b/crates/assistant/src/tests.rs index a7fd5f6f94..be8e248a55 100644 --- a/crates/assistant/src/tests.rs +++ b/crates/assistant/src/tests.rs @@ -5517,7 +5517,7 @@ fn mistral_typed_stream_preserves_visible_text_thinking_and_signatures_for_repla assert_eq!(reply.text, "Before Hello world"); assert_eq!(reply.native["content"][1], thinking); let replay = Turn::Assistant { text: reply.text.clone(), calls: vec![], native: Some((Api::OpenAi, reply.native.clone())) }; - let request = chat_request(&cfg("openai"), "system", &[replay.clone()], &[]); + let request = chat_request(&cfg("openai"), "system", std::slice::from_ref(&replay), &[]); let body: Value = serde_json::from_str(&request.body.unwrap()).unwrap(); assert_eq!(body["messages"][1]["content"], "Before Hello world"); let request = chat_request(&cfg("mistral"), "system", &[replay], &[]); From be0e0483910ef2cd139f3a3e33c60ebada75e57f Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 27 Nov 2026 22:11:33 -0600 Subject: [PATCH 3/3] fix(assistant): report undisplayed typed reply content --- crates/assistant/src/agent.rs | 4 +++ crates/assistant/src/provider.rs | 38 ++++++++++++++++++++++++---- crates/assistant/src/tests.rs | 43 ++++++++++++++++++++++++++++++++ docs/user-guide/assistant.md | 2 +- 4 files changed, 81 insertions(+), 6 deletions(-) diff --git a/crates/assistant/src/agent.rs b/crates/assistant/src/agent.rs index 3694c6a6da..168bda2f9b 100644 --- a/crates/assistant/src/agent.rs +++ b/crates/assistant/src/agent.rs @@ -756,6 +756,7 @@ impl Agent { } /// Discards stale generations, applies provider recovery and records privacy-policy refusals. + /// Content notices reach the transcript for both normal replies and compaction summaries. fn receive_unguarded(&mut self, generation: u64, resp: Result, s: &mut Session) -> Step { if generation != self.generation || !self.waiting() { return Step::Done; @@ -802,6 +803,9 @@ impl Agent { return Step::Retry(after); } self.retries = 0; + if let Ok(reply) = &parsed { + self.transcript.extend(reply.notes.iter().cloned().map(Entry::Note)); + } if let State::Compacting { upto, resume } = self.state { return self.summarised(upto, resume, parsed); } diff --git a/crates/assistant/src/provider.rs b/crates/assistant/src/provider.rs index 9500a700a0..3eb501ecdf 100644 --- a/crates/assistant/src/provider.rs +++ b/crates/assistant/src/provider.rs @@ -710,6 +710,7 @@ impl Note { /// Every [`Note`] template RustGIS writes (the interface's catalogs translate each). pub const NOTE_TEMPLATES: &[&str] = &[ + "The reply contains {count} content parts of type {kind} that aren't displayed.", "OpenRouter found no endpoint matching your data policy. Check Private routing in the Assistant settings or your OpenRouter privacy settings.", "The reply reached its length limit.", "The provider's content filter stopped the reply.", @@ -780,6 +781,8 @@ pub struct Reply { pub text: String, pub calls: Vec, pub native: Value, + /// Nonfatal diagnostics about content the interface cannot display. + pub notes: Vec, /// Why the reply stopped early (length limit, a refusal), if it did. pub cut: Option, /// A failed terminal response accompanying partial text. @@ -898,7 +901,7 @@ fn openai_assembled(events: &[Value]) -> Value { for e in events { for choice in e.get("choices").and_then(Value::as_array).into_iter().flatten() { let delta = choice.get("delta").unwrap_or(&Value::Null); - if let Some(next) = delta.get("content").filter(|v| !v.is_null()) { + if let Some(next) = delta.get("content").filter(|v| !v.is_null() && v.as_str() != Some("")) { match (&mut content, next) { (Value::String(text), Value::String(more)) => text.push_str(more), (Value::Array(parts), Value::Array(more)) => parts.extend(more.iter().cloned()), @@ -1103,6 +1106,8 @@ impl StreamPreview { self.text.len() > before } + /// Extracts visible text from one event. Native thinking and signatures are assembled by + /// the completed-response parser rather than streamed into the answer. fn delta(&self, v: &Value) -> String { let s = |p: &str| v.pointer(p).and_then(Value::as_str).unwrap_or("").to_string(); match self.api { @@ -1295,11 +1300,34 @@ fn openai_content_text(content: Option<&Value>) -> String { } } +/// Counts unsupported display parts once per type. Thinking is native replay metadata; +/// other non-text parts remain native too, but their omission from the answer must be visible. +fn openai_content_notes(content: Option<&Value>) -> Vec { + let mut counts = std::collections::BTreeMap::<&str, usize>::new(); + for part in content.and_then(Value::as_array).into_iter().flatten() { + let kind = part.get("type").and_then(Value::as_str).unwrap_or("unknown"); + if kind == "thinking" || (kind == "text" && part.get("text").is_some_and(Value::is_string)) { + continue; + } + *counts.entry(kind).or_default() += 1; + } + counts + .into_iter() + .map(|(kind, count)| { + Note::with( + "The reply contains {count} content parts of type {kind} that aren't displayed.", + [("count", count.to_string()), ("kind", kind.to_string())], + ) + }) + .collect() +} + /// Reads Chat Completions, retaining native typed content for the next request. fn openai_reply(v: &Value) -> Result { let choice = v.get("choices").and_then(|c| c.get(0)).ok_or("the reply has no choices")?; let msg = choice.get("message").ok_or("the reply has no message")?; let text = openai_content_text(msg.get("content")); + let notes = openai_content_notes(msg.get("content")); let calls = msg .get("tool_calls") .and_then(Value::as_array) @@ -1333,7 +1361,7 @@ fn openai_reply(v: &Value) -> Result { if let Some(o) = native.as_object_mut() { o.retain(|k, _| matches!(k.as_str(), "role" | "content" | "tool_calls" | "reasoning_content")); } - Ok(Reply { text, calls, native, cut, failure: None }) + Ok(Reply { text, calls, native, notes, cut, failure: None }) } // --------------------------------------------------------------------------------------------- @@ -1554,7 +1582,7 @@ fn responses_reply(resp: &HttpResponse) -> Result { }) .collect(); let failure = (!completed && last.get("error").is_some_and(Value::is_object)).then(|| Error::response(&last, resp)); - Ok(Reply { text, calls, native: Value::Array(native), cut, failure }) + Ok(Reply { text, calls, native: Value::Array(native), notes: Vec::new(), cut, failure }) } // --------------------------------------------------------------------------------------------- @@ -1681,7 +1709,7 @@ fn anthropic_reply(v: &Value) -> Result { if v.get("stop_reason").and_then(Value::as_str) == Some("refusal") { calls.clear(); } - Ok(Reply { text, calls, native: Value::Array(content.clone()), cut, failure: None }) + Ok(Reply { text, calls, native: Value::Array(content.clone()), notes: Vec::new(), cut, failure: None }) } // --------------------------------------------------------------------------------------------- @@ -1821,7 +1849,7 @@ fn gemini_reply(v: &Value) -> Result { if native.get("role").is_none() { native["role"] = json!("model"); } - Ok(Reply { text, calls, native, cut, failure: None }) + Ok(Reply { text, calls, native, notes: Vec::new(), cut, failure: None }) } /// `v` if it is an object, else an empty one (providers require objects for tool input). diff --git a/crates/assistant/src/tests.rs b/crates/assistant/src/tests.rs index be8e248a55..0f6597ca87 100644 --- a/crates/assistant/src/tests.rs +++ b/crates/assistant/src/tests.rs @@ -117,6 +117,9 @@ fn first_keyed_provider_is_the_first_key_provider_and_never_a_sign_in() { // Opper comes after Requesty, so its key never takes the place of another provider's either. assert_eq!(first_keyed(keyed(&["opper", "requesty"])), Some("requesty")); assert_eq!(first_keyed(keyed(&["opper"])), Some("opper")); + // Mistral follows the existing keyed presets. + assert_eq!(first_keyed(keyed(&["mistral", "opper"])), Some("opper")); + assert_eq!(first_keyed(keyed(&["mistral"])), Some("mistral")); assert_eq!(first_keyed(keyed(&[])), None); } @@ -5515,6 +5518,7 @@ fn mistral_typed_stream_preserves_visible_text_thinking_and_signatures_for_repla let response = streamed(&chunks); let reply = parse_reply(Api::OpenAi, &response).unwrap(); assert_eq!(reply.text, "Before Hello world"); + assert!(reply.notes.is_empty()); assert_eq!(reply.native["content"][1], thinking); let replay = Turn::Assistant { text: reply.text.clone(), calls: vec![], native: Some((Api::OpenAi, reply.native.clone())) }; let request = chat_request(&cfg("openai"), "system", std::slice::from_ref(&replay), &[]); @@ -5534,3 +5538,42 @@ fn mistral_typed_stream_preserves_visible_text_thinking_and_signatures_for_repla }; assert_eq!(parse_reply(Api::OpenAi, &whole).unwrap().text, "Before Hello world"); } + +#[test] +fn typed_reply_notices_count_unsupported_parts_and_keep_the_native_content() { + let content = json!([ + {"type":"text", "text":"Answer"}, + {"type":"thinking", "thinking":[], "signature":"signed"}, + {"type":"reference", "reference_ids":[0]}, + {"type":"reference", "reference_ids":[1]} + ]); + let streamed = streamed(&[ + json!({"choices":[{"delta":{"content":""}}]}), + json!({"choices":[{"delta":{"content":content.clone()}}]}), + json!({"choices":[{"delta":{"content":""}, "finish_reason":"stop"}]}), + ]); + let mut preview = StreamPreview::new(Api::OpenAi); + preview.feed(&streamed.body); + assert_eq!(preview.text(), "Answer"); + let whole = HttpResponse { + status: 200, + headers: vec![], + body: json!({"choices":[{"message":{"role":"assistant", "content":content}, "finish_reason":"stop"}]}).to_string().into_bytes(), + }; + for response in [streamed, whole] { + let mut session = sample(); + let mut agent = Agent::new(cfg("mistral"), &session); + assert!(matches!(agent.ask("hello", &session), Step::Send(_))); + assert_eq!(agent.receive(agent.generation(), Ok(response), &mut session), Step::Done); + let notes: Vec<_> = + agent.transcript.iter().filter_map(|entry| if let Entry::Note(note) = entry { Some(note) } else { None }).collect(); + assert_eq!(notes.len(), 1); + assert_eq!(notes[0].template, "The reply contains {count} content parts of type {kind} that aren't displayed."); + assert_eq!(notes[0].args, [("count", "2".to_string()), ("kind", "reference".to_string())]); + assert!(agent.transcript.iter().any(|entry| matches!(entry, Entry::Assistant(text) if text == "Answer"))); + let Some(Turn::Assistant { native: Some((Api::OpenAi, native)), .. }) = agent.turns().last() else { + panic!("missing native reply") + }; + assert_eq!(native["content"], content); + } +} diff --git a/docs/user-guide/assistant.md b/docs/user-guide/assistant.md index cc505cd333..1a3da1428e 100644 --- a/docs/user-guide/assistant.md +++ b/docs/user-guide/assistant.md @@ -102,7 +102,7 @@ Click the model name or the gear to open the settings. The assistant works with: | Requesty | A UK gateway to hundreds of models, which can move to another service when one fails. It logs requests up to 30 days by default; you can turn that off for each key. Some upstreams train on requests on paid plans too; Requesty may also train on free-plan requests. | `anthropic/claude-sonnet-5-5` | [app.requesty.ai](https://app.requesty.ai/api-keys), or `REQUESTY_API_KEY`; for the EU, set the **Address** to `https://router.eu.requesty.ai/v1` | | TrustedRouter | A US gateway to models from many services, run on servers whose software can be checked independently. The gateway doesn't keep request content; each service behind it follows its own policy and may keep or train on requests. | `trustedrouter/auto` | [trustedrouter.com](https://trustedrouter.com), or `TRUSTEDROUTER_API_KEY` | | Opper | A Swedish gateway to hundreds of models, built for keeping data in the EU. It doesn't store request content by default, but a model name without a route prefix may run outside the EU. | `claude-sonnet-5-5` | [platform.opper.ai](https://platform.opper.ai), or `OPPER_API_KEY` | -| Mistral | Mistral AI's own API, from France. Paid API requests aren't used for training by default; on a free account, turn training off under Privacy in the admin panel. Labs and Preview models may train regardless of that setting. | `mistral-small-2603` | [console.mistral.ai](https://console.mistral.ai/api-keys), or `MISTRAL_API_KEY`; for the EU, set **Address** to `https://api.eu.mistral.ai/v1` | +| Mistral | Mistral AI's own API, from France. Paid API requests aren't used for training by default; on a free account, turn training off under Privacy in the admin panel. Labs and Preview models may train regardless of that setting. | `mistral-small-2603` | [console.mistral.ai](https://console.mistral.ai/api-keys), or `MISTRAL_API_KEY`; for [EU inference](https://docs.mistral.ai/inference/regional-inference), set **Address** to `https://api.eu.mistral.ai/v1` (supported models only; 10% surcharge) | Last checked: November 2026. These descriptions apply to the presets' default addresses. If **Address** is changed, the chosen service's policy applies. These summaries aren't guarantees