rig_core/catalog/connector.rs
1//! How a catalog's models are reached: through a provider registered for
2//! their vendor, else with the environment's keys, else through a sign-in,
3//! such as a subscription plan's. Every HTTP client a model is reached
4//! through can be wrapped, such as to log or rotate keys.
5
6use std::borrow::Cow;
7use std::collections::HashMap;
8use std::fmt;
9use std::sync::Arc;
10
11use super::{Catalog, ModelSpec};
12use crate::http_client::DynHttpClient;
13use crate::operation::Completion;
14use crate::providers::registry::{ConnectError, ConnectOptions, ProviderId};
15use crate::serve::ErasedHandler;
16use crate::serve::adapters::ModelAdapter;
17use crate::wasm_compat::{WasmCompatSend, WasmCompatSync};
18
19/// A way to reach catalog models no key is set for, such as a
20/// subscription plan signed in to. A [`Connector`] asks it for a model only
21/// when the provider registered for the model's vendor, else the
22/// environment, has no key for it.
23pub trait SignIn: WasmCompatSend + WasmCompatSync + 'static {
24 /// The handler serving `spec` with the signed-in credential, or `None`
25 /// when this sign-in does not serve `spec` now. A handler that sends
26 /// HTTP sends through `transport`.
27 fn handler(
28 &self,
29 spec: &ModelSpec,
30 transport: &Transport,
31 ) -> Option<Result<ErasedHandler, ConnectError>>;
32 /// The name of the subscription plan through which this sign-in would
33 /// serve `spec`, such as `"ChatGPT"`, whether or not the user is signed
34 /// in; for model pickers.
35 fn plan(&self, spec: &ModelSpec) -> Option<&'static str>;
36
37 /// Whether the signed-in account offers `spec`. Asked only for a model
38 /// this sign-in serves. Must answer at once without blocking; return
39 /// [`ModelStatus::Checking`] while finding out.
40 fn offers(&self, _spec: &ModelSpec, _transport: &Transport) -> ModelStatus {
41 ModelStatus::Usable
42 }
43}
44
45/// How a [`Connector`] reaches every model of one vendor, in place of the
46/// registry's preset and the environment: a vendor declared at run time
47/// ([`ProviderId::declare`]) on a gateway of its own, a built-in vendor at
48/// another address, or a scripted model in a test.
49///
50/// [`ConnectOptions`] is one: the vendor's models connect with those
51/// options (a base URL, a key, an HTTP client, a protocol family). A
52/// closure from the spec, the catalog and the transport to a handler is
53/// another.
54pub trait Provide: WasmCompatSend + WasmCompatSync + 'static {
55 /// The handler serving `spec`, a model of `catalog`. A handler that
56 /// sends HTTP sends through `transport`: its shared client, or a client
57 /// of its own that it wraps.
58 fn handler(
59 &self,
60 spec: &ModelSpec,
61 catalog: &Catalog,
62 transport: &Transport,
63 ) -> Result<ErasedHandler, ConnectError>;
64}
65
66impl<F> Provide for F
67where
68 F: Fn(&ModelSpec, &Catalog, &Transport) -> Result<ErasedHandler, ConnectError>
69 + WasmCompatSend
70 + WasmCompatSync
71 + 'static,
72{
73 fn handler(
74 &self,
75 spec: &ModelSpec,
76 catalog: &Catalog,
77 transport: &Transport,
78 ) -> Result<ErasedHandler, ConnectError> {
79 self(spec, catalog, transport)
80 }
81}
82
83/// The vendor's models connect as [`Catalog::connect_with`] connects them
84/// with these options, on their HTTP client, else the shared one, wrapped
85/// by the transport.
86impl Provide for ConnectOptions {
87 fn handler(
88 &self,
89 spec: &ModelSpec,
90 catalog: &Catalog,
91 transport: &Transport,
92 ) -> Result<ErasedHandler, ConnectError> {
93 let mut options = self.clone();
94 options.http = match options.http {
95 Some(own) => Some(transport.wrap(own)),
96 None => transport.shared(),
97 };
98 catalog
99 .connect_with(spec, options)
100 .map(|model| adapted(spec, model))
101 }
102}
103
104/// `model`, which serves `spec`, as an effect handler labelled with the
105/// spec's reference.
106fn adapted(spec: &ModelSpec, model: crate::driver::DynModel<Completion>) -> ErasedHandler {
107 ErasedHandler::new(ModelAdapter::<Completion>::new(spec.reference(), model))
108}
109
110/// One wrapper of a [`Transport`], `Send` and `Sync` outside browser wasm.
111#[cfg(not(target_family = "wasm"))]
112type Wrapper = Arc<dyn Fn(DynHttpClient) -> DynHttpClient + Send + Sync>;
113/// One wrapper of a [`Transport`], which may hold browser values.
114#[cfg(target_family = "wasm")]
115type Wrapper = Arc<dyn Fn(DynHttpClient) -> DynHttpClient>;
116
117/// The wrappers a [`Connector`] applies to every HTTP client its models are
118/// reached through, in the order added: the first is closest to the
119/// network. Cloning is cheap.
120///
121/// ```
122/// use rig_core::catalog::Transport;
123/// use rig_core::http_client::DynHttpClient;
124///
125/// fn reach(transport: &Transport, own: DynHttpClient) -> DynHttpClient {
126/// // A provider with a client of its own wraps it; one without takes
127/// // the shared client, when the build has one.
128/// transport.wrap(own)
129/// }
130/// ```
131#[derive(Clone, Default)]
132pub struct Transport {
133 wrappers: Vec<Wrapper>,
134}
135
136impl Transport {
137 /// `base` with every wrapper applied.
138 pub fn wrap(&self, base: DynHttpClient) -> DynHttpClient {
139 self.wrappers.iter().fold(base, |client, wrap| wrap(client))
140 }
141
142 /// The shared client, wrapped, when the build has one (the `reqwest`
143 /// feature); `None` otherwise, such as on the web.
144 pub fn shared(&self) -> Option<DynHttpClient> {
145 #[cfg(feature = "reqwest")]
146 {
147 Some(self.wrap(rig_reqwest::shared()))
148 }
149 #[cfg(not(feature = "reqwest"))]
150 {
151 None
152 }
153 }
154}
155
156/// Shows how many wrappers there are.
157impl fmt::Debug for Transport {
158 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159 f.debug_struct("Transport")
160 .field("wrappers", &self.wrappers.len())
161 .finish()
162 }
163}
164
165/// Whether a [`Connector`] can reach a catalog model for an agent, and why
166/// not, for a picker's note.
167#[derive(Clone, Debug, PartialEq, Eq)]
168pub enum ModelStatus {
169 /// It calls tools, connects, and any sign-in serving it offers it.
170 Usable,
171 /// The sign-in serving it is still finding out whether its account offers it.
172 Checking,
173 /// The account served by the sign-in does not offer it, with a reason for logs.
174 NotOffered(String),
175 /// It calls tools, but no key is set: the variables read, in order.
176 NoKey(Vec<Cow<'static, str>>),
177 /// Its provider needs no key, such as a local server, and nothing
178 /// configures it: no provider is registered for it and the environment
179 /// sets neither its key nor its base URL. It connects when named, at
180 /// its default address, but nothing says a server runs there.
181 Unconfigured,
182 /// It does not call tools, so an agent cannot use it.
183 NoTools,
184 /// It calls tools but does not connect, for this reason.
185 Unavailable(String),
186}
187
188/// The models an application can use and how each is reached: a catalog,
189/// rig's built-in one by default, whose models connect through the
190/// provider registered for their vendor ([`Self::provide`]), else with the
191/// environment's keys, else through the first [`SignIn`] that serves them,
192/// each on an HTTP client wrapped by its [`Transport`]. Cloning is cheap.
193/// It is `Send` and `Sync` natively; on browser wasm its providers,
194/// sign-ins and wrappers may hold JavaScript values instead.
195#[derive(Clone)]
196pub struct Connector {
197 catalog: Catalog,
198 providers: HashMap<&'static str, Arc<dyn Provide>>,
199 sign_ins: Vec<Arc<dyn SignIn>>,
200 transport: Transport,
201}
202
203impl Default for Connector {
204 fn default() -> Self {
205 Self::new(Catalog::builtin().clone())
206 }
207}
208
209impl Connector {
210 /// A connector for the models of `catalog`, such as the built-in one
211 /// with a user's overrides laid over it.
212 pub fn new(catalog: Catalog) -> Self {
213 Self {
214 catalog,
215 providers: HashMap::new(),
216 sign_ins: Vec::new(),
217 transport: Transport::default(),
218 }
219 }
220
221 /// Wraps the HTTP client every model of this connector is reached
222 /// through, outside the wrappers added before. Connections made before
223 /// the call are not rebuilt.
224 ///
225 /// ```
226 /// use rig_core::catalog::Connector;
227 /// use rig_core::http_client::DynHttpClient;
228 ///
229 /// let mut connector = Connector::default();
230 /// // A wrapper sees every request and response, such as to log them.
231 /// connector.wrap_http(|inner: DynHttpClient| inner);
232 /// ```
233 pub fn wrap_http(
234 &mut self,
235 wrap: impl Fn(DynHttpClient) -> DynHttpClient + WasmCompatSend + WasmCompatSync + 'static,
236 ) {
237 self.transport.wrappers.push(Arc::new(wrap));
238 }
239
240 /// The transport this connector's models are reached through, for a
241 /// host that builds a model of its own beside them.
242 pub fn transport(&self) -> &Transport {
243 &self.transport
244 }
245
246 /// Falls back to `sign_in` for a model the environment has no key for
247 /// and no sign-in added earlier serves.
248 pub fn add_sign_in(&mut self, sign_in: impl SignIn) {
249 self.sign_ins.push(Arc::new(sign_in));
250 }
251
252 /// Reaches every model of `vendor` (any of its protocol families)
253 /// through `provider`, before the environment. A model the provider
254 /// has no key for ([`ConnectError::MissingKey`]) falls back to the
255 /// sign-ins, as one the environment has no key for does. A later
256 /// provider for the same vendor replaces this one: to wrap it instead,
257 /// take it first with [`Self::provider`].
258 ///
259 /// ```
260 /// use rig_core::catalog::{Catalog, Connector, ModelSpec};
261 /// use rig_core::providers::registry::{ConnectOptions, ProviderId};
262 ///
263 /// let corp = ProviderId::declare("corp")?;
264 /// let mut connector = Connector::default();
265 /// connector.catalog_mut().insert(ModelSpec::new(corp, "big").with_tools(true));
266 /// // A built-in vendor at another address.
267 /// let ollama = ProviderId::catalog("ollama").ok_or("known")?;
268 /// connector.provide(ollama, ConnectOptions::new().base_url("http://gpu:11434/v1"));
269 /// assert!(connector.is_provided(ollama) && !connector.is_provided(corp));
270 /// # Ok::<(), Box<dyn std::error::Error>>(())
271 /// ```
272 pub fn provide(&mut self, vendor: ProviderId, provider: impl Provide) {
273 self.providers.insert(vendor.vendor(), Arc::new(provider));
274 }
275
276 /// Whether a provider is registered for `vendor`'s models.
277 pub fn is_provided(&self, vendor: ProviderId) -> bool {
278 self.providers.contains_key(vendor.vendor())
279 }
280
281 /// The provider registered for `vendor`'s models, if any: what a
282 /// provider that wraps it, such as one that changes the key, delegates
283 /// to.
284 pub fn provider(&self, vendor: ProviderId) -> Option<Arc<dyn Provide>> {
285 self.providers.get(vendor.vendor()).cloned()
286 }
287
288 /// The catalog.
289 pub fn catalog(&self) -> &Catalog {
290 &self.catalog
291 }
292
293 /// The catalog, to add or change models in place, keeping the
294 /// providers and sign-ins.
295 pub fn catalog_mut(&mut self) -> &mut Catalog {
296 &mut self.catalog
297 }
298
299 /// The catalog model `reference` names, as [`Catalog::resolve`] finds
300 /// it, and that model as an effect handler: from the provider
301 /// registered for its vendor, else its provider's client built from the
302 /// environment, on the shared HTTP client of the `reqwest` feature, or,
303 /// without a key in either, the handler of a sign-in that serves it. The
304 /// HTTP client is wrapped by [`Self::wrap_http`]'s wrappers.
305 ///
306 /// # Errors
307 ///
308 /// [`ConnectError::NotFound`] for a model the catalog does not list,
309 /// what the registered provider reports, else what
310 /// [`Catalog::connect_with`] reports, when no sign-in serves a model
311 /// the provider or the environment has no key for.
312 pub fn connect(
313 &self,
314 reference: &str,
315 ) -> Result<(Arc<ModelSpec>, ErasedHandler), ConnectError> {
316 let spec = self.catalog.resolve(reference)?.shared();
317 let (handler, _) = self.handler(&spec);
318 Ok((spec, handler?))
319 }
320
321 /// The handler serving `spec`, as [`Self::connect`] finds it, and the
322 /// sign-in serving it when reached through one.
323 fn handler(
324 &self,
325 spec: &ModelSpec,
326 ) -> (Result<ErasedHandler, ConnectError>, Option<&dyn SignIn>) {
327 let connected = match self.providers.get(spec.provider.vendor()) {
328 Some(provider) => provider.handler(spec, &self.catalog, &self.transport),
329 None => ConnectOptions::new().handler(spec, &self.catalog, &self.transport),
330 };
331 match connected {
332 Err(error @ ConnectError::MissingKey { .. }) => self
333 .sign_ins
334 .iter()
335 .find_map(|sign_in| {
336 sign_in
337 .handler(spec, &self.transport)
338 .map(|handler| (handler, Some(sign_in.as_ref())))
339 })
340 .unwrap_or((Err(error), None)),
341 other => (other, None),
342 }
343 }
344
345 /// The plan of the first sign-in that would serve `spec`
346 /// ([`SignIn::plan`]).
347 pub fn plan(&self, spec: &ModelSpec) -> Option<&'static str> {
348 self.sign_ins.iter().find_map(|sign_in| sign_in.plan(spec))
349 }
350
351 /// Whether `spec` can serve an agent now, and why not: it must call
352 /// tools, connect as [`Self::connect`] would connect it, be offered by
353 /// the account when served through a sign-in, and, when its provider
354 /// needs no key, be configured ([`ModelStatus::Unconfigured`]).
355 ///
356 /// ```
357 /// use rig_core::catalog::{Connector, ModelSpec, ModelStatus};
358 /// use rig_core::providers::registry::ProviderId;
359 ///
360 /// let corp = ProviderId::declare("status-doc-corp")?;
361 /// let connector = Connector::default();
362 /// let chat = ModelSpec::new(corp, "chat");
363 /// assert_eq!(connector.status(&chat), ModelStatus::NoTools);
364 /// let agent = chat.with_tools(true);
365 /// assert!(matches!(connector.status(&agent), ModelStatus::Unavailable(_)));
366 /// # Ok::<(), Box<dyn std::error::Error>>(())
367 /// ```
368 pub fn status(&self, spec: &ModelSpec) -> ModelStatus {
369 if !spec.tools {
370 return ModelStatus::NoTools;
371 }
372 let (handler, sign_in) = self.handler(spec);
373 if let Some(sign_in) = sign_in {
374 let offered = sign_in.offers(spec, &self.transport);
375 if offered != ModelStatus::Usable {
376 return offered;
377 }
378 }
379 let provider = spec.provider;
380 match handler {
381 Ok(_)
382 if !provider.requires_credential()
383 && !self.is_provided(provider)
384 && !provider.configured_in_env() =>
385 {
386 ModelStatus::Unconfigured
387 }
388 Ok(_) => ModelStatus::Usable,
389 Err(ConnectError::MissingKey { tried, .. }) => ModelStatus::NoKey(tried),
390 Err(error) => ModelStatus::Unavailable(error.to_string()),
391 }
392 }
393
394 /// Catalog models that call tools and can be reached through a
395 /// registered provider, the environment or a sign-in: first those of
396 /// providers registered, with a key set or signed in, then those of
397 /// configured providers that need none (local servers such as Ollama),
398 /// which a picker can mark "no key needed". Only [`ModelStatus::Usable`]
399 /// models are reachable, checked as [`Self::statuses`] checks them.
400 pub fn reachable(&self) -> Vec<&ModelSpec> {
401 let statuses = self.statuses().into_iter();
402 let usable = statuses.filter(|(_, status)| *status == ModelStatus::Usable);
403 usable.map(|(spec, _)| spec).collect()
404 }
405
406 /// Every catalog model with its [`ModelStatus`]: first the
407 /// [`reachable`](Self::reachable) ones in that order, then the others in
408 /// catalog order. Only [`ModelStatus::Usable`] is reachable. Models
409 /// claimed by a sign-in's plan or reached through a registered provider
410 /// ([`Self::provide`]), which may answer per model, are checked
411 /// individually; the others, which the environment configures per
412 /// provider, share one check per provider.
413 pub fn statuses(&self) -> Vec<(&ModelSpec, ModelStatus)> {
414 let mut checked: HashMap<ProviderId, ModelStatus> = HashMap::new();
415 let mut statuses: Vec<(&ModelSpec, ModelStatus)> = self
416 .catalog
417 .iter()
418 .map(|spec| {
419 let status = match spec.tools {
420 false => ModelStatus::NoTools,
421 true if self.plan(spec).is_some() || self.is_provided(spec.provider) => {
422 self.status(spec)
423 }
424 true => checked
425 .entry(spec.provider)
426 .or_insert_with(|| self.status(spec))
427 .clone(),
428 };
429 (spec, status)
430 })
431 .collect();
432 // Stable: catalog order within each group.
433 statuses.sort_by_key(|(spec, status)| match status {
434 ModelStatus::Usable => {
435 u8::from(!self.is_provided(spec.provider) && !spec.provider.requires_credential())
436 }
437 _ => 2,
438 });
439 statuses
440 }
441}
442
443// On browser wasm a provider, a sign-in and an HTTP wrapper may hold values
444// that are neither `Send` nor `Sync`, such as JavaScript handles.
445#[cfg(target_family = "wasm")]
446const _: fn(&mut Connector, ProviderId) = |connector, vendor| {
447 use std::rc::Rc;
448
449 struct PageSignIn {
450 _page: Rc<()>,
451 }
452 impl SignIn for PageSignIn {
453 fn handler(
454 &self,
455 _: &ModelSpec,
456 _: &Transport,
457 ) -> Option<Result<ErasedHandler, ConnectError>> {
458 None
459 }
460 fn plan(&self, _: &ModelSpec) -> Option<&'static str> {
461 None
462 }
463 }
464
465 let page = Rc::new(());
466 let wrapped = page.clone();
467 connector.wrap_http(move |client| {
468 let _ = &wrapped;
469 client
470 });
471 let provided = page.clone();
472 connector.provide(vendor, move |_: &ModelSpec, _: &Catalog, _: &Transport| {
473 let _ = &provided;
474 Err(ConnectError::Provider("not on this page".into()))
475 });
476 connector.add_sign_in(PageSignIn { _page: page });
477};
478
479#[cfg(test)]
480mod tests;