Rust

Agents

AI agents on LLM providers: conversations, messages with image attachments, structured output schemas, streamed responses, token accounting, embeddings, and diff checks.
Rust 5,651 lines (3,542 code)split
PartCodeCommentsBlankTotalFiles
Rust source3,5421,5285815,65124
Rust tests1501161

Comments include doc comments. Rust tests are tests/ and #[cfg(test)] modules.

Install#

The crate lives in the Appwrite repository; depend on it from Git.

Cargo.toml
[dependencies]
utopia-agents = { git = "https://github.com/appwrite/appwrite" }

Getting started#

Common tasks with Agents, each a complete program you can copy and run.

Utopia Agents talks to AI providers. An Agent wraps a provider adapter (OpenAI, Anthropic, Gemini, Deepseek, OpenRouter, Perplexity, xAI, or the Ollama and Appwrite embedding services) with a description and instructions; a Conversation sends it messages and keeps the answers. This guide covers the common tasks. Its examples answer from a canned client instead of a provider, the way tests do: pass a client to any adapter with with_client (PHP: the constructor's $client).

Ask an agent a question

Give the agent a description and instructions, add the user's message to a conversation and send it. The answer is added to the conversation as the assistant's message, and the tokens the provider reported are counted.

Rust
use std::sync::Arc;
use utopia_agents::{Agent, BoxFuture, Conversation, Message, OpenAi, Transport, User};
use utopia_client::{Request, Response};

/// Answers every streamed request with the same server-sent events.
struct Canned(&'static str);

impl Transport for Canned {
    fn send(&self, _request: Request) -> BoxFuture<'_, Result<Response, utopia_client::Error>> {
        Box::pin(async { Response::new(200) })
    }

    fn stream<'a>(
        &'a self,
        _request: Request,
        sink: &'a mut (dyn FnMut(&[u8]) + Send),
    ) -> BoxFuture<'a, Result<Response, utopia_client::Error>> {
        Box::pin(async move {
            sink(self.0.as_bytes());
            Response::new(200)
        })
    }
}

let stream = "data: {\"choices\":[{\"delta\":{\"content\":\"Appwrite is an open-source backend.\"}}]}\n\ndata: [DONE]\n\n";
let adapter = OpenAi::new("sk-test").with_client(Arc::new(Canned(stream)));

let mut agent = Agent::new(adapter);
agent.set_description("You answer questions about Appwrite.").add_instruction("Tone", "Be brief.");

let mut conversation = Conversation::new(agent);
conversation.message(&User::new("user-1", "Ada"), Message::new("What is Appwrite?"), Vec::new())?;
let answer = conversation.send().await?;

assert_eq!(answer.text(), "Appwrite is an open-source backend.");
assert_eq!(conversation.messages().len(), 2);
assert_eq!(conversation.messages()[1].role(), "assistant");

Stream the answer as it arrives

A listener gets each token of a streamed answer as it is parsed, however the response is cut into chunks on the way.

Rust
use std::sync::{Arc, Mutex};
use utopia_agents::{Agent, BoxFuture, Conversation, Message, Anthropic, Transport, User};
use utopia_client::{Request, Response};

// Two text deltas, split mid-event across three chunks.
let client = Arc::new(Chunks(vec![
    "data: {\"type\":\"content_block_delta\",\"delta\":{\"type\":\"text_",
    "delta\",\"text\":\"Hello\"}}\ndata: {\"type\":\"content_block_delta\",",
    "\"delta\":{\"type\":\"text_delta\",\"text\":\" there\"}}\n",
]));
let mut conversation = Conversation::new(Agent::new(Anthropic::new("sk-test").with_client(client)));

let tokens = Arc::new(Mutex::new(Vec::new()));
let seen = Arc::clone(&tokens);
conversation.listen(move |token: &str| seen.lock().unwrap().push(token.to_owned()));
conversation.message(&User::new("user-1", ""), Message::new("Hi"), Vec::new())?;
conversation.send().await?;

assert_eq!(*tokens.lock().unwrap(), ["Hello", " there"]);

Ask for structured output

A schema makes the agent answer with a JSON object of the given properties. Adapters without structured output refuse it.

Rust
use utopia_agents::{Agent, OpenAi, Schema, SchemaObject, Xai, property};

let mut object = SchemaObject::default();
object.add_property("location", property("string", "The city and state"))?;
object.add_property("unit", property("string", "celsius or fahrenheit"))?;
let schema = Schema::new("get_weather", "The weather in a city", object, vec!["location".into(), "unit".into()]);

let mut agent = Agent::new(OpenAi::new("sk-test"));
agent.set_schema(schema.clone())?;
assert_eq!(agent.schema().map(Schema::name), Some("get_weather"));

let error = Agent::new(Xai::new("sk-test")).set_schema(schema).err().unwrap();
assert_eq!(error.to_string(), "Schema is not supported for this model");

Attach an image

Attachments are messages whose content is the file. The adapter's limits are checked as the message is added: OpenAI, Anthropic, Gemini and Deepseek take up to ten PNG, JPEG, WebP or GIF images of 5 MB each, 20 MB in all.

