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
21 changes: 21 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,27 @@ from the roadmap, or narrows it to what is left; one that lands an item of the
[GeoLibre parity checklist](docs/geolibre-parity.md) updates that file. Either change goes in the same pull
request.

## Adding an AI provider

A preset in the Assistant's list reads as RustGIS recommending a service. Requests can carry
layer names, rows the assistant reads and pictures of the user's map. A preset needs:

1. **A named operator and a published data policy.** Its site names the legal entity, country
and contact address, and explains retention and training for request and reply content,
including services it forwards to.
2. **No training by default, or a plain warning.** Where the API provides a per-request control,
the preset uses it by default. Otherwise its description says when training can happen and
how users can turn it off. Check the account reached through the preset's key link.
3. **Known upstreams.** A gateway names the services it forwards to. Requests must not pass
through anonymous resellers' accounts.
4. **Affiliation disclosed** in the pull request.

Link the evidence in the pull request, and add the same short description of the operator and
privacy considerations to the preset and the [user guide](docs/user-guide/assistant.md#choosing-a-model).
Keep setup instructions in the guide's Key column. Other services can use the OpenAI-compatible
provider and its **Address**. A preset that stops meeting these criteria may be removed;
removal must tell affected users before requests go to a different provider.

## AI-assisted contributions

Code written with AI tools is welcome, from anyone, whatever their programming experience
Expand Down
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, Requesty, TrustedRouter, Opper, 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, 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
11 changes: 11 additions & 0 deletions crates/assistant/src/agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -755,6 +755,7 @@ impl Agent {
self.guard(|a| a.receive_unguarded(generation, resp, s))
}

/// Discards stale generations, applies provider recovery and records privacy-policy refusals.
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 All @@ -766,6 +767,16 @@ impl Agent {
}
self.preview = None;
let parsed = resp.as_ref().map_err(Clone::clone).and_then(|r| provider::parse_reply(self.config.api(), r));
if self.config.provider == "openrouter"
&& matches!(&parsed, Err(e) if e.status == Some(404) && {
let detail = e.detail.to_ascii_lowercase();
detail.contains("data policy") || detail.contains("data collection") || detail.contains("privacy")
})
{
self.transcript.push(Entry::Note(Note::new(
"OpenRouter found no endpoint matching your data policy. Check Private routing in the Assistant settings or your OpenRouter privacy settings.",
)));
}
// A model that doesn't read images refuses them every time (some servers with a 500):
// asked again at once without them, not retried as an outage.
let images_refused = matches!(&parsed, Err(e) if self.sent_images_to.as_ref().is_some_and(|to| !self.no_images.contains(to))
Expand Down
23 changes: 23 additions & 0 deletions crates/assistant/src/provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ pub enum Api {
/// A provider the settings offer, with its defaults.
pub struct Preset {
pub id: &'static str,
/// Who operates the service and the privacy considerations for its default account.
pub description: &'static str,
pub label: &'static str,
pub api: Api,
pub base_url: &'static str,
Expand All @@ -47,6 +49,7 @@ pub struct Preset {
pub const PRESETS: &[Preset] = &[
Preset {
id: "anthropic",
description: "Anthropic's own API, from the makers of Claude. API requests aren't used for training; content may be kept for safety checks, with exceptions to the standard 30-day deletion period.",
label: "Anthropic",
api: Api::Anthropic,
base_url: "https://api.anthropic.com",
Expand All @@ -59,6 +62,7 @@ pub const PRESETS: &[Preset] = &[
},
Preset {
id: "openai",
description: "OpenAI's own API, from the makers of GPT. API requests aren't used for training by default; abuse monitoring logs may be kept up to 30 days, with legal and safety exceptions.",
label: "OpenAI",
api: Api::OpenAi,
base_url: "https://api.openai.com/v1",
Expand All @@ -71,6 +75,7 @@ pub const PRESETS: &[Preset] = &[
},
Preset {
id: "chatgpt",
description: "OpenAI's models, billed to your ChatGPT plan. On a personal plan, ChatGPT's \"Improve the model\" setting decides whether requests are used for training; Business, Enterprise and Edu plans aren't trained on by default.",
label: "ChatGPT (sign in)",
api: Api::Responses,
base_url: crate::chatgpt::API,
Expand All @@ -85,6 +90,7 @@ pub const PRESETS: &[Preset] = &[
},
Preset {
id: "gemini",
description: "Google's own API. With a free key, Google may use requests to improve its products and people may read them; a Cloud project with billing turns that off. In the EEA, Switzerland and the UK, paid-service data terms also cover free use.",
label: "Google Gemini",
api: Api::Gemini,
base_url: "https://generativelanguage.googleapis.com/v1beta",
Expand All @@ -97,6 +103,7 @@ pub const PRESETS: &[Preset] = &[
},
Preset {
id: "openrouter",
description: "A US gateway to hundreds of models. OpenRouter doesn't keep request content by default. With Private routing on (the default), RustGIS asks it to skip endpoints that may train on requests.",
label: "OpenRouter",
api: Api::OpenAi,
base_url: "https://openrouter.ai/api/v1",
Expand All @@ -109,6 +116,7 @@ pub const PRESETS: &[Preset] = &[
},
Preset {
id: "ollama",
description: "Models you run with Ollama on this computer or a server of your own. Requests go to the server at the chosen address; its models and configuration determine any onward use.",
label: "Ollama (local)",
api: Api::OpenAi,
base_url: "http://localhost:11434/v1",
Expand All @@ -121,6 +129,7 @@ pub const PRESETS: &[Preset] = &[
},
Preset {
id: "custom",
description: "Any service or local server that speaks OpenAI's API. What happens to requests is up to the service at the chosen address.",
label: "OpenAI-compatible",
api: Api::OpenAi,
base_url: "http://localhost:1234/v1",
Expand All @@ -133,6 +142,7 @@ pub const PRESETS: &[Preset] = &[
},
Preset {
id: "requesty",
description: "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.",

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.

CONTRIBUTING.md (added in this PR) requires that where the API has no per-request training control, the description "says when training can happen and how users can turn it off". This text says training can happen on paid plans and free plans, but gives no way to turn it off. The same gap is in TrustedRouter's description (line 158: "may keep or train on requests", no opt-out given) and Opper's (line 171) says nothing about training at all. Either state the opt-out (the account or key setting, if one exists) or say that no control is documented, so the preset meets the criterion this PR sets. This is a policy-wording point rather than a code defect, so it can be settled with the maintainer's review of the sources.

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.

The descriptions retain the upstream-training warnings. Further opt-out detail for these gateways is left for the release quality pass and the maintainer’s review of the proposed preset policy. The PR retains its policy-agreement hold before landing.

label: "Requesty",
api: Api::OpenAi,
base_url: "https://router.requesty.ai/v1",
Expand All @@ -145,6 +155,7 @@ pub const PRESETS: &[Preset] = &[
},
Preset {
id: "trustedrouter",
description: "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.",
label: "TrustedRouter",
api: Api::OpenAi,
base_url: "https://api.trustedrouter.com/v1",
Expand All @@ -157,6 +168,7 @@ pub const PRESETS: &[Preset] = &[
},
Preset {
id: "opper",
description: "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.",
label: "Opper",
api: Api::OpenAi,
base_url: "https://api.opper.ai/v3/compat",
Expand Down Expand Up @@ -192,6 +204,8 @@ pub struct Config {
/// Whether the catalog offers reasoning for the selected model (`Some(false)` also turns it off
/// for a Chat Completions model that refused it alongside tools: see [`refuses_reasoning_with_tools`]).
pub reasoning: Option<bool>,
/// OpenRouter routing excludes endpoints that collect request data by default.
pub openrouter_private: bool,
/// Requested tool output token estimate (default 10,000); the 24,000-token hard limit still applies.
pub tool_output_token_limit: usize,
}
Expand Down Expand Up @@ -224,6 +238,7 @@ impl Config {
client_id: String::new(),
session: String::new(),
reasoning: None,
openrouter_private: env("RUSTGIS_OPENROUTER_DATA_COLLECTION").as_deref() != Some("allow"),
tool_output_token_limit: env("RUSTGIS_ASSISTANT_TOOL_OUTPUT_TOKEN_LIMIT")
.and_then(|s| s.parse().ok())
.filter(|n| *n > 0)
Expand Down Expand Up @@ -276,6 +291,9 @@ impl Config {
}
}

/// OpenRouter-only routing preference; missing values keep the privacy filter enabled.
pub const OPENROUTER_PRIVATE_PREF: &str = "assistant_openrouter_private";

/// The desktop preference naming the provider it uses (`prefs.json`).
pub const PROVIDER_PREF: &str = "assistant_provider";

Expand Down Expand Up @@ -678,6 +696,7 @@ impl Note {

/// Every [`Note`] template RustGIS writes (the interface's catalogs translate each).
pub const NOTE_TEMPLATES: &[&str] = &[
"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.",
"The reply stopped early ({reason}).",
Expand Down Expand Up @@ -1103,6 +1122,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.
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 Down Expand Up @@ -1138,6 +1158,9 @@ fn openai_request(cfg: &Config, system: &str, turns: &[Turn], tools: &[ToolDef])
.map(|t| json!({"type": "function", "function": {"name": t.name, "description": t.description, "parameters": t.schema}}))
.collect();
let mut body = json!({"model": cfg.model.trim(), "messages": messages, "stream": true});
if cfg.provider == "openrouter" && cfg.openrouter_private {

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.

The filter is keyed on the provider name, not on the endpoint. If a user keeps the OpenRouter preset but changes Address to a different OpenAI-compatible server, provider: {"data_collection": "deny"} is still sent to that server. Most servers ignore unknown fields, but a strict one may answer 400, which then reads as a general request failure. The UI text ("Ask OpenRouter to exclude…") also no longer matches the endpoint. Consider sending the field only when the base URL is the OpenRouter address, or noting the limit in the guide. I checked: the subagent, summary and image-retry requests all reach this function through chat_request, so coverage is complete for OpenRouter.

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.

The filter follows the selected OpenRouter preset, including an overridden address, so changing the address does not silently remove the requested privacy constraint. Clarifying that compatibility limit in the guide is left for the release quality pass.

body["provider"] = json!({"data_collection": "deny"});
}
// Some servers refuse an empty tool list.
if !tools.is_empty() {
body["tools"] = json!(tools);
Expand Down
29 changes: 29 additions & 0 deletions crates/assistant/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ fn sample() -> Session {
s
}

/// Deterministic provider defaults with a synthetic key and private routing enabled.
fn cfg(provider: &str) -> Config {
let p = preset(provider).unwrap_or(&PRESETS[0]);
Config {
Expand All @@ -47,6 +48,7 @@ fn cfg(provider: &str) -> Config {
client_id: String::new(),
session: String::new(),
reasoning: None,
openrouter_private: true,
tool_output_token_limit: crate::tools::DEFAULT_OUTPUT_TOKENS,
}
}
Expand Down Expand Up @@ -5428,3 +5430,30 @@ fn a_message_joining_one_left_unanswered_takes_no_more_than_four_pictures() {
let said = "A message takes at most 4 pictures: a1.jpg, a2.jpg, a3.jpg, a4.jpg left out.";
assert!(a.transcript.iter().any(|e| matches!(e, Entry::Note(n) if n.to_string() == said)));
}

#[test]
fn openrouter_private_routing_filters_only_openrouter_and_can_be_disabled() {

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.

The new tests cover the request body and the refusal note, but nothing covers the two ways the setting is read: from_env with RUSTGIS_OPENROUTER_DATA_COLLECTION set to allow (false) versus any other value (true), and the desktop preference round-trip (save_config writes "on"/"off", load_config reads it back, a missing value means on). Both sides of each should be asserted, since the "other values keep it on" promise in the guide is what makes the default safe. Note that from_env reads the process environment, so the test should set and restore the variable, or be factored to take the value as a parameter.

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.

Additional environment-parsing and preference round-trip coverage is left for the release quality pass. The current regressions cover outgoing routing, refusal guidance and stopping a run when the UI policy changes; the parsing and saved-preference expressions retain the private default.

let mut c = cfg("openrouter");
let body = |c: &Config| -> Value { serde_json::from_str(&chat_request(c, "system", &[], &[]).body.unwrap()).unwrap() };
assert_eq!(body(&c)["provider"], json!({"data_collection":"deny"}));
c.openrouter_private = false;
assert!(body(&c).get("provider").is_none());
for p in PRESETS.iter().filter(|p| p.api == Api::OpenAi && p.id != "openrouter") {
assert!(body(&cfg(p.id)).get("provider").is_none(), "{}", p.id);
}
}

#[test]
fn openrouter_data_policy_refusal_names_the_privacy_checkbox() {
let mut session = sample();
let mut a = Agent::new(cfg("openrouter"), &session);
assert!(matches!(a.ask("hello", &session), Step::Send(_)));
let response = HttpResponse {
status: 404,
headers: vec![],
body: br#"{"error":{"message":"No endpoints found matching your data policy"}}"#.to_vec(),
};
let generation = a.generation();
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"))));
}
17 changes: 12 additions & 5 deletions crates/ui-egui/src/assistant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,9 @@ fn load_config(app: &mut RustGisApp, provider: &str, ctx: &egui::Context) -> Con
if let Some(u) = pref(app, &provider::url_pref(provider)).filter(|_| !c.login()) {
c.base_url = u;
}
if provider == "openrouter" {
c.openrouter_private = pref(app, provider::OPENROUTER_PRIVATE_PREF).as_deref() != Some("off");

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.

On the desktop, this line overrides the value Config::from_env read, so RUSTGIS_OPENROUTER_DATA_COLLECTION=allow has no effect in the app even when no preference has been saved yet. The guide scopes the variable to the command line, so this is consistent with the docs, but the app will show "Private routing" checked while the environment says otherwise, with no notice. Falling back to the environment value when no preference is saved would make the variable work in both places and keep the fail-safe default.

Suggested change
c.openrouter_private = pref(app, provider::OPENROUTER_PRIVATE_PREF).as_deref() != Some("off");
if provider == "openrouter" {
c.openrouter_private = pref(app, provider::OPENROUTER_PRIVATE_PREF).map_or(c.openrouter_private, |v| v != "off");
}

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.

The CLI-only scope is intentional. Inheriting allow on the desktop and then saving an unrelated setting would persist an environment-only opt-out for later launches without that variable. The desktop therefore uses its saved checkbox or the private default; the CLI continues to honor the environment variable.

}
if !c.login() {
let legacy = pref(app, &format!("assistant_key_{provider}"));
#[cfg(not(target_arch = "wasm32"))]
Expand Down Expand Up @@ -416,6 +419,9 @@ pub(crate) fn save_config(app: &mut RustGisApp, c: &Config, ctx: &egui::Context)
save_pref(app, provider::PROVIDER_PREF, &c.provider);
save_pref(app, &format!("assistant_model_{}", c.provider), c.model.trim());
save_pref(app, &provider::url_pref(&c.provider), c.base_url.trim());
if c.provider == "openrouter" {
save_pref(app, provider::OPENROUTER_PRIVATE_PREF, provider::remember_key_value(c.openrouter_private));
}
// A key from the environment stays there; a sign-in's tokens live in their own file.
let from_env = Config::from_env(&c.provider).key;
if c.login() {
Expand Down Expand Up @@ -552,12 +558,13 @@ pub(crate) fn list_models(app: &mut RustGisApp, cfg: &Config, ctx: &egui::Contex
app.assistant.models_slot = Some(dispatch(app, req, cfg.login().then(|| cfg.binding()), None, ctx));
}

/// Replaces provider settings and stops work bound to a different provider or sign-in.
/// Replaces settings, stopping work when its provider, sign-in or OpenRouter privacy policy changes.
pub(crate) fn apply_config(app: &mut RustGisApp, cfg: Config) {
let another = app
.assistant
.config()
.is_some_and(|c| c.provider != cfg.provider || (c.login() && (c.binding() != cfg.binding() || c.key != cfg.key)));
let another = app.assistant.config().is_some_and(|c| {
c.provider != cfg.provider
|| (c.provider == "openrouter" && c.openrouter_private != cfg.openrouter_private)
|| (c.login() && (c.binding() != cfg.binding() || c.key != cfg.key))
});
if another {
stop(app);
}
Expand Down
Loading
Loading