Skip to main content

gadk_model/
registry.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! A name-based model registry.
17//!
18//! An [`Llm`] can be constructed from just a model-name string via
19//! [`Registry::new_llm`]. Registration is opt-in: provider crates do not register
20//! themselves. A user who wants name-based resolution registers a factory explicitly,
21//! using an anchored pattern such as `"^(?i)gemini-.*"`.
22//!
23//! [`Registry::new_llm`] requires exactly one registered pattern to match a given name:
24//! zero matches or two-or-more matches are reported as errors, so resolution never
25//! depends on registration order.
26
27use std::sync::{Arc, LazyLock};
28
29use futures::future::BoxFuture;
30use parking_lot::RwLock;
31use regex::Regex;
32
33use crate::{Llm, ModelError};
34
35/// Constructs an [`Llm`] for the given model name.
36///
37/// The name is the same string that was matched against the registered pattern, so a
38/// single factory can serve a family of models (for example, all `gemini-*` names).
39pub type Factory =
40    Arc<dyn Fn(String) -> BoxFuture<'static, Result<Arc<dyn Llm>, ModelError>> + Send + Sync>;
41
42/// Errors returned by [`Registry`].
43#[derive(Debug, thiserror::Error)]
44#[non_exhaustive]
45pub enum RegistryError {
46    /// The pattern is not a valid regular expression: `(pattern, reason)`.
47    #[error("model: invalid LLM pattern {0:?}: {1}")]
48    InvalidPattern(String, String),
49    /// The exact pattern string is already registered.
50    #[error("model: LLM pattern {0:?} is already registered")]
51    DuplicatePattern(String),
52    /// No registered pattern matches the name.
53    #[error("model: no registered LLM matches {0:?}")]
54    NoMatch(String),
55    /// More than one registered pattern matches the name.
56    #[error(
57        "model: {name:?} matches multiple registered LLM patterns {patterns:?}; patterns must be unambiguous"
58    )]
59    Ambiguous {
60        /// The model name that was looked up.
61        name: String,
62        /// The matching patterns, in registration order.
63        patterns: Vec<String>,
64    },
65    /// The matching factory failed.
66    #[error(transparent)]
67    Factory(ModelError),
68}
69
70struct Registration {
71    regex: Regex,
72    pattern: String,
73    factory: Factory,
74}
75
76/// A registry mapping model-name patterns to [`Factory`] functions.
77///
78/// Safe for concurrent use.
79#[derive(Default)]
80pub struct Registry {
81    entries: RwLock<Vec<Registration>>,
82}
83
84static GLOBAL: LazyLock<Registry> = LazyLock::new(Registry::new);
85
86impl Registry {
87    /// Creates an empty registry.
88    pub fn new() -> Self {
89        Self::default()
90    }
91
92    /// The process-wide registry.
93    pub fn global() -> &'static Registry {
94        &GLOBAL
95    }
96
97    /// Associates a model-name pattern with a [`Factory`].
98    ///
99    /// `pattern` is a regular expression matched against candidate names with an
100    /// unanchored, partial match; anchor it with `^` and `$` to match a name exactly.
101    /// Registration order is not significant, so patterns must not overlap for names a
102    /// caller intends to resolve.
103    ///
104    /// Returns [`RegistryError::InvalidPattern`] if `pattern` does not compile and
105    /// [`RegistryError::DuplicatePattern`] if the same pattern string is already
106    /// registered.
107    pub fn register(&self, pattern: &str, f: Factory) -> Result<(), RegistryError> {
108        let regex = Regex::new(pattern)
109            .map_err(|e| RegistryError::InvalidPattern(pattern.to_string(), e.to_string()))?;
110        let mut entries = self.entries.write();
111        if entries.iter().any(|r| r.pattern == pattern) {
112            return Err(RegistryError::DuplicatePattern(pattern.to_string()));
113        }
114        entries.push(Registration {
115            regex,
116            pattern: pattern.to_string(),
117            factory: f,
118        });
119        Ok(())
120    }
121
122    /// Builds an [`Llm`] for `name` using the single registration whose pattern matches.
123    ///
124    /// Returns [`RegistryError::NoMatch`] if no pattern matches,
125    /// [`RegistryError::Ambiguous`] if two or more match, and
126    /// [`RegistryError::Factory`] if the matching factory fails. The registry lock is
127    /// not held while the factory runs.
128    pub async fn new_llm(&self, name: &str) -> Result<Arc<dyn Llm>, RegistryError> {
129        let (factory, matched) = {
130            let entries = self.entries.read();
131            let mut factory = None;
132            let mut matched = Vec::new();
133            for r in entries.iter().filter(|r| r.regex.is_match(name)) {
134                factory = Some(r.factory.clone());
135                matched.push(r.pattern.clone());
136            }
137            (factory, matched)
138        };
139
140        match (factory, matched.len()) {
141            (Some(f), 1) => f(name.to_string()).await.map_err(RegistryError::Factory),
142            (_, 0) | (None, _) => Err(RegistryError::NoMatch(name.to_string())),
143            _ => Err(RegistryError::Ambiguous {
144                name: name.to_string(),
145                patterns: matched,
146            }),
147        }
148    }
149}