AI SDK
An ergonomic, Laravel-inspired AI SDK for Elyra apps — agents, tools,
structured output, images, and embeddings over Anthropic and OpenAI.
It lives in the elyra-ai crate and is re-exported as elyra::ai
behind the ai feature. Everything runs in the Rust backend, so API keys never
reach the frontend.
elyra = { …, features = ["ai"] }
Configuration
Keys are read from the environment:
ANTHROPIC_API_KEY=…
OPENAI_API_KEY=…
# optional proxy/gateway overrides
ANTHROPIC_BASE_URL=…
OPENAI_BASE_URL=…
# other providers: see below
GEMINI_API_KEY=… GROQ_API_KEY=… MISTRAL_API_KEY=… …
The default provider is Anthropic with the claude-sonnet-5-5 text model;
images default to OpenAI gpt-image-1, embeddings to text-embedding-3-small.
Build a client with Ai::from_env() or Ai::builder().
Other providers
Every provider other than Anthropic speaks OpenAI's Chat Completions shape and runs on the same driver (RFC 0048): text, tools, structured output, streaming and failover. Images, speech, transcription and embeddings stay on OpenAI, and provider tools (web search, web fetch, code execution) on Anthropic.
| Provider | Key | Base URL (override with …_BASE_URL) |
|---|---|---|
Provider::Gemini |
GEMINI_API_KEY |
https://generativelanguage.googleapis.com/v1beta/openai |
Provider::Groq |
GROQ_API_KEY |
https://api.groq.com/openai/v1 |
Provider::Mistral |
MISTRAL_API_KEY |
https://api.mistral.ai/v1 |
Provider::DeepSeek |
DEEPSEEK_API_KEY |
https://api.deepseek.com/v1 |
Provider::XAi |
XAI_API_KEY |
https://api.x.ai/v1 |
Provider::OpenRouter |
OPENROUTER_API_KEY |
https://openrouter.ai/api/v1 |
Provider::Ollama |
none | http://localhost:11434/v1 |
Provider::Compatible |
ELYRA_AI_COMPATIBLE_KEY (optional) |
none: set ELYRA_AI_COMPATIBLE_BASE_URL |
The chat goes to {base URL}/chat/completions. Compatible is any other
endpoint of that shape: a company gateway, vLLM, LM Studio. Ollama, and a
compatible endpoint without a key, are sent no Authorization header.
These providers have no default model: model names change faster than
releases. Name one per chat, or per provider on the client; without one, the
chat fails with Error::NotConfigured before anything is sent:
let ai = Ai::builder()
.provider_key(Provider::Groq, key)
.text_model_for(Provider::Groq, "llama-3.3-70b-versatile")
.text_model_for(Provider::Ollama, "llama3.2")
.build();
ai.chat().provider(Provider::Groq).prompt("Hi").await?;
ai.chat().provider(Provider::Gemini).model("gemini-2.5-flash").prompt("Hi").await?;
A chat's model is, in order: its .model(…), the provider's
text_model_for, the client's text_model, the provider's default
(Anthropic's and OpenAI's).
A key compiled into a desktop app is a key anyone can extract. Behind a
gateway that holds the key (your own server, with the user's session),
authenticate with a bearer token instead. token() is asked for each
request, so a renewed token is picked up, and with none (the user signed out)
the call fails with Error::NoToken before anything is sent:
let ai = Ai::builder()
.base_url(Provider::Anthropic, "https://crm.example.com/api/elyra/assistant")
.bearer(Provider::Anthropic, move || session.token()) // Option<String>
.build();
The request is then Authorization: Bearer <token> instead of x-api-key.
Binding into the app
Add the provider so commands can resolve the client:
use elyra::App;
use elyra::ai::{Ai, AiProvider};
App::new().provider(AiProvider).run()?;
#[command]
async fn ask(ctx: Ctx, prompt: String) -> Result<String, String> {
ctx.get::<Ai>()
.chat()
.instructions("You are a concise assistant.")
.prompt(prompt)
.await
.map(|r| r.text().to_string())
.map_err(|e| e.to_string())
}
Anonymous agents (one-off chats)
The Rust analogue of Laravel's agent(...) helper:
let reply = ai.chat()
.instructions("You are a concise Rust expert.")
.prompt("What is ownership?")
.await?;
println!("{reply}"); // Display = the text
println!("{:?}", reply.usage()); // token usage
.temperature(t) applies to OpenAI only. Anthropic's Messages API (version
2026-10-21, which the SDK speaks) refuses temperature on every model, so
the SDK doesn't send it there and Claude samples at its defaults; it says so
once on stderr.
When Claude declines a request for safety reasons, the call fails with
Error::Refused, carrying the model's explanation.
Override the provider/model per call:
use elyra::ai::Provider;
ai.chat()
.provider(Provider::OpenAI)
.model("gpt-4o-mini")
.prompt("Summarize this…")
.await?;
Named agents
Implement [Agent] for reusable agents (like a Laravel agent class). Only
instructions is required; override the rest for context, tools, or model
config.
use elyra::ai::{Agent, Message, Provider, Tool};
struct SalesCoach { history: Vec<Message> }
impl Agent for SalesCoach {
fn instructions(&self) -> String {
"You are a sales coach. Give concise, actionable feedback.".into()
}
fn messages(&self) -> Vec<Message> { self.history.clone() }
fn provider(&self) -> Option<Provider> { Some(Provider::Anthropic) }
fn max_steps(&self) -> u32 { 6 }
}
let resp = ai.prompt(&SalesCoach { history: vec![] }, "Analyze this transcript…").await?;
Tools
Implement [Tool] — a name, description, a JSON-Schema for the parameters,
and call. The SDK runs the tool loop automatically (up to max_steps).
use elyra::ai::{async_trait, json, Result, Tool, Value};
struct RandomNumber;
#[async_trait]
impl Tool for RandomNumber {
fn name(&self) -> String { "random_number".into() }
fn description(&self) -> String { "Generate a random integer in [min, max].".into() }
fn parameters(&self) -> Value {
json!({
"type": "object",
"properties": {
"min": { "type": "integer" },
"max": { "type": "integer" }
},
"required": ["min", "max"]
})
}
async fn call(&self, args: Value) -> Result<String> {
let min = args["min"].as_i64().unwrap_or(0);
let max = args["max"].as_i64().unwrap_or(100);
Ok(((min + max) / 2).to_string())
}
}
let reply = ai.chat()
.instructions("Use tools when useful.")
.tool(RandomNumber)
.prompt("Pick a number between 1 and 10.")
.await?;
Sub-agents
Delegate to a specialized agent by adding it as a sub-agent — an [Agent]
used as a tool. The delegate runs in isolation (it does not see the parent's
history), exactly like Laravel's sub-agents. Override name/description so the
parent knows when to call it.
use elyra::ai::{Agent, Provider};
struct RefundsAgent;
impl Agent for RefundsAgent {
fn instructions(&self) -> String {
"You are a refunds specialist. Give concise eligibility guidance.".into()
}
fn name(&self) -> String { "refunds_specialist".into() }
fn description(&self) -> String { "Answer refund eligibility questions.".into() }
fn provider(&self) -> Option<Provider> { Some(Provider::Anthropic) }
}
let reply = ai.chat()
.instructions("You help customers. Delegate refund questions to the specialist.")
.sub_agent(RefundsAgent)
.prompt("Can I return an item I bought 40 days ago?")
.await?;
Sub-agents can have their own tools and sub-agents, composing into a hierarchy. For full control over the tool name/description at the call site, build the wrapper directly:
use elyra::ai::AgentTool;
let tool = AgentTool::new(&ai, RefundsAgent)
.with_name("refunds")
.with_description("Refund policy expert.");
Provider tools (web search / fetch)
Provider tools are executed by the AI provider, not your app (unlike the
Tool trait above). They run server-side and the results are folded
into the answer.
Web search runs on Anthropic and OpenAI; web fetch and code execution on Anthropic only. On OpenAI, a chat with web search goes through its Responses API (RFC 0049), with the app's tools and structured output as usual, so a search can fail over between the two labs.
WebSearch::allowandlocationcarry over;blockis anUnsupportederror there (OpenAI's search has no blocked domains), andmaxis ignored, said once. Other providers returnUnsupportedfor every provider tool, and a streamed chat sends none. These paths are not live-tested here. Opus 4.6 and later and Sonnet 4.6 and later get the 2026-02-09 tools, which filter results before they reach the context; Haiku and older models get the basic ones. When a long search pauses the turn (pause_turn), the SDK sends it back and the server resumes it; each resume counts againstmax_steps.
use elyra::ai::{Provider, WebSearch, WebFetch, UserLocation};
let answer = ai.chat()
.provider(Provider::Anthropic)
.instructions("Answer with up-to-date facts and cite sources.")
.web_search(
WebSearch::new()
.max(5)
.allow(["rust-lang.org", "docs.rs"])
.location(UserLocation { country: Some("NO".into()), ..Default::default() }),
)
.prompt("What changed in the latest Rust release?")
.await?;
// Web fetch (retrieves a specific URL):
ai.chat()
.web_fetch(WebFetch::new().max(3).allow(["doc.rust-lang.org"]))
.prompt("Summarize https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html")
.await?;
Citations
An answer from a web search says which pages back which words
(RFC 0051). Response::citations() gives
them in the order they appear in the text, on Anthropic and OpenAI alike,
so a failover between the two gives the same shape:
let answer = ai.chat()
.web_search(WebSearch::new())
.prompt("What changed in the latest Rust release?")
.await?;
for c in answer.citations() {
// `span`: a byte range into `answer.text()`, the words this page backs.
println!("[{}] {} — {}", &answer.text()[c.span.clone()], c.title.as_deref().unwrap_or(""), c.url);
}
// Just the sources, each once, in the order first cited:
let mut sources: Vec<&str> = Vec::new();
for c in answer.citations() {
if !sources.contains(&c.url.as_str()) {
sources.push(&c.url);
}
}
url,title,cited_text,span.cited_textis the quote from the page, and only Anthropic sends it. Several pages can back the same span, and one page can back several spans.- Anthropic cites per text block, so a span is a whole block.
OpenAI gives character positions, which are read as
chars with an exclusive end and clamped to the text. This reading has not been checked live yet;ai/tests/live.rschecks it when run. - Empty without web search, on other providers, from the cache, and
in
Chat::stream, which sends no provider tools. A prompt withon_texthas them. CitationderivesSerialize, so a command can return it to the page. Web fetch citations aren't read.
Code execution (tools called from code)
code_execution() lets the model write Python that runs in Anthropic's
sandbox and calls your tools from it: programmatic tool calling.
A tool opts in with callable_from_code(); each call pauses the code, runs
in your app like any tool call, and its result goes back to the code, not
to the model's context. Only what the code prints reaches the model, so a
loop over 200 records is one turn, not 200.
use elyra::ai::{CodeEvent, Tool};
struct InvoicesShow;
#[elyra::ai::async_trait]
impl Tool for InvoicesShow {
fn name(&self) -> String { "invoices_show".into() }
fn description(&self) -> String { "One invoice by id.".into() }
fn parameters(&self) -> serde_json::Value { serde_json::json!({"type": "object", "properties": {"id": {"type": "integer"}}}) }
async fn call(&self, args: serde_json::Value) -> elyra::ai::Result<String> { /* … */ Ok("{}".into()) }
fn callable_from_code(&self) -> bool { true } // sent as `allowed_callers`
}
let answer = ai.chat()
.code_execution()
.tool(InvoicesShow)
.on_code(|event| if let CodeEvent::Started { code, .. } = event { println!("{code}") })
.prompt("Total invoices 1 to 50")
.await?;
- A call from code to a tool that isn't
callable_from_codeis refused to the code and never runs, whatever the model sent:allowed_callersguides the model, it isn't a guard. - The code's container is kept through the prompt. A pause for calls from
code isn't one of
max_steps; a prompt makes at most 500 calls from code. - Where the data goes: the results of code's calls go to Anthropic's code execution container, kept up to 30 days, and code execution isn't eligible for zero data retention. Anthropic only. Not live-tested here.
- The app's assistant uses it with
code_mode().
Structured output
Return typed JSON with prompt_as::<T>(), where T derives serde::Deserialize
and schemars::JsonSchema. The model answers JSON matching T's schema, and
the SDK deserializes it. With Anthropic this is structured outputs
(output_config.format), so the agent's tools still run first; with OpenAI the
model is forced to call a synthetic tool.
use elyra::ai::JsonSchema;
#[derive(serde::Deserialize, JsonSchema)]
struct Sentiment {
label: String, // positive | negative | neutral
score: i32, // 1–10
}
let s: Sentiment = ai.chat()
.instructions("Classify the sentiment.")
.prompt_as("I love building with Elyra!")
.await?;
Anthropic accepts a subset of JSON Schema: the SDK closes every object
(additionalProperties: false) and moves what it refuses (number and length
bounds such as the minimum schemars gives an unsigned integer, and formats
other than dates, times, emails, hostnames, URIs, IPs and UUIDs) into the
field's description, where the model still reads it. Recursive types aren't
supported.
Streaming
Stream a plain-text answer token-by-token with stream(input) — ideal for
piping to the event bus so the UI paints as tokens arrive. Tools
and structured output are not used in streaming mode; for those, see
with tools.
use elyra::ai::StreamChunk;
let mut chunks = ai.chat().instructions("Be brief.").stream("Explain lifetimes.");
while let Some(chunk) = chunks.next().await {
match chunk? {
StreamChunk::Delta(text) => print!("{text}"),
StreamChunk::Done(usage) => eprintln!("\n{usage:?}"),
}
}
// or: let full = ai.chat().stream("…").collect_text().await?;
Streaming to the frontend
Emit each delta on a channel and subscribe in Svelte:
#[command]
async fn ask_stream(ctx: Ctx, prompt: String) -> Result<(), String> {
use elyra::ai::StreamChunk;
let bus = ctx.get::<EventBus>();
let mut chunks = ctx.get::<Ai>().chat().stream(prompt);
while let Some(chunk) = chunks.next().await {
if let StreamChunk::Delta(text) = chunk.map_err(|e| e.to_string())? {
let _ = bus.emit("elyra:ai", &text);
}
}
Ok(())
}
import { channel, api } from "@elyra/runtime";
let answer = "";
channel<string>("elyra:ai").subscribe((delta) => { if (delta) answer += delta; });
await api.ask_stream("Explain lifetimes.");
Streaming with tools
on_text(|step, piece| ..) streams a prompt that uses tools: each piece of
text as it's written, in each step, while prompt runs the tool loop and
returns the whole response as usual. step is 0, then one more after each
tool step, so the text before a tool ("Let me check.") can be told apart
from the answer. The app's assistant uses it.
let reply = ai.chat()
.tool(Weather)
.on_text(move |step, piece| { let _ = bus.emit("elyra:ai", &(step, piece)); })
.prompt("Weather in Oslo?")
.await?;
With Anthropic each step is streamed over SSE. A gateway that answers whole
is told each step's text at once, and OpenAI answers whole, once.
AiFake tells its script a word at a time (.pace(..) spreads them out),
and tool_call_saying(text, ..) says something before a tool step.
Images
let image = ai.image("A donut on a kitchen counter, warm light")
.landscape() // or .portrait() / .square() / .size("1024x1024")
.quality("high")
.generate()
.await?;
image.save("donut.png")?; // or image.bytes()
Audio (text-to-speech & transcription)
OpenAI text-to-speech and speech-to-text.
// TTS
let audio = ai.speech("I love building with Elyra.")
.female() // or .male() / .voice("onyx")
.instructions("Warm and upbeat.")
.format("mp3")
.generate()
.await?;
audio.save("hello.mp3")?; // or audio.bytes()
// STT (transcription)
let bytes = std::fs::read("hello.mp3").map_err(|e| e.to_string())?;
let text = ai.transcribe(bytes, "hello.mp3")
.language("en")
.generate()
.await?;
Defaults: TTS gpt-4o-mini-tts, transcription whisper-1 (override with
AiBuilder::tts_model / transcribe_model).
Embeddings
let vectors = ai.embeddings(["Napa Valley has great wine.", "Elyra is a Rust framework."])
.dimensions(1536)
.generate()
.await?; // Vec<Vec<f32>>
Retrieval (RAG)
A portable, in-memory [VectorStore] ranks embeddings by cosine similarity in
Rust. Elyra's database layer uses the sqlx Any driver, which has no native
vector type (no pgvector), so ranking happens in-process — a good fit for the
small-to-medium corpora typical of desktop apps.
use elyra::ai::VectorStore;
let mut store = VectorStore::new();
store.add_texts(&ai, vec![
("Napa Valley is famous for wine.", 1u32), // payload = row id
("Rust has a strong ownership model.", 2u32),
("Elyra is a Rust + Svelte framework.", 3u32),
]).await?;
let hits = store.search_text(&ai, "best wineries", 3).await?;
for hit in &hits {
println!("{:.3} id={}", hit.score, hit.payload);
}
Feed the top hits into a prompt as context:
let context = hits.iter().map(|h| h.payload.to_string()).collect::<Vec<_>>().join("\n");
let answer = ai.chat()
.instructions(format!("Answer using only this context:\n{context}"))
.prompt("Where should I taste wine?")
.await?;
Persisting embeddings
Store each embedding as a JSON/text column and rebuild the store per query (or keep it warm in the container):
// migration: add `embedding TEXT` to your documents table
let json = serde_json::to_string(&embedding)?; // Vec<f32> -> text
// on load:
let embedding: Vec<f32> = serde_json::from_str(&row_json)?;
store.add(embedding, row_id);
Use [cosine_similarity] directly if you rank rows yourself.
Reliability (retries, failover, caching)
Retries are on by default: transient failures (timeouts, connection errors) and retryable statuses (429, 5xx, 529) are retried with exponential backoff (capped at 8s). Configure on the client:
use std::time::Duration;
let ai = Ai::builder()
.retries(3) // default 2; 0 disables
.retry_backoff(Duration::from_millis(400)) // base; doubles each attempt
.build();
Failover tries other providers (in order) if the primary fails after its
retries. Each fallback gets its own model (text_model_for, then
text_model, then its default); a fallback without one is skipped, and the
primary's error is the one returned:
use elyra::ai::Provider;
let reply = ai.chat()
.provider(Provider::Anthropic)
.failover([Provider::OpenAI])
.prompt("Summarize the meeting notes…")
.await?;
Caching memoizes plain prompts (no tools / provider tools) in-process, keyed by provider + model + full conversation:
let ai = Ai::builder()
.cache(true) // or .cache_ttl(Duration::from_secs(3600))
.build();
// identical prompts now skip the network; ai.clear_cache() empties it.
Cached hits report zero token usage. Requests that use tools or provider tools are never cached (they may have side effects).
Testing with a fake
Ai::fake(AiFake) answers prompts and streams from a script: no network, no
key. Each step takes the next reply. Text ends the run, and a tool call runs
the agent's real tool and goes on with its result, as a provider would.
use elyra::ai::{Ai, AiFake};
let fake = AiFake::new()
.tool_call("weather", json!({ "city": "Oslo" }))
.text("It's sunny in Oslo.");
let reply = Ai::fake(fake.clone()).chat().tool(Weather).prompt("Oslo?").await?;
assert_eq!(fake.calls()[0].output, "Sunny in Oslo"); // what the tool answered
assert_eq!(fake.requests()[0].tools, ["weather"]); // what each step was sent
assert!(fake.is_spent());
.text(..)(the JSON, for structured output),.tool_call(name, input),.tool_calls([..])for several in one turn,.text_citing(text, [Citation::new(url, span)])for a web-search answer with its sources (each span checked against the text),.refusal(..)and.error(status, message)..usage(input, output)sets what the last reply reports, which counts against atoken_budget.- A stream gets the text a word at a time, then
Donewith the usage. - A run that needs a reply the script doesn't have panics, naming the step.
Ai::builder().fake(..)keeps the rest of a configuration (a budget, a cache). In an app, swap it in:App::new().swap(Ai::fake(fake.clone())). Images, embeddings and audio aren't faked.
Verification status
The SDK compiles, is clippy-clean, and has offline tests (provider metadata,
builder, message helpers, and what the Anthropic driver sends and reads,
against a local server: ai/tests/anthropic.rs; the OpenAI-shaped
providers' URLs, auth, a tool round trip, a stream and failover:
ai/tests/providers.rs; web search on OpenAI: ai/tests/openai_responses.rs;
citations on both labs: ai/tests/citations.rs; the fake: ai/tests/fake.rs). The live provider calls are exercised
only when ELYRA_AI_LIVE=1 and the relevant key are set (ai/tests/live.rs) —
they make real, paid API calls and are skipped on pushes, pull requests and by
default.
The Live AI workflow (.github/workflows/live-ai.yml) runs them weekly
and by hand (Actions → Live AI → Run workflow), with the code execution
test. Each provider runs when its key is a repository secret
(ANTHROPIC_API_KEY, OPENAI_API_KEY, GEMINI_API_KEY, …). The providers
without a default model also need it as a repository variable
(GEMINI_MODEL, …). The job summary lists what ran, what was skipped, and
the citations each web search gave. An empty key or model counts as unset.
Related
- Commands · Container & providers
- Events — stream tokens/progress to the frontend.