#[non_exhaustive]pub struct Agent<M>where
M: CompletionModel,{Show 17 fields
pub name: Option<String>,
pub description: Option<String>,
pub model: Arc<M>,
pub preamble: Option<String>,
pub static_context: Vec<Document>,
pub temperature: Option<f64>,
pub max_tokens: Option<u64>,
pub additional_params: Option<Value>,
pub tool_server_handle: ToolServerHandle,
pub dynamic_context: Arc<Vec<(usize, Arc<dyn VectorStoreIndexDyn + Send + Sync>)>>,
pub tool_choice: Option<ToolChoice>,
pub default_max_turns: Option<usize>,
pub hooks: HookStack<M>,
pub output_schema: Option<Schema>,
pub output_mode: OutputMode,
pub memory: Option<Arc<dyn ConversationMemory>>,
pub default_conversation_id: Option<String>,
}Expand description
Struct representing an LLM agent. An agent is an LLM model combined with a preamble (i.e.: system prompt) and a static set of context documents and tools. All context documents and tools are always provided to the agent when prompted.
Default hooks attached with AgentBuilder::add_hook
are used for every prompt request, plus any added on the request or runner.
§Example
use rig_core::{
client::{CompletionClient, ProviderClient},
completion::Prompt,
providers::openai,
};
let openai = openai::Client::from_env()?;
let comedian_agent = openai
.agent(openai::GPT_5_2)
.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?;Fields (Non-exhaustive)§
This struct is marked as non-exhaustive
Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.name: Option<String>Name of the agent used for logging and debugging
description: Option<String>Agent description. Primarily useful when using sub-agents as part of an agent workflow and converting agents to other formats.
model: Arc<M>Completion model (e.g.: OpenAI’s gpt-3.5-turbo-1106, Cohere’s command-r)
preamble: Option<String>System prompt
static_context: Vec<Document>Context documents always available to the agent
temperature: Option<f64>Temperature of the model
max_tokens: Option<u64>Maximum number of tokens for the completion
additional_params: Option<Value>Additional parameters to be passed to the model
tool_server_handle: ToolServerHandle§dynamic_context: Arc<Vec<(usize, Arc<dyn VectorStoreIndexDyn + Send + Sync>)>>List of vector store, with the sample number
tool_choice: Option<ToolChoice>Whether or not the underlying LLM should be forced to use a tool before providing a response.
default_max_turns: Option<usize>Default total model-call budget, including the initial call and every
retry or continuation. None uses the implicit budget of one.
hooks: HookStack<M>Default hook stack applied to every prompt request and runner created from this agent. Empty by default.
output_schema: Option<Schema>Optional JSON Schema for structured output. When set, providers that support native structured outputs will constrain the model’s response to match this schema.
output_mode: OutputModeHow output_schema is enforced — tool call, native structured output, or
prompt injection (see OutputMode and issue #1928).
memory: Option<Arc<dyn ConversationMemory>>Optional conversation memory backend that loads/saves history per conversation id.
default_conversation_id: Option<String>Optional default conversation id used when none is set per-request.
Implementations§
Source§impl<M> Agent<M>where
M: CompletionModel,
impl<M> Agent<M>where
M: CompletionModel,
Sourcepub fn runner(&self, prompt: impl Into<Message>) -> AgentRunner<M>
pub fn runner(&self, prompt: impl Into<Message>) -> AgentRunner<M>
Build a hook-aware AgentRunner for this agent, seeded with the
agent’s default hook stack. Attach more hooks with
AgentRunner::add_hook, then call AgentRunner::run.
Trait Implementations§
Source§impl<M> Chat for Agent<M>where
M: CompletionModel + 'static,
impl<M> Chat for Agent<M>where
M: CompletionModel + 'static,
Source§impl<M> Completion<M> for Agent<M>where
M: CompletionModel,
impl<M> Completion<M> for Agent<M>where
M: CompletionModel,
Source§async fn completion<I, T>(
&self,
prompt: impl Into<Message> + WasmCompatSend,
chat_history: I,
) -> Result<CompletionRequestBuilder<M>, CompletionError>
async fn completion<I, T>( &self, prompt: impl Into<Message> + WasmCompatSend, chat_history: I, ) -> Result<CompletionRequestBuilder<M>, CompletionError>
prompt and chat_history.
This function is meant to be called by the user to further customize the
request at prompt time before sending it. Read moreSource§impl<M> DiscordExt for Agent<M>
Available on crate feature discord-bot only.
impl<M> DiscordExt for Agent<M>
discord-bot only.async fn into_discord_bot(self, token: &str) -> Result<Client, DiscordBotError>
fn into_discord_bot_from_env( self, ) -> impl Future<Output = Result<Client, DiscordBotError>> + Send
Source§impl<M> Prompt for Agent<M>where
M: CompletionModel + 'static,
impl<M> Prompt for Agent<M>where
M: CompletionModel + 'static,
Source§fn prompt(
&self,
prompt: impl Into<Message> + WasmCompatSend,
) -> PromptRequest<Standard, M>
fn prompt( &self, prompt: impl Into<Message> + WasmCompatSend, ) -> PromptRequest<Standard, M>
Source§impl<M> Prompt for &Agent<M>where
M: CompletionModel + 'static,
impl<M> Prompt for &Agent<M>where
M: CompletionModel + 'static,
Source§fn prompt(
&self,
prompt: impl Into<Message> + WasmCompatSend,
) -> PromptRequest<Standard, M>
fn prompt( &self, prompt: impl Into<Message> + WasmCompatSend, ) -> PromptRequest<Standard, M>
Source§impl<M> StreamingChat<M, <M as CompletionModel>::StreamingResponse> for Agent<M>
impl<M> StreamingChat<M, <M as CompletionModel>::StreamingResponse> for Agent<M>
Source§fn stream_chat<I, T>(
&self,
prompt: impl Into<Message> + WasmCompatSend,
chat_history: I,
) -> StreamingPromptRequest<M>
fn stream_chat<I, T>( &self, prompt: impl Into<Message> + WasmCompatSend, chat_history: I, ) -> StreamingPromptRequest<M>
Source§impl<M> StreamingCompletion<M> for Agent<M>where
M: CompletionModel,
impl<M> StreamingCompletion<M> for Agent<M>where
M: CompletionModel,
Source§async fn stream_completion<I, T>(
&self,
prompt: impl Into<Message> + WasmCompatSend,
chat_history: I,
) -> Result<CompletionRequestBuilder<M>, CompletionError>
async fn stream_completion<I, T>( &self, prompt: impl Into<Message> + WasmCompatSend, chat_history: I, ) -> Result<CompletionRequestBuilder<M>, CompletionError>
Source§impl<M> StreamingPrompt<M, <M as CompletionModel>::StreamingResponse> for Agent<M>
impl<M> StreamingPrompt<M, <M as CompletionModel>::StreamingResponse> for Agent<M>
Source§fn stream_prompt(
&self,
prompt: impl Into<Message> + WasmCompatSend,
) -> StreamingPromptRequest<M>
fn stream_prompt( &self, prompt: impl Into<Message> + WasmCompatSend, ) -> StreamingPromptRequest<M>
Source§impl<M: CompletionModel + 'static> Tool for Agent<M>
impl<M: CompletionModel + 'static> Tool for Agent<M>
Source§async fn call_with_extensions(
&self,
args: Self::Args,
extensions: &ToolCallExtensions,
) -> Result<Self::Output, Self::Error>
async fn call_with_extensions( &self, args: Self::Args, extensions: &ToolCallExtensions, ) -> Result<Self::Output, Self::Error>
Propagate the caller’s ToolCallExtensions into the sub-agent run, so the
inner agent’s own tools observe them too (sub-agent delegation / A2A
chains). Without this, a sub-agent invoked as a tool would start with
empty extensions.
Source§const NAME: &'static str = "agent_tool"
const NAME: &'static str = "agent_tool"
ToolSet or other registration scope that dispatches tools by name.Source§type Error = PromptError
type Error = PromptError
Source§fn description(&self) -> String
fn description(&self) -> String
Source§fn parameters(&self) -> Value
fn parameters(&self) -> Value
Source§async fn call(&self, args: Self::Args) -> Result<Self::Output, Self::Error>
async fn call(&self, args: Self::Args) -> Result<Self::Output, Self::Error>
Source§fn classify_error(&self, error: &Self::Error) -> ToolFailure
fn classify_error(&self, error: &Self::Error) -> ToolFailure
ToolFailure. Read moreSource§fn call_structured(
&self,
args: Self::Args,
extensions: &ToolCallExtensions,
) -> impl Future<Output = Result<ToolReturn<Self::Output>, Self::Error>> + WasmCompatSend
fn call_structured( &self, args: Self::Args, extensions: &ToolCallExtensions, ) -> impl Future<Output = Result<ToolReturn<Self::Output>, Self::Error>> + WasmCompatSend
ToolReturn instead of a bare
output. Read moreSource§impl<M> TypedPrompt for Agent<M>where
M: CompletionModel + 'static,
impl<M> TypedPrompt for Agent<M>where
M: CompletionModel + 'static,
Source§fn prompt_typed<T>(
&self,
prompt: impl Into<Message> + WasmCompatSend,
) -> TypedPromptRequest<T, Standard, M>
fn prompt_typed<T>( &self, prompt: impl Into<Message> + WasmCompatSend, ) -> TypedPromptRequest<T, Standard, M>
Send a prompt and receive a typed structured response.
The JSON schema for T is automatically generated and sent to the provider.
Providers that support native structured outputs will constrain the model’s
response to match this schema.
§Example
use rig_core::prelude::*;
use schemars::JsonSchema;
use serde::Deserialize;
#[derive(Debug, Deserialize, JsonSchema)]
struct WeatherForecast {
city: String,
temperature_f: f64,
conditions: String,
}
let agent = client.agent("gpt-4o").build();
// Type inferred from variable
let forecast: WeatherForecast = agent
.prompt_typed("What's the weather in NYC?")
.await?;
// Or explicit turbofish syntax
let forecast = agent
.prompt_typed::<WeatherForecast>("What's the weather in NYC?")
.max_turns(3)
.await?;Source§type TypedRequest<T> = TypedPromptRequest<T, Standard, M>
where
T: JsonSchema + DeserializeOwned + WasmCompatSend + 'static
type TypedRequest<T> = TypedPromptRequest<T, Standard, M> where T: JsonSchema + DeserializeOwned + WasmCompatSend + 'static
prompt_typed.Source§impl<M> TypedPrompt for &Agent<M>where
M: CompletionModel + 'static,
impl<M> TypedPrompt for &Agent<M>where
M: CompletionModel + 'static,
Source§type TypedRequest<T> = TypedPromptRequest<T, Standard, M>
where
T: JsonSchema + DeserializeOwned + WasmCompatSend + 'static
type TypedRequest<T> = TypedPromptRequest<T, Standard, M> where T: JsonSchema + DeserializeOwned + WasmCompatSend + 'static
prompt_typed.Source§fn prompt_typed<T>(
&self,
prompt: impl Into<Message> + WasmCompatSend,
) -> TypedPromptRequest<T, Standard, M>
fn prompt_typed<T>( &self, prompt: impl Into<Message> + WasmCompatSend, ) -> TypedPromptRequest<T, Standard, M>
Auto Trait Implementations§
impl<M> !RefUnwindSafe for Agent<M>
impl<M> !UnwindSafe for Agent<M>
impl<M> Freeze for Agent<M>
impl<M> Send for Agent<M>
impl<M> Sync for Agent<M>
impl<M> Unpin for Agent<M>
impl<M> UnsafeUnpin for Agent<M>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> CloneableStorage for T
impl<T> CloneableStorage for T
fn clone_storage(&self) -> Box<dyn CloneableStorage>
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§impl<T> Pointable for T
impl<T> Pointable for T
Source§impl<T> PolicyExt for Twhere
T: ?Sized,
impl<T> PolicyExt for Twhere
T: ?Sized,
impl<T> Read<Exclusive, BecauseExclusive> for Twhere
T: ?Sized,
Source§impl<T> ToolDyn for Twhere
T: Tool,
impl<T> ToolDyn for Twhere
T: Tool,
Source§fn call_structured<'a>(
&'a self,
args: String,
extensions: &'a ToolCallExtensions,
) -> Pin<Box<dyn Future<Output = ToolExecutionResult> + Send + 'a>>
fn call_structured<'a>( &'a self, args: String, extensions: &'a ToolCallExtensions, ) -> Pin<Box<dyn Future<Output = ToolExecutionResult> + Send + 'a>>
Routes through Tool::call_structured so rich returns
(ToolReturn) and Tool::classify_error are honored: a JSON
argument parse failure becomes an
InvalidArgs outcome, a returned
Err(Self::Error) is classified, and a successful ToolReturn is
serialized while preserving its outcome and extensions.