Rust
use utopia_agents::{Agent, Conversation, Gemini, Message, User};

let png = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR\0\0\0\x01\0\0\0\x01\x08\x06\0\0\0".to_vec();
let mut conversation = Conversation::new(Agent::new(Gemini::new("test-api-key")));
let user = User::new("user-1", "");

conversation.message(&user, Message::new("What is in this image?"), vec![Message::new(png)])?;
assert_eq!(conversation.messages()[0].attachments()[0].mime_type(), Some("image/png"));

let refused = conversation.message(&user, Message::new("And this?"), vec![Message::new("%PDF-1.4 ...")]);
assert_eq!(refused.err().unwrap().to_string(), "Attachment MIME type is not allowed");

Embed texts

Embedding adapters turn text into vectors. Ollama embeds one text per request; Appwrite's embedding service takes several at once.

Rust
use std::sync::Arc;
use utopia_agents::{Adapter, Agent, BoxFuture, Ollama, Transport};
use utopia_client::{Request, Response};

let body = "{\"embeddings\":[[0.25,-0.5,0.125]],\"prompt_eval_count\":4,\"total_duration\":81000}";
let mut agent = Agent::new(Ollama::new().with_client(Arc::new(Json(body))));

let result = agent.embed("Hello world").await?;
assert_eq!(result.embedding.len(), 3);
assert_eq!(result.tokens_processed, Some(4));
assert_eq!(agent.adapter().embedding_dimension()?, 768);

Ask about a change between two versions

DiffCheck copies two directories (or clones two Git URLs), compares them with git diff, and asks the agent about the difference only when there is one. Placeholders in the prompt receive the diff, the two sources and the diff's size.

Rust
use utopia_agents::{DiffCheck, OpenAi};
use utopia_agents::diff_check::{Options, Runner};

let mut adapter = OpenAi::new("sk-...");
let mut options = Options::default();
options.set_exclude_paths(&[".github", "docs/**"]).set_max_diff_lines(300)?;

let outcome = DiffCheck::new()
    .run(Runner::Adapter(&mut adapter), "/srv/sdk-1.0", "/srv/sdk-1.1", "Summarize ({{diff_stats}}):\n{{diff}}", &options)
    .await?;
if outcome.has_changes {
    println!("{}", String::from_utf8_lossy(&outcome.response));
}
Compiles in CI; needs a running service to execute.

Reference#

AI agents on LLM providers: an Agent (a provider Adapter with a description, instructions and an optional Schema for structured output) holds Conversations of Messages, which may carry image attachments. Answers stream token by token to a listener, and tokens are counted by kind (Usage). Embedding adapters turn texts into vectors. DiffCheck asks an agent about the difference between two versions of a repository.

Adapters: OpenAi, Anthropic, Gemini, Deepseek, OpenRouter (with its generated model catalog), Perplexity, Xai, and the embedding adapters Ollama and Appwrite. They send JSON over utopia-client (a keep-alive client built on first use, or the Transport given), and parse server-sent events split anywhere across chunks.

Rust
use utopia_agents::{Agent, Conversation, Message, OpenAi, User};

let mut agent = Agent::new(OpenAi::new("sk-..."));
agent.set_description("You are a helpful assistant.");

let mut conversation = Conversation::new(agent);
conversation.message(&User::new("user-1", ""), Message::new("What is Appwrite?"), Vec::new())?;
let answer = conversation.send().await?;
println!("{}", answer.text());
Compiles in CI; needs a running service to execute.

Modules#

Each module groups one concept of the library. Internal ones hold items the crate re-exports at its root.

adapter9 items
The provider interface every adapter implements, the state they share (token counts, timeout, HTTP client, stream buffer) and the HTTP client interface requests go through.
adapters::anthropic11 items
Anthropic.
adapters::appwrite8 items
Appwrite's embedding service.
adapters::chatinternal
The OpenAI chat completions protocol, which OpenAI, OpenRouter, Perplexity and xAI speak, each with its own differences (`Dialect`).
adapters::deepseek5 items
Deepseek.
adapters::gemini8 items
Google Gemini.
adapters0 items
The provider adapters.
adapters::ollama5 items
Ollama (embeddings).
adapters::openai10 items
OpenAI.
adapters::openrouter2 items
OpenRouter.
adapters::openrouter::models0 items
OpenRouter's model catalog: a named constant per model of the curated providers (Anthropic, OpenAI, Google, Meta, Deepseek, Mistral, xAI) and `MODELS`(models::MODELS), every model id, generated from `data/openrouter-constants.txt` and `data/openrouter-models.txt`, which the `agents-sync-openrouter-models` task refreshes.
adapters::perplexity8 items
Perplexity.
adapters::xai6 items
xAI.
agentinternal
Agents: an adapter with a description, instructions and a schema.
conversationinternal
Conversations: the messages exchanged with an agent.
diff_check6 items
Asking an agent about the difference between two versions of a repository.
errorinternal
Undocumented.
messageinternal
Messages and their attachments.
mimeinternal
MIME type detection of message content.
phpinternal
Undocumented.
roleinternal
Who takes part in a conversation.
schema4 items
Structured output: the JSON Schema an agent's answers must follow.
schema::types7 items
A JSON Schema type a property may have.

