Skip to main content

Agent

Struct Agent 

Source
pub struct Agent { /* private fields */ }
Expand description

Configured model, request settings, hooks, memory, and tool registry for runs. Per-run overrides and dynamic retrieval determine each turn’s effective request.

Default hooks attached with AgentBuilder::add_hook are used for every prompt request, plus any added on the request or runner.

§Example

use rig_agent::prelude::*;
use rig_core::{Model, providers::openai::{self, OpenAI}};

let model = OpenAI::from_env()?.completion(openai::GPT_5_2);

let comedian_agent = AgentBuilder::new(model)
    .preamble("You are a comedian here to entertain the user using humour and jokes.")
    .temperature(0.9)
    .build();

let response = comedian_agent.prompt("Entertain me!").await?;

Implementations§

Source§

impl Agent

Source

pub fn run_spec(&self) -> RunSpec

Return serializable request settings and run policy, excluding live models, tools, hooks, and memory.

Source§

impl Agent

Source

pub fn tool_server_handle(&self) -> &ToolServerHandle

The tool server this agent dispatches tool calls through. Cloning the handle lets external tool sources (an MCP client handler, for example) register and refresh tools the agent will see on its next turn.

Source

pub fn name(&self) -> Option<&str>

Returns the configured agent name.

Source

pub fn description(&self) -> Option<&str>

Returns the configured agent description.

Source

pub fn model_key(&self) -> &Key<Completion>

The key of this agent’s default model on its bus (a completion key; .raw() for the wire string).

Source

pub fn model_descriptor(&self) -> Option<HandlerDescriptor>

The descriptor of this agent’s default model, as registered now.

Source

pub fn model_label(&self) -> Option<ModelRef>

The label of this agent’s default model, as registered now.

Source

pub fn register_model( &self, label: impl Into<ModelRef>, model: impl Into<DynModel<Completion>>, ) -> ModelRef

Register model on this agent’s bus under label and return the label a run selects it by.

Source

pub fn set_model_label(&mut self, label: impl Into<ModelRef>)

Make the model registered under label this agent value’s default. Value semantics: clones of the agent keep their own default.

Source

pub fn set_model(&mut self, model: impl Into<DynModel<Completion>>)

Register model under a generated label and make it this agent value’s default. The registration is scoped to the values that select it (this agent, its clones, the runners it produces): it leaves the bus when the last of them drops or selects another model.

Source

pub fn owner(&self) -> &str

The owner segment of the keys this agent minted (<owner>/model:<label>, <owner>/memory, …): the label given to AgentBuilder::owner, else agent#<n>.

Source

pub fn with_model_label(self, label: impl Into<ModelRef>) -> Self

Source

pub fn with_model(self, model: impl Into<DynModel<Completion>>) -> Self

Agent::set_model by value.

Source

pub fn required_row(&self) -> EffectRow

The effect row this program can dispatch to: its model, every tool the registry serves, its memory backend and its retrieval indexes, each with the family it needs, from the registry rather than what a run happened to dispatch.

Source

pub fn program_names(&self) -> Vec<String>

What decides on this agent’s behalf: its hook stack’s names, then every layer on the bus’s handlers (the handler table’s order, outermost in). The log’s hooks; a replay under another stack of either is refused.

Source

pub fn bus_config(&self) -> Option<ServingPolicy>

The policy this agent’s own bus runs under; None over a host’s bus.

Source

pub fn handler_descriptor(&self, key: &HandlerKey) -> Option<HandlerDescriptor>

The descriptor currently registered under key, without access to dispatch.

Source

pub fn owns_bus(&self) -> bool

Whether this agent owns and drives its own bus driver.

Source

pub fn into_parts(self) -> Result<AgentParts, Agent>

Take the agent apart: the dispatcher and the driver leave together, so whoever gets the dispatcher also gets the duty to drive. Fails when the agent was built over a host’s bus or when another clone of it still shares the driver.

Source

pub async fn tool_definitions( &self, prompt: Option<String>, ) -> Result<Vec<ToolDefinition>, ToolServerError>

Resolve the provider-facing tool definitions available for a prompt.

This read-only view does not expose tool dispatch. Agent execution and tool lifecycle hooks remain owned by Self::prompt.

Source§

impl Agent

Source

pub fn prompt(&self, prompt: impl Into<Message>) -> AgentRunner

Start a run from prompt. The returned AgentRunner is the run: configure it (history, turn budget, tool context, hooks, …), then pick how to drive it. Nothing happens until it is driven.

  • .await (or run) folds the whole loop to a PromptResponse, whose output is the accepted assistant text.
  • stream yields every provider delta, tool event and the final response as a stream.
  • run_channel splits the run into a future and an event feed for a host with its own executor or tick.

