Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
2 changes: 1 addition & 1 deletion apps/rustgis-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions crates/assistant/src/agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<HttpResponse, crate::Error>, s: &mut Session) -> Step {
if generation != self.generation || !self.waiting() {
return Step::Done;
Expand Down Expand Up @@ -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);
}
Expand Down
130 changes: 119 additions & 11 deletions crates/assistant/src/provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -696,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.",
Expand Down Expand Up @@ -766,6 +781,8 @@ pub struct Reply {
pub text: String,
pub calls: Vec<ToolCall>,
pub native: Value,
/// Nonfatal diagnostics about content the interface cannot display.
pub notes: Vec<Note>,
/// Why the reply stopped early (length limit, a refusal), if it did.
pub cut: Option<Note>,
/// A failed terminal response accompanying partial text.
Expand Down Expand Up @@ -879,12 +896,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() && 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()),
(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})];

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.

When the first content delta is an empty string (common in the opening chunk of a stream), this arm stores an empty {"type":"text","text":""} part. That part is replayed to Mistral in the native message. I can't confirm from here whether Mistral rejects empty text chunks, but skipping empty text avoids sending one for no reason. Small fix:

Suggested change
let mut all = vec![json!({"type":"text", "text":text})];
let mut all = if text.is_empty() { Vec::new() } else { vec![json!({"type":"text", "text":text})] };

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in be0e048 by ignoring empty string deltas before assembly. The regression opens and closes a typed stream with empty deltas and checks the exact native payload. It fails with the filter reverted. Full fork CI passed.

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());
Expand Down Expand Up @@ -917,7 +947,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("") {

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.

This check can no longer fire. The delta filter above never stores an empty string (v.as_str() != Some("")), and every push_str/append adds non-empty content, so content is never "". Meanwhile an all-empty array delta ("content": []) is stored as [], which the old code turned into null. A [] now goes into the native assistant message, and Mistral replays that native message on later turns. Normalising both empty shapes keeps the old behaviour and makes the check do its job:

Suggested change
if content.as_str() == Some("") {
if content.as_str() == Some("") || content.as_array().is_some_and(Vec::is_empty) {
content = Value::Null;
}

Confidence: high that the string branch is dead; medium that an empty array is a real replay problem (I can't test against the live API here).

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Empty-array normalization and removing the now-redundant string check are left for the release quality pass. The existing fix prevents empty string deltas from creating replay text blocks; no empty-array rejection has been demonstrated.

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() {
Expand Down Expand Up @@ -1073,11 +1106,13 @@ 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 {
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")
Expand Down Expand Up @@ -1122,7 +1157,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 {
Expand All @@ -1134,7 +1169,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

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.

For Mistral, this keeps the full native message, including every thinking block and its signature, and sends it back on each later request. Compaction does not reclaim that space. compact::trim (crates/assistant/src/compact.rs:157-167) strips thinking only for Api::Responses (reasoning) and Api::Anthropic (thinking, redacted_thinking). For Api::OpenAi it matches _ => &[], and it only edits native values that are arrays, while this one is an object. So Mistral thinking stays in every request for the rest of the conversation, and compact::size counts it toward the budget. That makes compaction trigger earlier and raises per-turn tokens for the whole session. Either drop the thinking parts from older OpenAI-shaped native turns in trim (the way the Anthropic branch does), or say in the PR why replay must keep them for all turns. Confidence: medium-high from reading the code; I have not measured the size.

Category: performance

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Full compaction does reclaim these blocks: compact::apply drains the summarized turns, including their native payloads. The earlier trimming pass does not strip OpenAI-shaped thinking, as noted. Adding that optimization, with provider replay validation, is left for the release quality pass; native reasoning is retained until the existing summary path replaces those turns.

// 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() {
Expand All @@ -1153,6 +1197,9 @@ fn openai_request(cfg: &Config, system: &str, turns: &[Turn], tools: &[ToolDef])
}
}
}
if cfg.provider == "mistral" {
mistral_call_ids(&mut messages);
}
let tools: Vec<Value> = tools
.iter()
.map(|t| json!({"type": "function", "function": {"name": t.name, "description": t.description, "parameters": t.schema}}))
Expand Down Expand Up @@ -1183,6 +1230,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: <https://huggingface.co/mistralai/Mistral-Large-Instruct-2407>.
fn mistral_call_ids(messages: &mut [Value]) {
let mut ids = std::collections::BTreeMap::<String, String>::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
Expand Down Expand Up @@ -1216,10 +1286,48 @@ 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"))

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.

openai_content_text keeps only type: "text" parts and drops every other typed part without a trace. The visible reply and the stream preview therefore lose anything else a compatible server sends in content, such as a reference or citation chunk. AGENTS asks that a reader which drops data says what and how much (Session::notify or ToolResult::messages, one notice per kind with a count), and that lossy input has a test that expects the notice. Either count the skipped non-text parts and report them, or pin the chosen behaviour in a test. Confidence is low-to-medium: RustGIS sends only function tools, so I'm not sure the Mistral API returns these parts on this path.

Category: bug

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in be0e048. Unsupported display parts now generate one counted transcript notice per type, including for summary replies, while the native payload remains intact. Known thinking metadata does not generate a notice. The regression exercises streamed and whole replies through the agent, checks the exact count and native content, and fails with reporting reverted. Full fork CI passed. Mistral’s citation documentation confirms reference chunks can accompany function-tool replies.

.filter_map(|p| p.get("text").and_then(Value::as_str))
.collect(),
_ => String::new(),
}
}

/// 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<Note> {
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<Reply, String> {
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 notes = openai_content_notes(msg.get("content"));
let calls = msg
.get("tool_calls")
.and_then(Value::as_array)
Expand Down Expand Up @@ -1253,7 +1361,7 @@ fn openai_reply(v: &Value) -> Result<Reply, String> {
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 })
}

// ---------------------------------------------------------------------------------------------
Expand Down Expand Up @@ -1474,7 +1582,7 @@ fn responses_reply(resp: &HttpResponse) -> Result<Reply, Error> {
})
.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 })
}

// ---------------------------------------------------------------------------------------------
Expand Down Expand Up @@ -1601,7 +1709,7 @@ fn anthropic_reply(v: &Value) -> Result<Reply, String> {
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 })
}

// ---------------------------------------------------------------------------------------------
Expand Down Expand Up @@ -1741,7 +1849,7 @@ fn gemini_reply(v: &Value) -> Result<Reply, String> {
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).
Expand Down
Loading
Loading