Skip to content

About

AgentAI is a Rust library designed to simplify the creation of AI agents

Resources

Contributing

Stars

176 stars

Watchers

3 watching

Forks

Repository files navigation

AgentAI logo

AgentAI

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.

Warning

This library is under heavy development. The interface may change at any time without notice.

Features

  • 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-image crate gives the agent tools to draw and edit images (OpenAI and compatible APIs). Tools can return images to the model with ToolOutput.
  • Speech, voice cloning and voice design: The agentai-audio crate 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-video crate 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.

What's New

0.7.5 - The final answer keeps its thinking

  • Thinking survives the final answer: on models with thinking (Anthropic adaptive or extended thinking), the last message of AgentResult::new_messages now holds the thinking blocks with their signatures before the text, in run and run_stream alike. 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 added result.reasoning_content to it yourself, stop: it is there already, and a copy without a signature cannot be sent back to Anthropic.

0.7.4 - Voice languages

  • 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::language is the language of a preview, and keeping it with create_voice stores it with the voice.
  • Voices know their language: StoredVoice::language (with_language) and VoiceInfo::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.

0.7.3 - Dialogue speed

  • Set the speaking speed of a dialogue: in agentai-audio, generate_dialogue(turns).with_speed(1.5) speaks every turn at that speed (Fish Audio prosody). ElevenLabs dialogues have no speed setting and return Unsupported.

0.7.2 - Dialogues and per-engine audio models

  • Dialogues as turns: in agentai-audio, generator.generate_dialogue([DialogueTurn::new(voice, text), ..]).await speaks 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 VoiceStore sent 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 with InvalidRequest before anything is sent.
  • One model per engine: a provider speaks with its speech model, speaks dialogues with the model set by with_dialogue_model and designs voices with the one set by with_design_model (for example Fish Audio voice-design-1, ElevenLabs eleven_ttv_v3). An engine without a model is off and returns MissingModel without a request; with_model on a call overrides the model for that call.
  • Calls are builders: generate(text).with_voice(id).with_instructions(..).await, and design_voice(description).with_text(..).with_count(n).await.
  • Choosing a provider: speech_provider("fishaudio", "s2-pro") (or SpeechProviderKind::FishAudio.builder(..)) builds a provider with its keys from the environment or with_api_key/with_base_url, and SpeechProviderKind::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::origin is Preset, Account or Store, so a voice picker can show the account voices and the VoiceStore voices of Fish Audio in separate sections.
  • Voice previews: VoiceInfo::preview is a recording to play: the ElevenLabs preview_url, the first sample of a Fish Audio voice model (when its server gives a full URL) or the sample of a VoiceStore voice. The list_voices tool 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.

0.7.1 - Voice design

  • Design voices from a description: SpeechGenerator::design_voice(description, text, count) in agentai-audio returns VoicePreviews to listen to, and create_voice keeps one as a voice you use with Voice::id. Fish Audio, ElevenLabs and oMLX can design voices; supports_voice_design() tells whether yours can. The new design_voice example shows the whole flow.
  • Cloning and designing share create_voice: it takes a VoiceSource, either VoiceSource::samples(samples, transcript) or a preview from design_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.

