pub struct Agent { /* private fields */ }Expand description
Configured model, request settings, hooks, 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 in its table (a completion
key; .raw() for the wire string).
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 in this agent’s table 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 table 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>, …): the label given to
AgentBuilder::owner, else
agent#<n>.
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 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 its handlers (the handler table’s order, outermost
in). The log’s hooks; a replay under another stack of either is
refused.
Sourcepub fn handler_descriptor(&self, key: &HandlerKey) -> Option<HandlerDescriptor>
pub fn handler_descriptor(&self, key: &HandlerKey) -> Option<HandlerDescriptor>
The descriptor currently registered under key.
Sourcepub async fn tool_definitions(
&self,
prompt: Option<String>,
) -> Result<Vec<Arc<ToolDefinition>>, ProviderError>
pub async fn tool_definitions( &self, prompt: Option<String>, ) -> Result<Vec<Arc<ToolDefinition>>, ProviderError>
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 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 handlers, 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). Invalid-call hooks see, and a
Skip is gated by, the tool choice each turn was sent with. One
run-side value still shows through: the output tool the run pinned
stays pinned even though the schema and mode advertising it are the
runner’s.
Unanswered tool
calls re-execute on resume: a tool that ran before the suspension but
whose result was not fed to the run runs again (at least once), while
answered calls keep their results. 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 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.