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
impl Agent
Sourcepub fn tool_server_handle(&self) -> &ToolServerHandle
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.
Sourcepub fn description(&self) -> Option<&str>
pub fn description(&self) -> Option<&str>
Returns the configured agent description.
Sourcepub fn model_key(&self) -> &Key<Completion>
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).
Sourcepub fn model_descriptor(&self) -> Option<HandlerDescriptor>
pub fn model_descriptor(&self) -> Option<HandlerDescriptor>
The descriptor of this agent’s default model, as registered now.
Sourcepub fn model_label(&self) -> Option<ModelRef>
pub fn model_label(&self) -> Option<ModelRef>
The label of this agent’s default model, as registered now.
Sourcepub fn register_model(
&self,
label: impl Into<ModelRef>,
model: impl Into<DynModel<Completion>>,
) -> ModelRef
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.
Sourcepub fn set_model_label(&mut self, label: impl Into<ModelRef>)
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.
Sourcepub fn set_model(&mut self, model: impl Into<DynModel<Completion>>)
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.
Sourcepub fn owner(&self) -> &str
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>.
Sourcepub fn with_model_label(self, label: impl Into<ModelRef>) -> Self
pub fn with_model_label(self, label: impl Into<ModelRef>) -> Self
Agent::set_model_label by value.
Sourcepub fn with_model(self, model: impl Into<DynModel<Completion>>) -> Self
pub fn with_model(self, model: impl Into<DynModel<Completion>>) -> Self
Agent::set_model by value.
Sourcepub fn required_row(&self) -> EffectRow
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.
Sourcepub fn program_names(&self) -> Vec<String>
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.
Sourcepub fn bus_config(&self) -> Option<ServingPolicy>
pub fn bus_config(&self) -> Option<ServingPolicy>
The policy this agent’s own bus runs under; None over a host’s bus.
Sourcepub fn handler_descriptor(&self, key: &HandlerKey) -> Option<HandlerDescriptor>
pub fn handler_descriptor(&self, key: &HandlerKey) -> Option<HandlerDescriptor>
The descriptor currently registered under key, without access to dispatch.
Sourcepub fn into_parts(self) -> Result<AgentParts, Agent>
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.
Sourcepub async fn tool_definitions(
&self,
prompt: Option<String>,
) -> Result<Vec<ToolDefinition>, ToolServerError>
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
impl Agent
Sourcepub fn prompt(&self, prompt: impl Into<Message>) -> AgentRunner
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(orrun) folds the whole loop to aPromptResponse, whoseoutputis the accepted assistant text.streamyields every provider delta, tool event and the final response as a stream.run_channelsplits 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`
}Sourcepub fn resume(&self, run: AgentRun) -> AgentRunner
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?;Sourcepub async fn chat(
&self,
prompt: impl Into<Message> + WasmCompatSend,
chat_history: &mut Vec<Message>,
) -> Result<PromptResponse, PromptError>
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.
Sourcepub fn prompt_typed<T>(&self, prompt: impl Into<Message>) -> TypedRun<T>
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
impl Agent
Sourcepub fn into_tool(self) -> Result<DynamicTool, EmptyToolName>
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.