Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Quick start

On this page you build an agent, run it against a hosted model, and then give it a tool. You need Rust 1.89 or newer and an API key for one of the catalog vendors. The key is read from <VENDOR>_API_KEY, so an openai/... model reads OPENAI_API_KEY.

Create the project

cargo new hello-agent
cd hello-agent

Then we add troupekit and tokio from crates.io:

cargo add troupekit
cargo add tokio --features rt-multi-thread,macros

Cargo.toml now has:

[dependencies]
troupekit = "0.4"
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }

Write the agent

Now we write the agent in src/main.rs. The doc comment becomes its instructions, and the fn name becomes its name:

use troupekit::prelude::*;

/// Greet the user by name.
#[agent(model = "openai/gpt-6-luna")]
fn greeter() {}

#[tokio::main]
async fn main() -> Result<(), KitError> {
    println!("{}", greeter().run("I am Ada").await?);
    Ok(())
}

Run it

export OPENAI_API_KEY="sk-..."
cargo run

run builds the agent, checks every setting, makes the model call and returns the final answer as a String. If a setting is wrong, such as an unknown model or a missing key, you get an error before any call is made.

Give it a tool

An agent gets much more useful once it can act. We give ours an add tool. #[tool] turns a fn into a tool: the doc comment is the description and the arguments become the JSON Schema the model sees. Put it in src/tools.rs:

#![allow(unused)]
fn main() {
use troupekit::prelude::*;

/// Adds two numbers.
#[tool]
pub async fn add(a: i64, b: i64) -> i64 {
    a + b
}
}

Then list it in the agent's tools key:

mod tools;
use tools::add;
use troupekit::prelude::*;

/// Adds numbers with the add tool.
#[agent(model = "openai/gpt-6-luna", tools = [add])]
fn calc() {}

#[tokio::main]
async fn main() -> Result<(), KitError> {
    println!("{}", calc().run("What is 2 + 40?").await?);
    Ok(())
}

Run it again. This time the model asks for add, the agent calls your fn, and the model answers with the result.

Run the repository examples

If you would rather not type, both programs ship as examples in the troupekit repository. Clone it and run them from its root, not from hello-agent:

git clone https://github.com/ChaoticQubit/troupekit
cd troupekit
cargo run -p troupekit --example hello
cargo run -p troupekit --example tool_agent

Next

From here, Agents and personas explains every agent setting, and Tools covers the other ways to write a tool, plus web and HTTP tools. The Guides walk through one example each.