API#

What utopia_agents exports at its root.

Structs

AgentAn AI agent: a provider adapter, with a description, instructions and optionally a schema its answers must follow.AnthropicAnthropic's Messages API: answers streamed token by token, with token usage (prompt cache writes and reads included) counted from the stream's events; with a schema, a forced tool call whose input is the answer. The description and the first instructions (four blocks in all) are marked for prompt caching. Images attach as base64 sources.AppwriteEmbeddings from Appwrite's embedding service (no API key), several texts per request. It does not chat: `Adapter::send` fails.BaseThe state every adapter keeps: token counts, the request timeout, the HTTP client, and the fragment of a streamed line still incomplete.ConversationA conversation with an agent: messages added in order, sent together, the answer added as the assistant's, and the tokens every send used.DeepseekDeepseek's chat completions, always streamed, with token usage counted from the stream. Messages without a role or any text or image are left out. With a schema, the answer is asked for in JSON mode and the schema is described in the system message (`Schema::to_json`(crate::Schema::to_json)).DiffCheckCompares two versions of a repository with `git diff` and asks an agent about the difference.EmbeddingAn embedding of one text.EmbeddingsEmbeddings of several texts, in order.GeminiGoogle's Gemini API: answers always streamed (server-sent events), the description and instructions as the system instruction, the assistant's messages as the `model` role, images inline. No structured output.MessageOne message of a conversation: who sent it (its role), its content, and the messages attached to it (images, as their raw bytes).OllamaEmbeddings from a local Ollama service (no API key). It does not chat: `Adapter::send` fails.OpenAiOpenAI's chat completions: answers streamed token by token, or, with a schema, a JSON answer in strict `json_schema` mode. Images attach as data URLs. `gpt-5-nano` only takes temperature 1 (another is replaced, with a warning on standard error), and the o-series and `gpt-5-nano` take `max_completion_tokens` instead of `max_tokens`.OpenRouterOpenRouter's OpenAI-compatible chat completions, routed to any provider's model (`meta-llama/llama-3.3-70b-instruct`). Structured output is not offered: not every routed model supports it. The routed model's provider prefix and `:` suffix are ignored when choosing the token limit parameter and temperature (`openai/gpt-5-nano:free` is treated as `gpt-5-nano`). An app URL and title, when given, go in the `HTTP-Referer` and `X-Title` headers.PerplexityPerplexity's OpenAI-compatible chat completions. An HTML error page in the stream (an authorization failure) becomes `(http_<status>) <reason>` from its title or first heading.ProfileWhat an agent tells its provider besides the conversation: a description, named instructions and, for structured output, a schema. Adapters read it in `Adapter::send`.SchemaA named JSON Schema the agent's answer must follow: an object whose properties and required names are given.SchemaObjectUndocumented.UsageTokens counted so far, by kind.XaixAI's OpenAI-compatible chat completions, without structured output. Errors read `{"code": ..., "error": "..."}`.

Commands#

Programs the crate ships besides its API. Run them with cargo from the repository root.

agents-sync-openrouter-models

sync-openrouter-models

Refreshes the OpenRouter model catalog the crate embeds (adapters::openrouter::models) from OpenRouter's model list: data/openrouter-models.txt, every model id sorted, and data/openrouter-constants.txt, a named constant per model of the curated providers.

Shell
cargo run -p utopia-agents --bin agents-sync-openrouter-models
cargo run -p utopia-agents --bin agents-sync-openrouter-models -- /tmp/catalog

Models without a string id are dropped and the rest sorted by id. The curated providers (anthropic, openai, google, meta-llama, deepseek, mistralai, x-ai) get a constant named after the id (openai/gpt-4o is MODEL_OPENAI_GPT_4O), except date-pinned snapshots and :extended, :free, :beta, preview, GPT-3.5 and GPT-4 Turbo variants; a name taken twice gets the first eight hex digits of the id's SHA-1 appended. Rebuild the crate after a sync: the catalog is embedded at compile time.

Arguments

[output-path]

the directory the two data files are written to, created when missing (default: the crate's data/).

Environment

OPENROUTER_MODELS_ENDPOINT

where the catalog is fetched from (default https://openrouter.ai/api/v1/models).

OPENROUTER_API_KEY

, else LLM_KEY_OPENROUTER: sent as a bearer token when set.

Exit codes

0

written (Wrote <n> named constants + <m> model IDs to <path>).

1

the catalog could not be fetched, has no data array, or has no model; the reason is on standard error.

Writes

  • crates/utopia/agents/data/openrouter-constants.txt
  • crates/utopia/agents/data/openrouter-models.txt

The crate embeds these files when it is compiled: rebuild after running the task.