AgentAI is a Rust library designed to simplify the creation of AI agents. It leverages the GenAI library to interface with a wide range of popular Large Language Models (LLMs), making it versatile and powerful. Written in Rust, AgentAI benefits from strong static typing and robust error handling, ensuring reliable and maintainable code. Whether you're developing simple or complex AI agents, AgentAI provides a streamlined and efficient development process.
This library is under heavy development. The interface may change at any time without notice.
- Connect to any major LLM provider: Support for OpenAI, Anthropic, Gemini, Ollama, and other OpenAI-compatible APIs.
- Choose the right model for the job: Flexibly select the best-suited model for each step in your agent's workflow.
- Build custom tools with ease: A simple interface for creating and managing your own tools using the
ToolBox. - MCP Server Support, local and remote: Use tools from any Model Context Protocol server, whether you start it locally over stdio or connect to a running or hosted server over Streamable HTTP (with optional bearer token). Built on the official MCP Rust SDK.
- Structured Output: No need to parse raw text from model, just provide structure, and AI agent will provide response in defined format.
- Streaming: Show the answer as the model writes it, together with the tool calls the agent makes. The stream is
Send + 'static, ready for spawned tasks and server-sent events. - Images for vision models: Send text and images together in a
Prompt, by URL or from bytes. Plain text prompts work as before. - Image generation and editing: The
agentai-imagecrate gives the agent tools to draw and edit images (OpenAI and compatible APIs). Tools can return images to the model withToolOutput. - Speech, voice cloning and voice design: The
agentai-audiocrate gives the agent tools to speak texts (OpenAI and compatible APIs, ElevenLabs, Fish Audio, oMLX), including dialogues of several voices, and clones or designs voices from your code. - Video generation: The
agentai-videocrate submits video jobs, follows them and downloads the result (comfy-serve, OpenRouter), from text, frames or reference files. - Background tools: A tool can start slow work in the background and answer at once; the agent tells the model when the work is done.
- Cost and context control: Cap the dollar cost of runs with a budget, and trim images and reasoning from what is sent to the model with history processors.
- You own the conversation: An agent is shareable configuration. You keep the history, decide what to store, trim or persist, and get token usage and the stop reason from every run.
- Thinking survives the final answer: on models with thinking (Anthropic adaptive or extended
thinking), the last message of
AgentResult::new_messagesnow holds the thinking blocks with their signatures before the text, inrunandrun_streamalike. The next run sends them back, so the model keeps the thinking of its last turn. Before, that message held only the text. If you addedresult.reasoning_contentto it yourself, stop: it is there already, and a copy without a signature cannot be sent back to Anthropic.
- Design a voice in a language: in
agentai-audio,design_voice(description).with_language("pl")sends the language to Fish Audio and oMLX (ElevenLabs has no such setting).VoicePreview::languageis the language of a preview, and keeping it withcreate_voicestores it with the voice. - Voices know their language:
StoredVoice::language(with_language) andVoiceInfo::language, filled from the store, Fish Audio model languages and ElevenLabs labels.
Breaking changes: VoiceSource::Samples has a language field and is #[non_exhaustive]; match it
with .. and build it with VoiceSource::samples(..). Read the
CHANGELOG and the
migration guide
before upgrading.
- Set the speaking speed of a dialogue: in
agentai-audio,generate_dialogue(turns).with_speed(1.5)speaks every turn at that speed (Fish Audioprosody). ElevenLabs dialogues have no speed setting and returnUnsupported.
- Dialogues as turns: in
agentai-audio,generator.generate_dialogue([DialogueTurn::new(voice, text), ..]).awaitspeaks a dialogue of several voices as one audio, with Fish Audio (drama-3,s2-pro, ...) and now also ElevenLabs (eleven_v3,eleven_v4). Each turn is plain text: you no longer write<|speaker:N|>tags. - Fish Audio speaks every turn in the right voice: a dialogue whose voices came from a
VoiceStoresent both the store IDs and the samples, so the server could speak turns in the wrong voice. Now a request sends samples when all its voices are in the store and voice model IDs when none are; a mix fails withInvalidRequestbefore anything is sent. - One model per engine: a provider speaks with its speech model, speaks dialogues with the model set
by
with_dialogue_modeland designs voices with the one set bywith_design_model(for example Fish Audiovoice-design-1, ElevenLabseleven_ttv_v3). An engine without a model is off and returnsMissingModelwithout a request;with_modelon a call overrides the model for that call. - Calls are builders:
generate(text).with_voice(id).with_instructions(..).await, anddesign_voice(description).with_text(..).with_count(n).await. - Choosing a provider:
speech_provider("fishaudio", "s2-pro")(orSpeechProviderKind::FishAudio.builder(..)) builds a provider with its keys from the environment orwith_api_key/with_base_url, andSpeechProviderKind::known_models()lists the models this crate knows with what each can do (speech, dialogue, voice design), for example for a model picker. - Where a voice comes from:
VoiceInfo::originisPreset,AccountorStore, so a voice picker can show the account voices and theVoiceStorevoices of Fish Audio in separate sections. - Voice previews:
VoiceInfo::previewis a recording to play: the ElevenLabspreview_url, the first sample of a Fish Audio voice model (when its server gives a full URL) or the sample of aVoiceStorevoice. Thelist_voicestool never sends it to the model.
Breaking changes (all in agentai-audio; released as a patch while the audio interface is reworked):
SpeechGenerator::new takes a provider from speech_provider(..).build()?, generate_with and
SpeechRequest::new are replaced by the generate(..) builder, the generator defaults
(with_default_voice, with_format, with_speed, with_language) and SpeechRequest::with_voices
are removed, design_voice is a builder that needs a design model, Voice is replaced by VoiceId (a
String), provider::from_model and provider::list_models are replaced by speech_provider and
SpeechProviderKind::known_models, AudioModel lost its model field, and VoiceInfo::cloned is
replaced by origin. Read the
CHANGELOG and the
migration guide
before upgrading.
- Design voices from a description:
SpeechGenerator::design_voice(description, text, count)inagentai-audioreturnsVoicePreviews to listen to, andcreate_voicekeeps one as a voice you use withVoice::id. Fish Audio, ElevenLabs and oMLX can design voices;supports_voice_design()tells whether yours can. The newdesign_voiceexample shows the whole flow. - Cloning and designing share
create_voice: it takes aVoiceSource, eitherVoiceSource::samples(samples, transcript)or a preview fromdesign_voice.
Breaking changes: a voice is always an ID (voices given as a description, and the description flag of the
list_voices tool, are removed), and create_voice takes a VoiceSource.
Read the CHANGELOG and the
migration guide
before upgrading.
- Tools that run in the background: a tool returns
ToolReturn::deferred(message, future)for slow work. The model gets the message and a task ID at once and the run goes on; when the task finishes, the agent tells the model in a user message, in the same run or in a later one that gets the unfinished tasks withwith_deferred_tasks(result.deferred_tasks). With thetokiofeature,TokioDeferredTaskToolBoxspawns the tasks and gives the modellist_deferred_tasks,get_deferred_taskandwait_deferred_task. - Video generation: the new
agentai-videocrate hasfrom_model("comfy-serve::wan-2.2")?(oropenrouter::<model>), which gives aVideoProvider.submitreturns aVideoJob, you pollstatusuntilJobStatus::Completedanddownloadthe video as aMedia. AVideoJobis serializable, so you can store it and follow it after a restart.VideoRequesttakes text only, a first and/or last frame, or reference images, videos and audio (comfy-serve; OpenRouter takes images only).list_models("comfy-serve")returns the durations, resolutions, aspect ratios and inputs a model accepts, where the provider says so; comfy-serve jobs can be cancelled. - History processors:
Agent::with_history_processorchanges the messages right before every model call, while your history andnew_messagesstay complete.HistoryPruningreplaces images and drops reasoning from finished turns, so long conversations stop resending them; write your ownHistoryProcessoror pass a closure to trim or summarize. - Dollar budgets: with the
budgetfeature,Agent::with_budgetcharges every model call to a limit fromllm-budgetand stops the run withAgentError::Budgetwhen it is used up;AgentResult::cost_usdtells what a run cost. - Fish Audio and dialogues:
agentai-audiospeaks with Fish Audio (fishaudio::<model>). ASpeechRequesttakes several voices for dialogue models such asdrama-3, Fish Audio clones voices, andwith_timestamps(true)returns the time of every word. - Provider-specific options:
ChatOptions::with_extra_headerandwith_extra_bodysend headers and body fields thatagentaihas no setting for, such as Anthropic beta features. - File names and types:
agentai_core::mime(re-exported byagentai-image,agentai-audioandagentai-video) maps MIME types to file extensions and back, andMediagainsextension(),file_name(stem)andto_url()(a data URL for bytes). Generated images and audio keep the extension of their name only when it is a known file type, so an image namedmy.pictureis saved asmy.picture.png. - Internal:
agentai-coreHTTP requests now supportDELETEand JSON parts in multipart forms; the media crates share its MIME table, base64 helpers and aMockHttptest client (featuretest-support).
Breaking changes: ToolBox::call_tool returns ToolResult<ToolReturn> (#[toolbox] methods need no
change), an empty prompt returns AgentError::EmptyPrompt, SpeechRequest::voice in agentai-audio is
now voices, a list in speaker order, and in agentai-image and agentai-audio a file name keeps only a
known media extension. Read the
CHANGELOG and the
migration guide
before upgrading.
- Speech generation: the new
agentai-audiocrate hasSpeechGeneratorto speak texts from your code with OpenAI and compatible servers, ElevenLabs or oMLX.SpeechGenerator::new("elevenlabs::eleven_v4")?takes the provider from the model name. - Voice cloning:
create_voice(name, samples, transcript, description)clones a voice and returns an ID forVoice::id, the same call on ElevenLabs and oMLX. oMLX needs the transcript of the sample and aVoiceStoreset withwith_voice_store. - Agents that speak:
SpeechToolBoxgives a modelgenerate_speechandlist_voices;with_voiceslimits it to the voices you allow. Cloning stays in your code. - Internal:
agentai-corenow has the HTTP and media helpers thatagentai-imageandagentai-audioshare.
- Image generation and editing: the new
agentai-imagecrate hasImageGeneratorto make and edit images from your code:ImageGenerator::new("openai::gpt-image-1")?takes the provider from the model name and the key fromOPENAI_API_KEY; OpenAI-compatible servers work withOPENAI_BASE_URLor a base URL set in code, and OpenRouter models withopenrouter::<model>.provider::list_modelslists the image models a server offers. - Agents that draw:
GenerateImageToolBoxgives the agentgenerate_imageandedit_image. The model gets the image itself, or only its metadata as JSON to save tokens.ReadMediaToolBoxlets the model read any stored file by its ID. - Media storage:
MediaReadandMediaSave(inagentai-core) store images and other files under an ID; implement them for your blob store or directory, or useMemoryStorage. - Tools can return images: a tool returns a
ToolOutputwith text andMediaparts, for example a chart or a screenshot. For now every provider gets the images in a user message right after the tool results; a later release puts them in the tool result itself for Anthropic, Gemini, OpenAI Responses, Bedrock and Ollama.#[toolbox]methods returnToolResult<ToolOutput>for that; methods that return text stay as they are. - Tools see the call:
ToolBox::call_toolgets theToolCallwith itsid, the same id as in the tool result and the agent events, so a tool can tell parallel calls apart or report progress for one call. A#[toolbox]method gets it through a&ToolCallparameter, which the model does not see. - Fewer argument errors with local models: when a model sends an array or object argument as a JSON
string (
"tags": "[\"a\"]"),#[toolbox]tools now parse it instead of failing. Turn it off withparse_json_strings = falseon#[toolbox]or#[tool]. - TLS backend switches: pick
rustls-ring(the new default),rustls-aws-lcornative-tls, andsystem-proxy(on by default). The default build no longer compiles theaws-lc-sysC library. If you build your owngenai::Clientorreqwest::Client, calltls::install_crypto_providerfirst. - Internal: the new
agentai-corecrate holds the shared types (Message,Prompt,Media, still available fromagentaiunder the same paths) and the HTTP client abstraction used byagentai-image, so it can later run on other HTTP stacks, such as WebAssembly.
Breaking changes: ToolBox::call_tool takes a &ToolCall and returns ToolResult<ToolOutput>, and ToolResponse::content and
the content of tool result events are no longer a String. With default-features = false you must enable a
TLS feature, or HTTPS requests fail. Read the
CHANGELOG and the
migration guide
before upgrading.
- Streaming:
Agent::run_streamtakes the same configuration asAgent::run, and awaiting it returns a stream ofAgentEvents: text and reasoning as the model writes them, each tool call and its result, and finally the result of the run. Runs with tool calls and structured output stream too. The stream isSend + 'static, so you can spawn it or return it from a web handler. - You manage the history: the agent no longer keeps the conversation. Pass your history with
.with_history(&history)and add the run'snew_messagesto it when you want to continue:history.extend(result.new_messages). Store, trim, persist or reset it however you like:Messagehas its own stable JSON format. A failed or cancelled run never changes your history, and the system prompt is not part of it: the agent sends it with every request. - One agent, many conversations: the model and toolbox now belong to the agent
(
Agent::with_model,Agent::with_toolbox), and running takes&self, so one agent can be cloned cheaply and shared between tasks. Change the model, toolbox, iteration limit or options for a single run with thewith_*methods ofAgentRequestor a reusableRunOptions. - Run details: awaiting a run returns a
AgentResultwith the answer, token usage summed over all model calls, the stop reason, the model's reasoning and the number of model calls. An answer cut off by the token limit is reported asAgentError::MaxTokensinstead of a confusing parse error.
Breaking changes: agent.run(model, prompt, toolbox) is replaced by
agent.run(prompt).with_history(&history).await, which returns an AgentResult instead of the bare answer;
the model and toolbox are set with Agent::with_model and Agent::with_toolbox (or per run), and the agent
no longer remembers earlier runs. Agent::new_with_provider takes a Provider, and Agent::new_with_client
is removed. Follow the migration guide to upgrade from 0.2.0: it shows each change with before and
after code.
- Creating agents:
Agent::new_with_providerbinds an agent to any genai provider with an explicit API key, for example the native OpenRouter adapter, which needs no base URL:Agent::new_with_provider(AdapterKind::OpenRouter, None, &api_key, system)?.Agent::newandAgent::new_with_urlnow returnResult, and the agent reports typed errors (AgentError). Tool errors are either recoverable (sent back to the model, which can try again) or fatal (they stop the run). - Remote MCP servers, not only stdio:
McpToolBoxnow connects to MCP servers over Streamable HTTP, so agents can use running and hosted servers, including ones that need a bearer token (McpToolBox::new_http,McpToolBox::new_http_with_bearer). Starting a local server over stdio (McpToolBox::new) works as before. MCP support is now built onrmcp, the official MCP Rust SDK. - Agent configuration:
Agent::with_max_iterationsandAgent::with_chat_optionsset the loop limit and the model options (temperature, max tokens, tool choice, reasoning effort, ...). - Strict tools:
#[tool(strict)]marks a tool as strict, so providers that support it make the model's arguments match the parameter schema exactly. - Dependencies: genai 0.7 (re-exported as
agentai::genai; tool calls are no longer lost when a model also returns text), schemars 1, reqwest 0.13, syn 3, Rust edition 2024 and MSRV 1.88.
Breaking changes: Agent::new, Agent::new_with_url and Agent::run return AgentError instead of
anyhow errors, ToolError variants are renamed and split, Tool is built with Tool::new, and answer
and tool parameter types need schemars 1.x. Read the
CHANGELOG before upgrading: it lists
every breaking change and how to migrate.
This release introduces the ToolBox, a new feature providing an easy-to-use interface for supplying tools to AI agents.
We are continuously working to improve AgentAI. These are the next features we plan; the linked issues have the details:
- Agent Memory: control what the agent remembers between runs, such as persistence, record limits and context management.
- User input during a run: let an agent ask the user for more information or confirmation before it continues.
To add the AgentAI crate to your project, run the following command in your project's root directory:
cargo add agentaiThis command adds the crate and its dependencies to your project.
Available features for agentai crate.
To enable any of these features, you need to enter this command:
cargo add agentai -F mcp-clientFeatures list:
rustls-ring(enabled by default) — TLS with rustls and the ring crypto provider, checking certificates against the OS trust store. The library installs ring as the process-wide rustls provider when it builds a client; calltls::install_crypto_providerbefore you build your owngenai::Clientorreqwest::Client.rustls-aws-lc— TLS with rustls and the aws-lc-rs crypto provider (builds theaws-lc-sysC library).native-tls— TLS of the operating system (OpenSSL, SChannel or Security Framework). It cannot be combined with arustls-*feature: setdefault-features = false.system-proxy(enabled by default) — Reads the macOS and Windows system proxy settings. Proxy environment variables (HTTP_PROXY,HTTPS_PROXY,NO_PROXY) work without it.mcp-client(enabled by default) — Enables support for Agent Tools served by MCP servers (stdio and Streamable HTTP, viarmcp)tokio(enabled by default) — Enables tokio integrations, such asTokioDeferredTaskToolBoxand writing a stream to a tokio writer withAgentStream::print_to_tokiomacros(enabled by default) — Enables support for macro#[toolbox]tools-buildin(enabled by default) — Enables support for buildin toolstools-web(enabled by default) — Enables support for web toolsbudget— Enables dollar spend limits withllm-budget: every model call is charged to the budget set withAgent::with_budget
Here is a basic example of how to create an AI agent using AgentAI:
use agentai::{Agent, Message, AgentResult};
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let agent = Agent::new("gpt-4o", "You are a useful assistant")?;
// The conversation history is yours
let mut history: Vec<Message> = Vec::new();
let result: AgentResult<String> = agent.run("Why is the sky blue?").with_history(&history).await?;
println!("Answer: {}", result.answer);
// Keep the question and the answer to continue the conversation
history.extend(result.new_messages);
Ok(())
}Models that support images take a Prompt with text and images, by URL or from bytes:
use agentai::{Agent, AgentResult, Prompt};
let prompt = Prompt::text("Which of these logos is brighter?")
.with_image_url("https://example.com/logo.png")
.with_image_bytes("image/png", &png);
let result: AgentResult<String> = agent.run(prompt).await?;To show the answer while it is written, use run_stream with the same configuration and
write the stream to the console, a file or any other std::io::Write:
use agentai::{Agent, AgentResult};
let result: AgentResult<String> = agent
.run_stream("Why is the sky blue?")
.await?
.print_to(std::io::stdout())
.await?;For your own handling, read the [AgentEvent]s of the stream:
use agentai::{Agent, AgentEvent};
use futures_util::StreamExt;
let mut stream = agent.run_stream::<String>("Why is the sky blue?").await?;
while let Some(event) = stream.next().await {
match event? {
AgentEvent::TextDelta(text) => print!("{text}"),
AgentEvent::Finished(result) => println!("\n{} tokens", result.usage.total_tokens),
_ => {}
}
}A run returns an [AgentError] that you can match on. Provider failures that may
succeed on a second try report it with [AgentError::is_transient]. Your history is not
changed by a failed run, so you can simply try again:
use agentai::{Agent, AgentError};
match agent.run::<String>("Why is the sky blue?").await {
Ok(result) => println!("Answer: {}", result.answer),
Err(err) if err.is_transient() => println!("Try again later: {err}"),
Err(AgentError::InvalidAnswer { raw, .. }) => println!("Unexpected answer: {raw}"),
Err(err) => println!("Failed: {err}"),
}Tools report failures with ToolError. Recoverable errors
(NotFound, InvalidArguments, Failed) are sent to the model as the tool result and the
run continues. Fatal errors (Configuration, Fatal) stop the run with
[AgentError::Tool]. ToolError::is_recoverable
tells the two groups apart.
For more examples, check out the examples directory. To run an example, use the following command, replacing <example_name> with the name of the example file (without the .rs extension):
cargo run --example <example_name>For instance, to run the simple example:
cargo run --example simpleFull documentation is available on docs.rs.
Contributions are welcome! Please see our CONTRIBUTING.md for more details.
This project is licensed under the MIT License. See the LICENSE file for details.
Special thanks to the creators of the GenAI library for providing a robust framework for interfacing with various LLMs.