1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
//! Agent construction over an owned or host-driven bus. Typestate permits either
//! builder-supplied tools or a shared tool server, not both.
//!
//! ```
//! use rig_agent::core::{DynModel, operation::Completion};
//! use rig_agent::{Agent, AgentBuilder};
//! fn assistant(model: impl Into<DynModel<Completion>>) -> Agent {
//! AgentBuilder::new(model).preamble("Be concise.").build()
//! }
//! ```
use std::sync::{Arc, OnceLock};
use crate::bus::{Bus, Dispatcher, Recording, Registrar};
use rig_core::serve::ServingPolicy;
use rig_core::serve::adapters::{MemoryAdapter, ModelAdapter, RetrieveAdapter};
use rig_core::serve::{ErasedHandler, Recorder};
use rig_core::{
completion::{Document, ModelRef},
effect::{HandlerKey, Key, family},
memory::ConversationMemory,
vector_store::{VectorSearchRequest, VectorStoreIndex, request::DynamicSearchFilter},
wasm_compat::{WasmCompatSend, WasmCompatSync},
};
use schemars::{JsonSchema, Schema, schema_for};
use crate::{
agent::{AgentHook, CompletionCallAction, CompletionCallEvent, HookContext, RequestPatch},
completion::message::ToolChoice,
tool::{
DynamicTool, Tool, ToolSet,
server::{ToolServer, ToolServerHandle},
},
};
use super::{Agent, OutputMode, completion::AgentConfig, drive::AgentBus};
/// The `dynamic_context` hook: retrieves documents for the prompt through
/// the agent's bus (an `IndexHandle` bound to the index registered at
/// build) and patches them into the request as extra context.
struct DynamicContext {
samples: usize,
/// The index's key, minted at build once the agent's owner is known.
key: Arc<OnceLock<Key<family::Retrieve>>>,
}
impl AgentHook for DynamicContext {
async fn on_completion_call(
&self,
ctx: &HookContext,
event: CompletionCallEvent<'_>,
) -> CompletionCallAction {
let query = event.prompt.rag_text().or_else(|| {
event
.history
.iter()
.rev()
.find_map(rig_core::completion::Message::rag_text)
});
let Some(query) = query else {
return CompletionCallAction::continue_run();
};
let Some(key) = self.key.get() else {
return CompletionCallAction::stop(
"dynamic context is keyed at build; this hook was not built",
);
};
let index = match ctx.bind(key) {
Ok(index) => index,
Err(report) => {
return CompletionCallAction::stop(format!(
"failed to bind the dynamic context index: {report}"
));
}
};
let request = VectorSearchRequest::builder()
.query(query)
.samples(self.samples as u64)
.build();
match index.top_n::<serde_json::Value>(request).await {
Ok(results) => CompletionCallAction::patch(RequestPatch::new().extra_context(
results.into_iter().map(|result| {
Document {
text: serde_json::to_string_pretty(&result.document)
.unwrap_or_else(|_| result.document.to_string()),
id: result.id,
additional_props: Default::default(),
}
}),
)),
Err(error) => {
CompletionCallAction::stop(format!("failed to retrieve dynamic context: {error}"))
}
}
}
}
/// Typestate: no tools configured.
#[derive(Default)]
pub struct NoToolConfig;
/// Typestate: a pre-existing shared registry supplies the tools.
pub struct WithToolServerHandle {
handle: ToolServerHandle,
}
/// Typestate: tools added through the builder.
pub struct WithBuilderTools(ToolServer);
/// Where the built agent's bus comes from.
enum BusSource {
/// The agent's own bus, created at build with this sizing.
Owned(ServingPolicy),
/// A host's bus; the host drives it. The agent registers on it through
/// the host's registrar.
Host(Dispatcher, Registrar),
}
/// The default model: a model the builder registers under a label, or the
/// key of one already registered on a host's bus.
enum DefaultModel {
Labelled(ModelRef, ErasedHandler),
/// An explicit key and the host's line that asserted it.
Key(HandlerKey, &'static std::panic::Location<'static>),
}
/// Builds an [`Agent`].
///
/// Every handler the builder registers (the default model, model routes,
/// memory, dynamic-context indexes) is minted a key under the agent's
/// owner label at build: `<owner>/model:<label>`, `<owner>/memory`, and
/// `<owner>/retrieve:context#<n>`. Hosts sharing a bus must choose distinct
/// owners to avoid replacing each other's bindings. The explicit owner takes
/// precedence over the agent name, then a generated `agent#<n>` label.
pub struct AgentBuilder<ToolState = NoToolConfig> {
config: AgentConfig,
tool_state: ToolState,
bus: BusSource,
owner: Option<String>,
model: DefaultModel,
/// Handlers to register at build, by key suffix.
pending: Vec<(String, ErasedHandler)>,
/// The dynamic-context hooks' key slots, by key suffix.
dynamic_contexts: Vec<(String, Arc<OnceLock<Key<family::Retrieve>>>)>,
memory: bool,
recorder: Option<Recording>,
retrieval_indexes: usize,
/// The labels `model_route` registered, in order.
routes: Vec<String>,
}
impl<ToolState> AgentBuilder<ToolState> {
/// Name the agent.
pub fn name(mut self, name: impl Into<String>) -> Self {
self.config.name = Some(name.into());
self
}
/// Describe the agent.
pub fn description(mut self, description: impl Into<String>) -> Self {
self.config.description = Some(description.into());
self
}
/// Set the system prompt.
pub fn preamble(mut self, preamble: impl Into<String>) -> Self {
self.config.preamble = Some(preamble.into());
self
}
/// Clear the system prompt.
pub fn without_preamble(mut self) -> Self {
self.config.preamble = None;
self
}
/// Append a paragraph to the system prompt.
pub fn append_preamble(mut self, doc: &str) -> Self {
self.config.preamble = Some(format!(
"{}\n{}",
self.config.preamble.unwrap_or_default(),
doc
));
self
}
/// Add a static context document.
pub fn context(mut self, doc: impl Into<String>) -> Self {
self.config.static_context.push(Document {
id: format!("static_doc_{}", self.config.static_context.len()),
text: doc.into(),
additional_props: Default::default(),
});
self
}
/// Retrieve `samples` documents from `index` for every prompt and add
/// them as context. The index is registered on the agent's bus.
pub fn dynamic_context<I, F>(mut self, samples: usize, index: I) -> Self
where
I: VectorStoreIndex<Filter = F> + 'static,
F: DynamicSearchFilter + WasmCompatSend + WasmCompatSync + 'static,
{
let n = self.retrieval_indexes;
self.retrieval_indexes += 1;
let suffix = format!("retrieve:context#{n}");
let key = Arc::new(OnceLock::new());
self.pending.push((
suffix.clone(),
ErasedHandler::new(RetrieveAdapter::new(index)),
));
self.dynamic_contexts.push((suffix, key.clone()));
self.add_hook(DynamicContext { samples, key })
}
/// Retrieve `samples` documents through a retrieval-family handler registered
/// under the next context key, using the dynamic-context hook lifecycle.
pub fn dynamic_context_handler(
mut self,
samples: usize,
handler: impl rig_core::serve::Serve + 'static,
) -> Self {
let n = self.retrieval_indexes;
self.retrieval_indexes += 1;
let suffix = format!("retrieve:context#{n}");
let key = Arc::new(OnceLock::new());
self.pending
.push((suffix.clone(), ErasedHandler::new(handler)));
self.dynamic_contexts.push((suffix, key.clone()));
self.add_hook(DynamicContext { samples, key })
}
/// Set the tool choice.
pub fn tool_choice(mut self, tool_choice: ToolChoice) -> Self {
self.config.tool_choice = Some(tool_choice);
self
}
/// Set the default maximum number of turns.
pub fn default_max_turns(mut self, default_max_turns: usize) -> Self {
self.config.max_turns = default_max_turns;
self
}
/// Set the sampling temperature.
pub fn temperature(mut self, temperature: f64) -> Self {
self.config.temperature = Some(temperature);
self
}
/// Remove the sampling temperature, for test scenarios run against
/// models that reject it.
#[cfg(any(test, feature = "test-utils"))]
pub(crate) fn clear_temperature(mut self) -> Self {
self.config.temperature = None;
self
}
/// Set the output-token cap.
pub fn max_tokens(mut self, max_tokens: u64) -> Self {
self.config.max_tokens = Some(max_tokens);
self
}
/// Set provider passthrough parameters.
pub fn additional_params(mut self, params: serde_json::Value) -> Self {
self.config.additional_params = Some(params);
self
}
/// Set the portable generation options every request of this agent
/// carries. A run's [`AgentRunner::options`](crate::agent::AgentRunner::options)
/// overlays them field by field. Calls apply in order: this replaces
/// every field, so a shortcut such as [`Self::seed`] called before it is
/// lost, and one called after it sets its one field on top.
pub fn options(mut self, options: rig_core::completion::GenerationOptions) -> Self {
self.config.options = options;
self
}
/// Set the reasoning level or budget in the agent's generation options, as
/// [`GenerationOptions::reasoning`](rig_core::completion::GenerationOptions::reasoning) does,
/// keeping its other fields. See
/// [`Self::options`] for the order of calls.
pub fn reasoning(mut self, reasoning: impl Into<rig_core::completion::Reasoning>) -> Self {
self.config.options = std::mem::take(&mut self.config.options).reasoning(reasoning);
self
}
/// Set the cache retention in the agent's generation options, as
/// [`GenerationOptions::cache`](rig_core::completion::GenerationOptions::cache) does,
/// keeping its other fields. See
/// [`Self::options`] for the order of calls.
pub fn cache(mut self, cache: rig_core::completion::CacheRetention) -> Self {
self.config.options = std::mem::take(&mut self.config.options).cache(cache);
self
}
/// Set the service tier in the agent's generation options, as
/// [`GenerationOptions::service_tier`](rig_core::completion::GenerationOptions::service_tier) does,
/// keeping its other fields. See
/// [`Self::options`] for the order of calls.
pub fn service_tier(mut self, tier: rig_core::completion::ServiceTier) -> Self {
self.config.options = std::mem::take(&mut self.config.options).service_tier(tier);
self
}
/// Set the answer verbosity in the agent's generation options, as
/// [`GenerationOptions::verbosity`](rig_core::completion::GenerationOptions::verbosity) does,
/// keeping its other fields. See
/// [`Self::options`] for the order of calls.
pub fn verbosity(mut self, verbosity: rig_core::completion::Verbosity) -> Self {
self.config.options = std::mem::take(&mut self.config.options).verbosity(verbosity);
self
}
/// Set whether the model may call several tools in one turn in the agent's generation options, as
/// [`GenerationOptions::parallel_tool_calls`](rig_core::completion::GenerationOptions::parallel_tool_calls) does,
/// keeping its other fields. See
/// [`Self::options`] for the order of calls.
pub fn parallel_tool_calls(mut self, parallel: bool) -> Self {
self.config.options =
std::mem::take(&mut self.config.options).parallel_tool_calls(parallel);
self
}
/// Set the nucleus sampling probability mass in the agent's generation options, as
/// [`GenerationOptions::top_p`](rig_core::completion::GenerationOptions::top_p) does,
/// keeping its other fields. See
/// [`Self::options`] for the order of calls.
pub fn top_p(mut self, top_p: f64) -> Self {
self.config.options = std::mem::take(&mut self.config.options).top_p(top_p);
self
}
/// Set the sampling seed in the agent's generation options, as
/// [`GenerationOptions::seed`](rig_core::completion::GenerationOptions::seed) does,
/// keeping its other fields. See
/// [`Self::options`] for the order of calls.
pub fn seed(mut self, seed: u64) -> Self {
self.config.options = std::mem::take(&mut self.config.options).seed(seed);
self
}
/// Set the stop sequences in the agent's generation options, as
/// [`GenerationOptions::stop`](rig_core::completion::GenerationOptions::stop) does,
/// keeping its other fields. See
/// [`Self::options`] for the order of calls.
pub fn stop<S: Into<String>>(mut self, stop: impl IntoIterator<Item = S>) -> Self {
self.config.options = std::mem::take(&mut self.config.options).stop(stop);
self
}
/// Set what happens to an option the wire or model cannot honour in the agent's generation options, as
/// [`GenerationOptions::on_unsupported`](rig_core::completion::GenerationOptions::on_unsupported) does,
/// keeping its other fields. See
/// [`Self::options`] for the order of calls.
pub fn on_unsupported(mut self, policy: rig_core::completion::OnUnsupported) -> Self {
self.config.options = std::mem::take(&mut self.config.options).on_unsupported(policy);
self
}
/// Set the typed per-provider options every request of this agent
/// carries. A run's
/// [`AgentRunner::provider_options`](crate::agent::AgentRunner::provider_options)
/// replaces the entry of each provider it names.
///
/// Calls apply in order: this replaces every entry, so an entry set by
/// an earlier [`Self::provider_option`] is lost, and a later
/// [`Self::provider_option`] replaces its provider's entry on top.
pub fn provider_options(mut self, options: rig_core::completion::ProviderOptions) -> Self {
self.config.provider_options = options;
self
}
/// Store `options` as the entry of their provider
/// ([`ExtensionOptions::Ext`](rig_core::completion::ExtensionOptions::Ext))
/// in the provider options every request of this agent carries,
/// replacing that provider's entry and keeping every other
/// ([`ProviderOptions::set`](rig_core::completion::ProviderOptions::set)).
/// Options that do not serialize fail each request's encode. A
/// third-party provider reusing a built-in options type needs
/// [`ProviderOptions::with::<P>`](rig_core::completion::ProviderOptions::with)
/// and [`Self::provider_options`]: this stores under the built-in key.
pub fn provider_option<O: rig_core::completion::ExtensionOptions>(
mut self,
options: O,
) -> Self {
self.config.provider_options =
std::mem::take(&mut self.config.provider_options).set(options);
self
}
/// Check the generation options of every model call against the
/// catalog entry of the model the call goes to, before it is sent:
/// `spec` (the agent's own model's entry) for a call to the model the
/// agent was built with, and for a call to another model (a run's
/// [`using_model`](crate::agent::AgentRunner::using_model) or
/// [`using_model_value`](crate::agent::AgentRunner::using_model_value),
/// [`Agent::set_model`](crate::agent::Agent::set_model), a
/// [`model_route`](Self::model_route) a model-selection hook picks) the
/// built-in catalog's entry for the provider and model id that model was
/// registered with. A model the catalog does not list, or one served by
/// a handler rig cannot see the model id of (a host's key, a
/// [`model_route_handler`](Self::model_route_handler)), is not checked,
/// and the run logs a warning saying so. Under
/// [`OnUnsupported::Error`](rig_core::completion::OnUnsupported::Error) an
/// option the model does not take fails the run with
/// [`ProviderError::UnsupportedOption`](rig_core::error::ProviderError::UnsupportedOption)
/// before that call is sent; under `Ignore` it is dropped from that call
/// with a warning.
pub fn model_spec(mut self, spec: rig_core::catalog::ModelSpec) -> Self {
self.config.model_spec = Some(spec);
self
}
/// Enable or disable sensitive message content on telemetry spans.
/// Disabled by default; enabling may expose prompts, responses, and tool data.
pub fn record_content_telemetry(mut self, enabled: bool) -> Self {
self.config.record_telemetry_content = enabled;
self
}
/// Accept finish reasons outside the normalized vocabulary
/// ([`FinishReason::Other`](rig_core::completion::FinishReason::Other))
/// as a normal stop. Off by default: such a turn fails the run,
/// and history replay leaves it out. When on, the turn succeeds, its
/// tool calls run, and it replays.
///
/// `Other` also holds genuine failures, such as Gemini's
/// `MALFORMED_FUNCTION_CALL` and `RECITATION` or Bedrock's
/// `malformed_tool_use`, so tool calls from a malformed reply may run.
/// Filtered content still fails the turn.
pub fn accept_unknown_finish_reasons(mut self, accept: bool) -> Self {
self.config.accept_unknown_finish_reasons = accept;
self
}
/// Constrain the output to `T`'s JSON schema.
pub fn output_schema<T>(mut self) -> Self
where
T: JsonSchema,
{
self.config.output_schema = Some(schema_for!(T));
self
}
/// Constrain the output to a raw JSON schema.
pub fn output_schema_raw(mut self, schema: Schema) -> Self {
self.config.output_schema = Some(schema);
self
}
/// Set the structured-output mode.
pub fn output_mode(mut self, mode: OutputMode) -> Self {
self.config.output_mode = mode;
self
}
/// Persist and load conversation history through `memory`, registered
/// on the agent's bus.
pub fn memory<B>(mut self, memory: B) -> Self
where
B: ConversationMemory + 'static,
{
self.pending.push((
"memory".to_owned(),
ErasedHandler::new(MemoryAdapter::new(memory)),
));
self.memory = true;
self
}
/// Register a memory-family handler under the agent's memory key.
pub fn memory_handler(mut self, handler: impl rig_core::serve::Serve + 'static) -> Self {
self.pending
.push(("memory".to_owned(), ErasedHandler::new(handler)));
self.memory = true;
self
}
/// The conversation id memory loads and saves under.
pub fn conversation(mut self, id: impl Into<rig_core::id::ConversationId>) -> Self {
self.config.conversation_id = Some(id.into());
self
}
/// Register another model the run can select by label
/// (`ModelSelectionAction::select(label)`, `using_model(label)`).
pub fn model_route(
mut self,
label: impl Into<ModelRef>,
model: impl Into<rig_core::DynModel<rig_core::operation::Completion>>,
) -> Self {
let label = label.into();
let model = model.into();
let suffix = rig_core::effect::model_key(label.as_str()).to_string();
self.config
.pending_model_ids
.push((suffix.clone(), crate::agent::drive::ModelId::of(&model)));
self.routes.push(label.as_str().to_owned());
self.pending
.push((suffix, ErasedHandler::new(ModelAdapter::new(label, model))));
self
}
/// Register a completion-family handler under the route key for `label`.
/// Includes that route in the program's required effect row.
pub fn model_route_handler(
mut self,
label: impl Into<ModelRef>,
handler: impl rig_core::serve::Serve + 'static,
) -> Self {
let label = label.into();
self.routes.push(label.as_str().to_owned());
self.pending.push((
rig_core::effect::model_key(label.as_str()).to_string(),
ErasedHandler::new(handler),
));
self
}
/// Name the agent's keys: `<owner>/model:<label>`, `<owner>/memory`,
/// `<owner>/retrieve:context#<n>`, and its own tools' `<owner>/tool:…`.
/// Defaults to the agent's name, or a process-local `agent#<n>` counter.
/// Use stable, distinct owners for replay and agents sharing a bus.
pub fn owner(mut self, label: impl Into<String>) -> Self {
self.owner = Some(label.into());
self
}
/// Configure the owned bus, which serves concurrently by default.
/// Runner tool concurrency is independent. Has no effect on a host-owned
/// bus and emits a warning in that case.
pub fn configure_bus(mut self, bus_config: ServingPolicy) -> Self {
match &mut self.bus {
BusSource::Owned(config) => *config = bus_config,
BusSource::Host(..) => tracing::warn!(
"AgentBuilder::configure_bus has no effect over a host's bus; the host sized it"
),
}
self
}
/// Observe every dispatch with a caller-owned recorder.
///
/// Keep a clone of a shared recorder to inspect its observations. The
/// driver retains the installed instance even after [`Agent::into_parts`].
/// Like [`BusDriver::record_to`](crate::bus::BusDriver::record_to), this
/// requires a thread-safe recorder on every target because reply observers
/// cross the bus's thread-safe channels, including on browser WASM.
///
/// An agent over a host's bus cannot install a recorder; the host owns
/// that driver's recording policy. Asking here fails at build.
pub fn record_to(mut self, recorder: impl Recorder + Send + Sync) -> Self {
self.recorder = Some(Recording::new(recorder));
self
}
/// Add a hook.
pub fn add_hook<H>(mut self, hook: H) -> Self
where
H: AgentHook + 'static,
{
self.config.hooks.push(hook);
self
}
fn with_tool_state<S>(self, tool_state: S) -> AgentBuilder<S> {
AgentBuilder {
config: self.config,
tool_state,
bus: self.bus,
owner: self.owner,
model: self.model,
pending: self.pending,
dynamic_contexts: self.dynamic_contexts,
memory: self.memory,
recorder: self.recorder,
retrieval_indexes: self.retrieval_indexes,
routes: self.routes,
}
}
fn build_agent(self, handle: impl FnOnce(ToolState, &str) -> ToolServerHandle) -> Agent {
/// A host's `over_bus` key that serves another family: the host's
/// programming error, reported at the host's line.
#[allow(
clippy::panic,
reason = "a wrong-family host key is a programming error at the host's call site, not a runtime condition; `build` stays infallible for every other case"
)]
fn host_key_of_another_family(
key: &HandlerKey,
caller: &'static std::panic::Location<'static>,
family: rig_core::effect::EffectFamily,
) -> ! {
panic!(
"the model key `{key}` handed to `over_bus` at {caller} serves the {family} family, not a completion model"
)
}
/// Panic at the host's construction site when an agent tries to replace
/// recording policy on a driver it does not own.
#[allow(
clippy::panic,
reason = "recording over a host's bus is a programming error at the host's call site, not a runtime condition; `build` stays infallible for every other case"
)]
fn recording_over_a_hosts_bus(caller: &'static std::panic::Location<'static>) -> ! {
panic!(
"the agent built over a host's bus at {caller} cannot record: the host records through its driver (`BusDriver::record_to`)"
)
}
let Self {
mut config,
tool_state,
bus,
owner,
model,
mut pending,
dynamic_contexts,
memory,
recorder,
retrieval_indexes: _,
routes,
} = self;
let host = match &model {
DefaultModel::Key(_, caller) => Some(*caller),
DefaultModel::Labelled(..) => None,
};
// Named agents need stable keys across processes for replay.
let owner = owner
.or_else(|| config.name.clone())
.unwrap_or_else(crate::agent::drive::default_owner);
config.bus = match bus {
BusSource::Owned(bus_config) => {
let (dispatcher, registrar, driver) = Bus::channel_with(bus_config);
AgentBus::owned(dispatcher, registrar, driver, owner, bus_config)
}
BusSource::Host(dispatcher, registrar) => AgentBus::over(dispatcher, registrar, owner),
};
config.model_key = match model {
DefaultModel::Labelled(label, handler) => {
let suffix = rig_core::effect::model_key(label.as_str()).to_string();
pending.insert(0, (suffix, handler));
config.bus.model_key(label.as_str())
}
DefaultModel::Key(key, caller) => {
// Reject an incompatible host binding now, but allow missing keys
// because hosts may register them after construction.
if let Some(descriptor) = config.bus.dispatcher().descriptor(&key)
&& descriptor.family.family()
!= <family::Completion as rig_core::effect::Family>::FAMILY
{
host_key_of_another_family(&key, caller, descriptor.family.family());
}
Key::new_unchecked(key)
}
};
for (suffix, handler) in pending {
let key = config.bus.raw_key(&suffix);
crate::agent::drive::register_generated(config.bus.register_erased(key, handler));
}
for (suffix, id) in std::mem::take(&mut config.pending_model_ids) {
config
.bus
.note_model(config.bus.raw_key(&suffix).as_str(), id);
}
config.model_spec_key = Some(config.model_key.clone());
for (suffix, slot) in dynamic_contexts {
// The slot is this builder's own, filled exactly once.
let key = config.bus.key(&suffix);
config.context_keys.push(key.clone());
let _ = slot.set(key);
}
config.route_keys = routes
.iter()
.map(|label| config.bus.model_key(label))
.collect();
if memory {
config.memory_key = Some(config.bus.key("memory"));
} else if let Some(conversation) = &config.conversation_id {
// Warn once at construction rather than silently ignoring memory on each run.
tracing::warn!(
%conversation,
"AgentBuilder::conversation set without memory(..) or memory_handler(..): nothing is loaded or saved"
);
}
if let Some(recorder) = recorder {
match (host, config.bus.record_to(recorder)) {
(Some(caller), Err(_)) => recording_over_a_hosts_bus(caller),
(None, registered) => crate::agent::drive::register_generated(registered),
(Some(_), Ok(())) => {}
}
}
let tool_server_handle = handle(tool_state, config.bus.owner());
tool_server_handle.attach(config.bus.registrar());
Agent {
tool_server_handle,
config,
}
}
}
impl AgentBuilder<NoToolConfig> {
/// An agent over its own bus, with `model` registered as the default
/// model (label `default`).
pub fn new(model: impl Into<rig_core::DynModel<rig_core::operation::Completion>>) -> Self {
Self::named_model("default", model)
}
/// An agent over its own bus, with `model` registered under `label`.
/// Size the bus with [`configure_bus`](Self::configure_bus).
pub fn named_model(
label: impl Into<ModelRef>,
model: impl Into<rig_core::DynModel<rig_core::operation::Completion>>,
) -> Self {
let label = label.into();
let model = model.into();
let id = crate::agent::drive::ModelId::of(&model);
let handler = ErasedHandler::new(ModelAdapter::new(label.clone(), model));
let mut builder = Self::start(
BusSource::Owned(ServingPolicy::default()),
None,
DefaultModel::Labelled(label.clone(), handler),
);
builder
.config
.pending_model_ids
.push((rig_core::effect::model_key(label.as_str()).to_string(), id));
builder
}
/// Build over a host-driven bus using `model` verbatim and owner-qualified
/// keys for additional handlers. `dispatcher` and `registrar` must name the
/// same bus; register the completion model before running the agent.
/// Building panics for an existing wrong-family model binding or a requested
/// recorder, since the host owns recording policy.
#[track_caller]
pub fn over_bus(
dispatcher: Dispatcher,
registrar: Registrar,
owner: impl Into<String>,
model: HandlerKey,
) -> Self {
Self::start(
BusSource::Host(dispatcher, registrar),
Some(owner.into()),
DefaultModel::Key(model, std::panic::Location::caller()),
)
}
fn start(bus: BusSource, owner: Option<String>, model: DefaultModel) -> Self {
// The config's bus and model key are placeholders until build mints
// the real ones under the owner.
let (placeholder, placeholder_registrar, _driver) =
Bus::channel_with(ServingPolicy::default());
let key = Key::new_unchecked(match &model {
DefaultModel::Labelled(label, _) => HandlerKey::from(label.as_str()),
DefaultModel::Key(key, _) => key.clone(),
});
Self {
config: AgentConfig::new(
AgentBus::over(placeholder, placeholder_registrar, String::new()),
key,
),
tool_state: NoToolConfig,
bus,
owner,
model,
pending: Vec::new(),
dynamic_contexts: Vec::new(),
memory: false,
recorder: None,
retrieval_indexes: 0,
routes: Vec::new(),
}
}
/// Use a pre-existing shared registry.
pub fn tool_server_handle(
self,
handle: ToolServerHandle,
) -> AgentBuilder<WithToolServerHandle> {
self.with_tool_state(WithToolServerHandle { handle })
}
fn into_tool_builder(self) -> AgentBuilder<WithBuilderTools> {
self.with_tool_state(WithBuilderTools(ToolServer::new()))
}
/// Add a typed tool.
pub fn tool<T>(self, tool: T) -> AgentBuilder<WithBuilderTools>
where
T: Tool + 'static,
{
self.into_tool_builder().tool(tool)
}
/// Build the agent with no tools.
pub fn build(self) -> Agent {
self.build_agent(|_, owner| ToolServer::new().owner(owner).run())
}
}
impl AgentBuilder<NoToolConfig> {
/// Add a runtime-defined tool.
pub fn dynamic_tool(self, tool: DynamicTool) -> AgentBuilder<WithBuilderTools> {
self.into_tool_builder().dynamic_tool(tool)
}
/// Add runtime-defined tools.
pub fn dynamic_tools(self, tools: Vec<DynamicTool>) -> AgentBuilder<WithBuilderTools> {
self.into_tool_builder().dynamic_tools(tools)
}
/// Add retrievable tools chosen per request by `index`.
pub fn retrieved_tools<I, F>(
self,
sample: usize,
index: I,
toolset: ToolSet,
) -> AgentBuilder<WithBuilderTools>
where
I: VectorStoreIndex<Filter = F> + 'static,
F: DynamicSearchFilter + WasmCompatSend + WasmCompatSync + 'static,
{
self.into_tool_builder()
.retrieved_tools(sample, index, toolset)
}
/// Add retrievable tools chosen per request by `handler`, a
/// retrieval-family handler such as a replayer answering a recorded
/// index; see [`ToolServer::retrieved_tools_handler`].
pub fn retrieved_tools_handler(
self,
sample: usize,
handler: impl rig_core::serve::Serve + 'static,
toolset: ToolSet,
) -> AgentBuilder<WithBuilderTools> {
self.into_tool_builder()
.retrieved_tools_handler(sample, handler, toolset)
}
}
impl AgentBuilder<WithToolServerHandle> {
/// Build the agent over the shared registry.
pub fn build(self) -> Agent {
self.build_agent(|state, _| state.handle)
}
}
impl AgentBuilder<WithBuilderTools> {
fn map_server(self, register: impl FnOnce(ToolServer) -> ToolServer) -> Self {
let Self {
config,
tool_state,
bus,
owner,
model,
pending,
dynamic_contexts,
memory,
recorder,
retrieval_indexes,
routes,
} = self;
Self {
config,
tool_state: WithBuilderTools(register(tool_state.0)),
bus,
owner,
model,
pending,
dynamic_contexts,
memory,
recorder,
retrieval_indexes,
routes,
}
}
/// Add a typed tool.
pub fn tool<T>(self, tool: T) -> Self
where
T: Tool + 'static,
{
self.map_server(|server| server.tool(tool))
}
/// Add a runtime-defined tool.
pub fn dynamic_tool(self, tool: DynamicTool) -> Self {
self.map_server(|server| server.dynamic_tool(tool))
}
/// Add runtime-defined tools.
pub fn dynamic_tools(self, tools: Vec<DynamicTool>) -> Self {
self.map_server(|server| server.dynamic_tools(tools))
}
/// Add retrievable tools chosen per request by `index`.
pub fn retrieved_tools<I, F>(self, sample: usize, index: I, toolset: ToolSet) -> Self
where
I: VectorStoreIndex<Filter = F> + 'static,
F: DynamicSearchFilter + WasmCompatSend + WasmCompatSync + 'static,
{
self.map_server(|server| server.retrieved_tools(sample, index, toolset))
}
/// Add retrievable tools chosen per request by `handler`, a
/// retrieval-family handler such as a replayer answering a recorded
/// index; see [`ToolServer::retrieved_tools_handler`].
pub fn retrieved_tools_handler(
self,
sample: usize,
handler: impl rig_core::serve::Serve + 'static,
toolset: ToolSet,
) -> Self {
self.map_server(|server| server.retrieved_tools_handler(sample, handler, toolset))
}
/// Build the agent with the builder's tools.
pub fn build(self) -> Agent {
// The builder's own registry takes the agent's owner, so a named
// agent's tool keys are stable too.
self.build_agent(|state, owner| state.0.owner(owner).run())
}
}
#[cfg(test)]
mod tests;