Skip to main content

rig_agent/agent/
builder.rs

1//! Agent construction over its own or a host's handler table, with the
2//! builder's tools, a shared tool server, or both (the builder's tools join
3//! the shared server at build).
4//!
5//! ```
6//! use rig_core::{DynModel, operation::Completion};
7//! use rig_agent::{Agent, AgentBuilder};
8//! fn assistant(model: impl Into<DynModel<Completion>>) -> Agent {
9//!     AgentBuilder::new(model).preamble("Be concise.").build()
10//! }
11//! ```
12
13use std::sync::{Arc, OnceLock};
14
15use crate::handlers::Handlers;
16use rig_core::serve::adapters::{ModelAdapter, RetrieveAdapter};
17use rig_core::serve::{ErasedHandler, Recorder};
18use rig_core::{
19    completion::{Document, ModelRef, ProviderToolDefinition},
20    effect::{HandlerKey, Key, family},
21    vector_store::{VectorSearchRequest, VectorStoreIndex, request::DynamicSearchFilter},
22    wasm_compat::{WasmCompatSend, WasmCompatSync},
23};
24use schemars::{JsonSchema, Schema, schema_for};
25
26use crate::{
27    agent::{AgentHook, CompletionCallAction, CompletionCallEvent, HookContext, RequestPatch},
28    completion::message::ToolChoice,
29    tool::{
30        DynamicTool, Tool, ToolSet,
31        server::{ToolServer, ToolServerHandle},
32    },
33};
34
35use super::{
36    Agent, OutputMode,
37    completion::{AgentConfig, default_owner, register_generated},
38};
39
40/// The `dynamic_context` hook: retrieves documents for the prompt through
41/// the agent's handlers (an `IndexHandle` bound to the index registered at
42/// build) and patches them into the request as extra context.
43struct DynamicContext {
44    samples: usize,
45    /// The index's key, minted at build once the agent's owner is known.
46    key: Arc<OnceLock<Key<family::Retrieve>>>,
47}
48
49impl AgentHook for DynamicContext {
50    async fn on_completion_call(
51        &self,
52        ctx: &HookContext,
53        event: CompletionCallEvent<'_>,
54    ) -> CompletionCallAction {
55        let Some(query) = super::completion::retrieval_query(event.prompt, event.history) else {
56            return CompletionCallAction::continue_run();
57        };
58        let Some(key) = self.key.get() else {
59            return CompletionCallAction::stop(
60                "dynamic context is keyed at build; this hook was not built",
61            );
62        };
63        let index = match ctx.bind(key) {
64            Ok(index) => index,
65            Err(report) => {
66                return CompletionCallAction::stop(format!(
67                    "failed to bind the dynamic context index: {report}"
68                ));
69            }
70        };
71
72        let request = VectorSearchRequest::builder()
73            .query(query)
74            .samples(self.samples as u64)
75            .build();
76        match index.top_n::<serde_json::Value>(request).await {
77            Ok(results) => CompletionCallAction::patch(RequestPatch::new().extra_context(
78                results.into_iter().map(|result| {
79                    Document {
80                        text: serde_json::to_string_pretty(&result.document)
81                            .unwrap_or_else(|_| result.document.to_string()),
82                        id: result.id,
83                        additional_props: Default::default(),
84                    }
85                }),
86            )),
87            Err(error) => {
88                CompletionCallAction::stop(format!("failed to retrieve dynamic context: {error}"))
89            }
90        }
91    }
92}
93
94/// The default model: a model the builder registers under a label, or the
95/// key of one a host registers in its table.
96enum DefaultModel {
97    Labelled(ModelRef, ErasedHandler),
98    Key(HandlerKey),
99}
100
101/// Builds an [`Agent`].
102///
103/// Every handler the builder registers (the default model, model routes,
104/// dynamic-context indexes) is minted a key under the agent's owner label at
105/// build: `<owner>/model:<label>` and `<owner>/retrieve:context#<n>`. Hosts sharing a table must choose distinct
106/// owners to avoid replacing each other's bindings. The explicit owner takes
107/// precedence over the agent name, then a generated `agent#<n>` label.
108pub struct AgentBuilder {
109    config: AgentConfig,
110    /// The tools added through the builder.
111    tools: ToolServer,
112    /// The shared registry, if any; the builder's tools join it at build.
113    shared: Option<ToolServerHandle>,
114    owner: Option<String>,
115    model: DefaultModel,
116    /// Handlers to register at build, by key suffix.
117    pending: Vec<(String, ErasedHandler)>,
118    /// The dynamic-context hooks' key slots, by key suffix.
119    dynamic_contexts: Vec<(String, Arc<OnceLock<Key<family::Retrieve>>>)>,
120    recorder: Option<Arc<dyn Recorder + Send + Sync>>,
121    /// The labels `model_route` registered, in order.
122    routes: Vec<String>,
123}
124
125impl AgentBuilder {
126    /// Name the agent.
127    pub fn name(mut self, name: impl Into<String>) -> Self {
128        self.config.name = Some(name.into());
129        self
130    }
131
132    /// Describe the agent.
133    pub fn description(mut self, description: impl Into<String>) -> Self {
134        self.config.description = Some(description.into());
135        self
136    }
137
138    /// Set the system prompt.
139    pub fn preamble(mut self, preamble: impl Into<String>) -> Self {
140        self.config.spec_mut().preamble = Some(preamble.into());
141        self
142    }
143
144    /// Clear the system prompt.
145    pub fn without_preamble(mut self) -> Self {
146        self.config.spec_mut().preamble = None;
147        self
148    }
149
150    /// Append a paragraph to the system prompt.
151    pub fn append_preamble(mut self, doc: &str) -> Self {
152        let preamble = &mut self.config.spec_mut().preamble;
153        *preamble = Some(format!("{}\n{doc}", preamble.take().unwrap_or_default()));
154        self
155    }
156
157    /// Add a static context document.
158    pub fn context(mut self, doc: impl Into<String>) -> Self {
159        let documents = &mut self.config.spec_mut().static_context;
160        documents.push(Document {
161            id: format!("static_doc_{}", documents.len()),
162            text: doc.into(),
163            additional_props: Default::default(),
164        });
165        self
166    }
167
168    /// Retrieve `samples` documents from `index` for every prompt and add
169    /// them as context. The index is registered in the agent's table.
170    pub fn dynamic_context<I, F>(self, samples: usize, index: I) -> Self
171    where
172        I: VectorStoreIndex<Filter = F> + 'static,
173        F: DynamicSearchFilter + WasmCompatSend + WasmCompatSync + 'static,
174    {
175        self.dynamic_context_handler(samples, RetrieveAdapter::new(index))
176    }
177
178    /// Retrieve `samples` documents through a retrieval-family handler registered
179    /// under the next context key, using the dynamic-context hook lifecycle.
180    pub fn dynamic_context_handler(
181        mut self,
182        samples: usize,
183        handler: impl rig_core::serve::Serve + 'static,
184    ) -> Self {
185        let suffix = format!("retrieve:context#{}", self.dynamic_contexts.len());
186        let key = Arc::new(OnceLock::new());
187        self.pending
188            .push((suffix.clone(), ErasedHandler::new(handler)));
189        self.dynamic_contexts.push((suffix, key.clone()));
190        self.add_hook(DynamicContext { samples, key })
191    }
192
193    /// Set the tool choice.
194    pub fn tool_choice(mut self, tool_choice: ToolChoice) -> Self {
195        self.config.spec_mut().tool_choice = Some(tool_choice);
196        self
197    }
198
199    /// Set the default maximum number of turns.
200    pub fn default_max_turns(mut self, default_max_turns: usize) -> Self {
201        self.config.spec_mut().max_turns = Some(default_max_turns);
202        self
203    }
204
205    /// Set the sampling temperature.
206    pub fn temperature(mut self, temperature: f64) -> Self {
207        self.config.spec_mut().temperature = Some(temperature);
208        self
209    }
210
211    /// Remove the sampling temperature, for test scenarios run against
212    /// models that reject it.
213    #[cfg(any(test, feature = "test-utils"))]
214    pub(crate) fn clear_temperature(mut self) -> Self {
215        self.config.spec_mut().temperature = None;
216        self
217    }
218
219    /// Set the output-token cap.
220    pub fn max_tokens(mut self, max_tokens: u64) -> Self {
221        self.config.spec_mut().max_tokens = Some(max_tokens);
222        self
223    }
224
225    /// Set provider passthrough parameters.
226    pub fn additional_params(mut self, params: serde_json::Value) -> Self {
227        self.config.spec_mut().additional_params = Some(params);
228        self
229    }
230
231    /// Add a provider-hosted tool (web search, code execution and the like)
232    /// to every request, after the agent's function tools. The provider runs
233    /// it; the agent never dispatches it. Calls accumulate. A
234    /// [`RequestPatch`]'s `active_tools` does not filter it; a turn's
235    /// [`ToolChoice::None`] keeps the model off it.
236    pub fn provider_tool(self, tool: ProviderToolDefinition) -> Self {
237        self.provider_tools([tool])
238    }
239
240    /// Add provider-hosted tools in order, as [`Self::provider_tool`] does.
241    pub fn provider_tools(
242        mut self,
243        tools: impl IntoIterator<Item = ProviderToolDefinition>,
244    ) -> Self {
245        self.config.spec_mut().provider_tools.extend(tools);
246        self
247    }
248
249    /// Set the portable generation options every request of this agent
250    /// carries. A run's [`AgentRunner::options`](crate::agent::AgentRunner::options)
251    /// overlays them field by field. Calls apply in order: this replaces
252    /// every field, so a shortcut such as [`Self::seed`] called before it is
253    /// lost, and one called after it sets its one field on top.
254    pub fn options(mut self, options: rig_core::completion::GenerationOptions) -> Self {
255        self.config.spec_mut().options = options;
256        self
257    }
258
259    generation_option_setters!("the agent's");
260
261    /// Set the stop sequences in the agent's generation options, as
262    /// [`GenerationOptions::stop`](rig_core::completion::GenerationOptions::stop) does,
263    /// keeping its other fields. See
264    /// [`Self::options`] for the order of calls.
265    pub fn stop<S: Into<String>>(mut self, stop: impl IntoIterator<Item = S>) -> Self {
266        self.config.spec_mut().options =
267            std::mem::take(&mut self.config.spec_mut().options).stop(stop);
268        self
269    }
270
271    /// Set the typed per-provider options every request of this agent
272    /// carries. A run's
273    /// [`AgentRunner::provider_options`](crate::agent::AgentRunner::provider_options)
274    /// replaces the entry of each provider it names.
275    ///
276    /// Calls apply in order: this replaces every entry, so an entry set by
277    /// an earlier [`Self::provider_option`] is lost, and a later
278    /// [`Self::provider_option`] replaces its provider's entry on top.
279    pub fn provider_options(mut self, options: rig_core::completion::ProviderOptions) -> Self {
280        self.config.spec_mut().provider_options = options;
281        self
282    }
283
284    /// Store `options` as the entry of their provider
285    /// ([`ExtensionOptions::Ext`](rig_core::completion::ExtensionOptions::Ext))
286    /// in the provider options every request of this agent carries,
287    /// replacing that provider's entry and keeping every other
288    /// ([`ProviderOptions::set`](rig_core::completion::ProviderOptions::set)).
289    /// Options that do not serialize fail each request's encode. A
290    /// third-party provider reusing a built-in options type needs
291    /// [`ProviderOptions::with::<P>`](rig_core::completion::ProviderOptions::with)
292    /// and [`Self::provider_options`]: this stores under the built-in key.
293    pub fn provider_option<O: rig_core::completion::ExtensionOptions>(
294        mut self,
295        options: O,
296    ) -> Self {
297        self.config.spec_mut().provider_options =
298            std::mem::take(&mut self.config.spec_mut().provider_options).set(options);
299        self
300    }
301
302    /// Enable or disable sensitive message content on telemetry spans.
303    /// Disabled by default; enabling may expose prompts, responses, tool data,
304    /// and the tool definitions sent with each completion.
305    pub fn record_content_telemetry(mut self, enabled: bool) -> Self {
306        self.config.record_telemetry_content = enabled;
307        self
308    }
309
310    /// Accept finish reasons outside the normalized vocabulary
311    /// ([`FinishReason::Other`](rig_core::completion::FinishReason::Other))
312    /// as a normal stop. Off by default: such a turn fails the run,
313    /// and history replay leaves it out. When on, the turn succeeds, its
314    /// tool calls run, and it replays.
315    ///
316    /// `Other` also holds genuine failures, such as Gemini's
317    /// `MALFORMED_FUNCTION_CALL` and `RECITATION` or Bedrock's
318    /// `malformed_tool_use`, so tool calls from a malformed reply may run.
319    /// Filtered content still fails the turn.
320    pub fn accept_unknown_finish_reasons(mut self, accept: bool) -> Self {
321        self.config.spec_mut().accept_unknown_finish_reasons = accept;
322        self
323    }
324
325    /// Constrain the output to `T`'s JSON schema.
326    pub fn output_schema<T>(mut self) -> Self
327    where
328        T: JsonSchema,
329    {
330        self.config.spec_mut().output_schema = Some(schema_for!(T));
331        self
332    }
333
334    /// Constrain the output to a raw JSON schema.
335    pub fn output_schema_raw(mut self, schema: Schema) -> Self {
336        self.config.spec_mut().output_schema = Some(schema);
337        self
338    }
339
340    /// Set the structured-output mode.
341    pub fn output_mode(mut self, mode: OutputMode) -> Self {
342        self.config.spec_mut().output_mode = mode;
343        self
344    }
345
346    /// Register another model the run can select by label
347    /// (`ModelSelectionAction::select(label)`, `using_model(label)`).
348    pub fn model_route(
349        self,
350        label: impl Into<ModelRef>,
351        model: impl Into<rig_core::DynModel<rig_core::operation::Completion>>,
352    ) -> Self {
353        let label = label.into();
354        let adapter = ModelAdapter::new(label.clone(), model);
355        self.model_route_handler(label, adapter)
356    }
357
358    /// Register a completion-family handler under the route key for `label`.
359    /// Includes that route in the program's required effect row.
360    pub fn model_route_handler(
361        mut self,
362        label: impl Into<ModelRef>,
363        handler: impl rig_core::serve::Serve + 'static,
364    ) -> Self {
365        let label = label.into();
366        self.routes.push(label.as_str().to_owned());
367        self.pending.push((
368            rig_core::effect::model_key(label.as_str()).to_string(),
369            ErasedHandler::new(handler),
370        ));
371        self
372    }
373
374    /// Name the agent's keys: `<owner>/model:<label>`,
375    /// `<owner>/retrieve:context#<n>`, and its own tools' `<owner>/tool:…`.
376    /// Defaults to the agent's name, or a process-local `agent#<n>` counter.
377    /// Use stable, distinct owners for replay and agents sharing a table.
378    pub fn owner(mut self, label: impl Into<String>) -> Self {
379        self.owner = Some(label.into());
380        self
381    }
382
383    /// Keep each run's conversation in `store`: a run loads it before its
384    /// first model call and saves its messages there once it finished, so
385    /// the next run goes on from them. A run that fails or is cancelled
386    /// saves nothing; a failed load or save fails the run with
387    /// [`PromptError::Memory`](crate::completion::PromptError::Memory). Of
388    /// two runs that loaded the same log, even at once, the second to save
389    /// fails with [`SessionError::Changed`](rig_memory::SessionError::Changed)
390    /// and adds nothing to it. Any rig-memory store will do, a host's
391    /// `Arc<dyn Store>` among them. See the
392    /// [`conversation`](Self::conversation) it keeps.
393    ///
394    /// ```
395    /// use rig_agent::AgentBuilder;
396    /// use rig_core::test_utils::{MockCompletionModel, MockTurn};
397    /// use rig_memory::{MemoryStore, load};
398    ///
399    /// # tokio_test::block_on(async {
400    /// let store = MemoryStore::default();
401    /// let model = MockCompletionModel::from_turns([MockTurn::text("Hi Alice!")]);
402    /// let agent = AgentBuilder::new(model).memory(store.clone()).build();
403    /// agent.prompt("I am Alice.").conversation("alice").await?;
404    /// assert_eq!(load(&store, "alice")?.messages().len(), 2);
405    /// # Ok::<(), Box<dyn std::error::Error>>(())
406    /// # }).unwrap();
407    /// ```
408    pub fn memory(
409        mut self,
410        store: impl rig_memory::AsyncStore
411        + rig_core::wasm_compat::WasmCompatSend
412        + rig_core::wasm_compat::WasmCompatSync
413        + 'static,
414    ) -> Self {
415        self.config.memory = Some(super::memory::Memory::new(store));
416        self
417    }
418
419    /// The log of the [`memory`](Self::memory) store that runs load and
420    /// save, one conversation per log: by default the agent's
421    /// [`name`](Self::name), or `agent`, so agents sharing a store keep
422    /// apart; renaming the agent then starts a new conversation, so name
423    /// the log for one that must outlive a rename. A log name is one part
424    /// of a [`check_name`](rig_memory::check_name) name; a run on one that
425    /// is not fails before its first model call.
426    pub fn conversation(mut self, log: impl Into<String>) -> Self {
427        self.config.conversation = Some(log.into());
428        self
429    }
430
431    /// Observe every dispatch with a caller-owned recorder, installed on
432    /// the agent's handler table at build ([`Handlers::record_to`]). Over a
433    /// host's table that is the host's: it replaces the host's recorder.
434    /// Keep a clone of a shared recorder to inspect its observations.
435    /// Agents that each own a table must not share one recorder, since each
436    /// table numbers its dispatches from 1: build them over one table.
437    pub fn record_to(mut self, recorder: impl Recorder + Send + Sync) -> Self {
438        self.recorder = Some(Arc::new(recorder));
439        self
440    }
441
442    /// Add a hook.
443    pub fn add_hook<H>(mut self, hook: H) -> Self
444    where
445        H: AgentHook + 'static,
446    {
447        self.config.hooks.push(hook);
448        self
449    }
450
451    /// Build the agent.
452    pub fn build(self) -> Agent {
453        let Self {
454            mut config,
455            tools,
456            shared,
457            owner,
458            model,
459            mut pending,
460            dynamic_contexts,
461            recorder,
462            routes,
463        } = self;
464        // Named agents need stable keys across processes for replay.
465        config.owner = Arc::from(
466            owner
467                .or_else(|| config.name.clone())
468                .unwrap_or_else(default_owner),
469        );
470        config.model_key = match model {
471            DefaultModel::Labelled(label, handler) => {
472                let suffix = rig_core::effect::model_key(label.as_str()).to_string();
473                pending.insert(0, (suffix, handler));
474                config.model_key_for(label.as_str())
475            }
476            // A host may register its model after the agent is built; a
477            // key of another family fails the run's first model call.
478            DefaultModel::Key(key) => Key::new_unchecked(key),
479        };
480        for (suffix, handler) in pending {
481            let key = config.raw_key(&suffix);
482            register_generated(config.handlers.register_erased(key, handler));
483        }
484        for (suffix, slot) in dynamic_contexts {
485            // The slot is this builder's own, filled exactly once.
486            let key = config.key(&suffix);
487            config.context_keys.push(key.clone());
488            let _ = slot.set(key);
489        }
490        config.route_keys = routes
491            .iter()
492            .map(|label| config.model_key_for(label))
493            .collect();
494        if let Some(recorder) = recorder {
495            config.handlers.record_with(recorder);
496        }
497        let tool_server_handle = match shared {
498            Some(handle) => {
499                handle.extend(tools);
500                handle
501            }
502            // The builder's own registry takes the agent's owner, so a
503            // named agent's tool keys are stable too.
504            None => tools.owner(config.owner.to_string()).run(),
505        };
506        tool_server_handle.attach(&config.handlers);
507        Agent {
508            tool_server_handle,
509            config,
510        }
511    }
512
513    /// An agent over its own handler table, with `model` registered as the
514    /// default model (label `default`).
515    pub fn new(model: impl Into<rig_core::DynModel<rig_core::operation::Completion>>) -> Self {
516        Self::named_model("default", model)
517    }
518
519    /// An agent over its own handler table, with `model` registered under
520    /// `label`.
521    pub fn named_model(
522        label: impl Into<ModelRef>,
523        model: impl Into<rig_core::DynModel<rig_core::operation::Completion>>,
524    ) -> Self {
525        let label = label.into();
526        let handler = ErasedHandler::new(ModelAdapter::new(label.clone(), model.into()));
527        Self::start(
528            Handlers::default(),
529            None,
530            DefaultModel::Labelled(label, handler),
531        )
532    }
533
534    /// An agent over a host's handler table, using the model under `model`
535    /// verbatim and owner-qualified keys for the handlers it registers. The
536    /// host registers the completion model before running the agent.
537    pub fn over_handlers(handlers: Handlers, owner: impl Into<String>, model: HandlerKey) -> Self {
538        Self::start(handlers, Some(owner.into()), DefaultModel::Key(model))
539    }
540
541    fn start(handlers: Handlers, owner: Option<String>, model: DefaultModel) -> Self {
542        // The model key is a placeholder until build mints the real one
543        // under the owner.
544        let key = Key::new_unchecked(match &model {
545            DefaultModel::Labelled(label, _) => HandlerKey::from(label.as_str()),
546            DefaultModel::Key(key) => key.clone(),
547        });
548        Self {
549            config: AgentConfig::new(handlers, key),
550            tools: ToolServer::new(),
551            shared: None,
552            owner,
553            model,
554            pending: Vec::new(),
555            dynamic_contexts: Vec::new(),
556            recorder: None,
557            routes: Vec::new(),
558        }
559    }
560
561    /// Use a pre-existing shared registry; tools added through the builder
562    /// join it at build.
563    pub fn tool_server_handle(mut self, handle: ToolServerHandle) -> Self {
564        self.shared = Some(handle);
565        self
566    }
567
568    fn map_tools(mut self, add: impl FnOnce(ToolServer) -> ToolServer) -> Self {
569        self.tools = add(std::mem::take(&mut self.tools));
570        self
571    }
572
573    /// Add a typed tool.
574    pub fn tool<T>(self, tool: T) -> Self
575    where
576        T: Tool + 'static,
577    {
578        self.map_tools(|tools| tools.tool(tool))
579    }
580
581    /// Add a runtime-defined tool.
582    pub fn dynamic_tool(self, tool: DynamicTool) -> Self {
583        self.map_tools(|tools| tools.dynamic_tool(tool))
584    }
585
586    /// Add runtime-defined tools.
587    pub fn dynamic_tools(self, tools: Vec<DynamicTool>) -> Self {
588        self.map_tools(|server| server.dynamic_tools(tools))
589    }
590
591    /// Add retrievable tools chosen per request by `index`.
592    pub fn retrieved_tools<I, F>(self, sample: usize, index: I, toolset: ToolSet) -> Self
593    where
594        I: VectorStoreIndex<Filter = F> + 'static,
595        F: DynamicSearchFilter + WasmCompatSend + WasmCompatSync + 'static,
596    {
597        self.map_tools(|tools| tools.retrieved_tools(sample, index, toolset))
598    }
599}
600
601#[cfg(test)]
602mod tests;