0.7.0 - Background tools, video generation, history processors, budgets

  • 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 with with_deferred_tasks(result.deferred_tasks). With the tokio feature, TokioDeferredTaskToolBox spawns the tasks and gives the model list_deferred_tasks, get_deferred_task and wait_deferred_task.
  • Video generation: the new agentai-video crate has from_model("comfy-serve::wan-2.2")? (or openrouter::<model>), which gives a VideoProvider. submit returns a VideoJob, you poll status until JobStatus::Completed and download the video as a Media. A VideoJob is serializable, so you can store it and follow it after a restart. VideoRequest takes 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_processor changes the messages right before every model call, while your history and new_messages stay complete. HistoryPruning replaces images and drops reasoning from finished turns, so long conversations stop resending them; write your own HistoryProcessor or pass a closure to trim or summarize.
  • Dollar budgets: with the budget feature, Agent::with_budget charges every model call to a limit from llm-budget and stops the run with AgentError::Budget when it is used up; AgentResult::cost_usd tells what a run cost.
  • Fish Audio and dialogues: agentai-audio speaks with Fish Audio (fishaudio::<model>). A SpeechRequest takes several voices for dialogue models such as drama-3, Fish Audio clones voices, and with_timestamps(true) returns the time of every word.
  • Provider-specific options: ChatOptions::with_extra_header and with_extra_body send headers and body fields that agentai has no setting for, such as Anthropic beta features.
  • File names and types: agentai_core::mime (re-exported by agentai-image, agentai-audio and agentai-video) maps MIME types to file extensions and back, and Media gains extension(), file_name(stem) and to_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 named my.picture is saved as my.picture.png.
  • Internal: agentai-core HTTP requests now support DELETE and JSON parts in multipart forms; the media crates share its MIME table, base64 helpers and a MockHttp test client (feature test-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.

0.6.0 - Text-to-speech and voice cloning

  • Speech generation: the new agentai-audio crate has SpeechGenerator to 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 for Voice::id, the same call on ElevenLabs and oMLX. oMLX needs the transcript of the sample and a VoiceStore set with with_voice_store.
  • Agents that speak: SpeechToolBox gives a model generate_speech and list_voices; with_voices limits it to the voices you allow. Cloning stays in your code.
  • Internal: agentai-core now has the HTTP and media helpers that agentai-image and agentai-audio share.

0.5.0 - Image generation, images in tool results

  • Image generation and editing: the new agentai-image crate has ImageGenerator to make and edit images from your code: ImageGenerator::new("openai::gpt-image-1")? takes the provider from the model name and the key from OPENAI_API_KEY; OpenAI-compatible servers work with OPENAI_BASE_URL or a base URL set in code, and OpenRouter models with openrouter::<model>. provider::list_models lists the image models a server offers.
  • Agents that draw: GenerateImageToolBox gives the agent generate_image and edit_image. The model gets the image itself, or only its metadata as JSON to save tokens. ReadMediaToolBox lets the model read any stored file by its ID.
  • Media storage: MediaRead and MediaSave (in agentai-core) store images and other files under an ID; implement them for your blob store or directory, or use MemoryStorage.
  • Tools can return images: a tool returns a ToolOutput with text and Media parts, 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 return ToolResult<ToolOutput> for that; methods that return text stay as they are.
  • Tools see the call: ToolBox::call_tool gets the ToolCall with its id, 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 &ToolCall parameter, 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 with parse_json_strings = false on #[toolbox] or #[tool].
  • TLS backend switches: pick rustls-ring (the new default), rustls-aws-lc or native-tls, and system-proxy (on by default). The default build no longer compiles the aws-lc-sys C library. If you build your own genai::Client or reqwest::Client, call tls::install_crypto_provider first.
  • Internal: the new agentai-core crate holds the shared types (Message, Prompt, Media, still available from agentai under the same paths) and the HTTP client abstraction used by agentai-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.

0.3.0 - Streaming, conversation history in your hands, run details

  • Streaming: Agent::run_stream takes the same configuration as Agent::run, and awaiting it returns a stream of AgentEvents: 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 is Send + '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's new_messages to it when you want to continue: history.extend(result.new_messages). Store, trim, persist or reset it however you like: Message has 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 the with_* methods of AgentRequest or a reusable RunOptions.
  • Run details: awaiting a run returns a AgentResult with 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 as AgentError::MaxTokens instead 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.

0.2.0 - Agent providers, remote MCP and configuration

  • Creating agents: Agent::new_with_provider binds 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::new and Agent::new_with_url now return Result, 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: McpToolBox now 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 on rmcp, the official MCP Rust SDK.
  • Agent configuration: Agent::with_max_iterations and Agent::with_chat_options set 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.

0.1.5 - ToolBox

This release introduces the ToolBox, a new feature providing an easy-to-use interface for supplying tools to AI agents.

Future Plans

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.

Installation

To add the AgentAI crate to your project, run the following command in your project's root directory:

cargo add agentai

This command adds the crate and its dependencies to your project.

Feature Flags

Available features for agentai crate. To enable any of these features, you need to enter this command:

cargo add agentai -F mcp-client

Features 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; call tls::install_crypto_provider before you build your own genai::Client or reqwest::Client.
  • rustls-aws-lc — TLS with rustls and the aws-lc-rs crypto provider (builds the aws-lc-sys C library).
  • native-tls — TLS of the operating system (OpenSSL, SChannel or Security Framework). It cannot be combined with a rustls-* feature: set default-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, via rmcp)
  • tokio (enabled by default) — Enables tokio integrations, such as TokioDeferredTaskToolBox and writing a stream to a tokio writer with AgentStream::print_to_tokio
  • macros (enabled by default) — Enables support for macro #[toolbox]
  • tools-buildin (enabled by default) — Enables support for buildin tools
  • tools-web (enabled by default) — Enables support for web tools
  • budget — Enables dollar spend limits with llm-budget: every model call is charged to the budget set with Agent::with_budget

Usage

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),
        _ => {}
    }
}

Error handling

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.

Examples

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 simple

Documentation

Full documentation is available on docs.rs.

Contributing

Contributions are welcome! Please see our CONTRIBUTING.md for more details.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Acknowledgements

Special thanks to the creators of the GenAI library for providing a robust framework for interfacing with various LLMs.

About

AgentAI is a Rust library designed to simplify the creation of AI agents

Resources

Contributing

Stars

176 stars

Watchers

3 watching

Forks

Releases

Contributors

Languages