The medium is chosen by the terminal call alone: an awaited runner asks the provider for a complete response, a streamed one for a stream. Hooks, tools, memory and the resulting history are the same in each.

let response = agent.prompt("What is 2 + 2?").max_turns(3).await?;
println!("{}", response.output());

let mut stream = agent.prompt("And 3 + 3?").stream();
while let Some(item) = stream.next().await {
    let item = item?;
    // text deltas, tool calls and results, then `FinalResponse`
}
Source

pub fn resume(&self, run: AgentRun) -> AgentRunner

Continue a persisted run instead of starting one from a prompt.

The state a driver serialized between steps (see AgentRun) is resumed under this agent’s hooks, tools, and bus, executing pending tool calls or requesting the next model turn. The run is authoritative for what it persisted: its prompt, its history, its turn budget, its invalid-tool-call retry budget and its unhandled-invalid-tool-call policy, so history, max_turns and unhandled_invalid_tool_call on the returned runner have no effect. Everything else still comes from the agent and the runner: the request shape (preamble, documents, sampling parameters, additional params, tool choice, output mode), add_hook, tool_context, tool_concurrency, the model selection and telemetry settings (inbound tool context is driver state, never part of the persisted run). Two run-side values still show through: the run’s persisted tool choice is what invalid-call hooks see and what gates a Skip, while the request’s tool choice is the runner’s; and the output tool the run committed stays committed even though the schema and mode advertising it are the runner’s. Conversation memory is neither loaded nor appended: the history is already in the run, and the driver that persisted it owns memory persistence and appends the finished run’s messages itself, since a suspended run never reached the Done append, so the response’s memory_append is None. Pending tool calls re-execute on resume: a tool that ran before the suspension and answered nothing runs again. Drive it like any runner: .await, stream or run_channel. The run must have been suspended by the same rig version.

let run: AgentRun = serde_json::from_str(saved)?;
let response = agent.resume(run).tool_concurrency(4).await?;
Source

pub async fn chat( &self, prompt: impl Into<Message> + WasmCompatSend, chat_history: &mut Vec<Message>, ) -> Result<PromptResponse, PromptError>

Run prompt against caller-owned history with the agent’s defaults, then append the messages the run committed to chat_history. This is prompt with history plus the write-back; the runner form is the one to configure or stream. The returned PromptResponse keeps its messages.

The caller’s history is the run’s input history, so conversation memory is bypassed (no load, no append) and the caller owns persistence. A run that fails appends nothing: the error carries the history the run had, the caller’s vector is unchanged.

Source

pub fn prompt_typed<T>(&self, prompt: impl Into<Message>) -> TypedRun<T>

Run prompt and deserialize the accepted structured response as T.

The JSON schema for T is generated and sent to the provider as the run’s structured-output schema. Providers that support native structured outputs constrain the model’s response to match it.

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
struct WeatherForecast { city: String, temperature_f: f64 }
let forecast = agent
    .prompt_typed::<WeatherForecast>("What's the weather in NYC?")
    .max_turns(3)
    .await?
    .output;
Source§

impl Agent

Source

pub fn into_tool(self) -> Result<DynamicTool, EmptyToolName>

Convert this agent into a runtime-defined tool.

Uses the configured name or agent_tool. The tool accepts a JSON prompt string and inherits dispatch context. Invalid arguments and failed runs become tool execution errors; successful output is returned as text.

Returns EmptyToolName when the configured name is empty.

Trait Implementations§

Source§

impl Chat for Agent

Source§

async fn chat( &self, prompt: impl Into<Message> + WasmCompatSend, history: &mut Vec<Message>, ) -> Result<String, PromptError>

Execute one turn and append only committed messages to history.
Source§

impl Clone for Agent

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl TryFrom<Agent> for DynamicTool

Source§

type Error = EmptyToolName

The type returned in the event of a conversion error.
Source§

fn try_from(agent: Agent) -> Result<Self, EmptyToolName>

Performs the conversion.

Auto Trait Implementations§

§

impl !RefUnwindSafe for Agent

§

impl !UnwindSafe for Agent

§

impl Freeze for Agent

§

impl Send for Agent

§

impl Sync for Agent

§

impl Unpin for Agent

§

impl UnsafeUnpin for Agent

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WasmCompatSend for T
where T: Send,

Source§

impl<T> WasmCompatSync for T
where T: Sync,

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more