Skip to main content

drep/llm/
models.rs

1//! Asking an endpoint which models it serves.
2//!
3//! `drep init` used to offer a hardcoded model name per preset and let the user
4//! type over it, with nothing checking the result. `presets.rs` said so out
5//! loud: the defaults are "the one thing here that goes stale". A typo, or a
6//! model the plan does not include, surfaced as a 404 on the first push rather
7//! than at the prompt.
8//!
9//! The endpoint already knows the answer, and the wizard is holding the key at
10//! exactly the moment it asks. So it asks the endpoint.
11//!
12//! ## Why not a registry
13//!
14//! A vendored catalogue would go stale exactly as the hardcoded defaults do
15//! and would additionally have to be noticed and updated. A third-party index
16//! (models.dev) covers every provider at once, but describes what a *vendor*
17//! publishes rather than what *this account's plan* serves, and it is a 4 MB
18//! network dependency on somebody else's uptime. The endpoint is authoritative
19//! for the only question being asked.
20//!
21//! ## One shape, three vendors
22//!
23//! Every endpoint drep ships a preset for answers `GET {base_url}/models` with
24//! `{"data": [{"id": ...}]}`, whichever protocol it otherwise speaks. They
25//! disagree only on what *else* is in each entry: z.ai sends OpenAI's
26//! `object`/`created`/`owned_by`, MiniMax sends Anthropic's `type`/`created_at`
27//! /`display_name`, and Kimi sends both plus `context_length` and
28//! `supports_reasoning`. Reading `id` and an optional `display_name` covers all
29//! three, and serde ignores the rest - which is also what stops a new field
30//! breaking the parse.
31//!
32//! The protocol still decides the **auth header**, because that is not
33//! negotiable per request: bearer for OpenAI-compatible, `x-api-key` plus a
34//! version for Anthropic.
35//!
36//! The configured endpoint is the exact origin allowed to receive that header.
37//! A redirect is reported like any other non-success status and is never
38//! followed, including when its destination stays on the same origin.
39//!
40//! ## Failure is never fatal
41//!
42//! A listing is a convenience during setup. An endpoint that does not serve one
43//! (a local llama.cpp build, a gateway, anything older) must leave the user
44//! typing a name exactly as before, so every error here is something the caller
45//! reports and moves past. Nothing in this module can stop `drep init`.
46
47use std::time::Duration;
48
49use open_agent::ApiProtocol;
50use serde::Deserialize;
51use thiserror::Error;
52
53/// How long to wait for a listing before giving up and letting the user type.
54///
55/// Short on purpose. This sits between two prompts in an interactive session,
56/// and a setup that appears to hang is worse than one that asks for a name.
57const TIMEOUT: Duration = Duration::from_secs(10);
58
59/// The API version header Anthropic-shaped endpoints require.
60///
61/// Duplicated from the SDK rather than imported because the SDK does not export
62/// it, and it is a one-line constant whose value is pinned by the same tests
63/// that pin the request shape. If it ever needs to change, `list` fails and the
64/// wizard falls back to typing a name.
65const ANTHROPIC_VERSION: &str = "2023-06-01";
66
67/// A model an endpoint offers.
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct Model {
70    /// The identifier to put in `drep.toml`.
71    pub id: String,
72    /// A human-facing name, when the endpoint sends one. Kimi's `k3` is
73    /// `"K2.7 Coding"`, which is worth showing beside the id nobody would guess
74    /// it from.
75    pub display_name: Option<String>,
76}
77
78impl Model {
79    /// How the wizard lists this model: the id, plus the vendor's own name for
80    /// it when that differs.
81    pub fn label(&self) -> String {
82        match &self.display_name {
83            Some(name) if name != &self.id => format!("{} ({name})", self.id),
84            _ => self.id.clone(),
85        }
86    }
87}
88
89/// Why a listing could not be produced.
90///
91/// Every variant is non-fatal: the caller reports it and asks for a name.
92#[derive(Debug, Error)]
93pub enum ListError {
94    #[error("this endpoint does not offer a model list")]
95    Unsupported,
96
97    #[error("the endpoint rejected the key (HTTP {0})")]
98    Unauthorized(u16),
99
100    #[error("could not reach the endpoint: {0}")]
101    Transport(String),
102
103    #[error("the endpoint's model list could not be read: {0}")]
104    Malformed(String),
105}
106
107/// Where the wizard gets a model list.
108///
109/// A trait so the wizard can be driven by a stub: the alternative is a wizard
110/// test suite that makes real network calls, which would be slow, offline-
111/// hostile, and dependent on somebody's plan still including a given model.
112pub trait ModelSource {
113    /// List the models `endpoint` serves.
114    #[allow(async_fn_in_trait)]
115    async fn list(
116        &self,
117        endpoint: &str,
118        api_key: &str,
119        protocol: ApiProtocol,
120    ) -> Result<Vec<Model>, ListError>;
121}
122
123/// The largest listing drep will read into memory.
124///
125/// A real listing is a few kilobytes - the longest of the four is Kimi's, at
126/// well under one. 8 MB is a margin no honest endpoint approaches, and it is
127/// what stops a mirror, a redirect to something else, or a compromised host
128/// making `drep init` allocate without bound. The timeout does not prevent
129/// that on its own: a fast host can send a great deal inside one.
130const MAX_LISTING_BYTES: u64 = 8 * 1024 * 1024;
131
132/// The real thing: one HTTP GET.
133#[derive(Debug, Clone, Copy)]
134pub struct Http {
135    /// The ceiling on the response body. A field rather than a constant read
136    /// directly, so the boundary is reachable from a test without a multi-
137    /// megabyte fixture - the same reason [`crate::llm::quirks::Http`] has one.
138    max_bytes: u64,
139}
140
141impl Http {
142    /// A fetcher with the production ceiling.
143    pub fn new() -> Self {
144        Self {
145            max_bytes: MAX_LISTING_BYTES,
146        }
147    }
148
149    /// The same fetcher with a different size ceiling. For the tests that pin
150    /// the boundary; production always uses [`MAX_LISTING_BYTES`].
151    #[cfg(test)]
152    pub fn with_max_bytes(mut self, max_bytes: u64) -> Self {
153        self.max_bytes = max_bytes;
154        self
155    }
156}
157
158impl Default for Http {
159    fn default() -> Self {
160        Self::new()
161    }
162}
163
164impl ModelSource for Http {
165    async fn list(
166        &self,
167        endpoint: &str,
168        api_key: &str,
169        protocol: ApiProtocol,
170    ) -> Result<Vec<Model>, ListError> {
171        let client = crate::http::client(TIMEOUT).map_err(ListError::Transport)?;
172
173        let request = client.get(url(endpoint));
174        let request = match protocol {
175            ApiProtocol::Anthropic => request
176                .header("x-api-key", api_key)
177                .header("anthropic-version", ANTHROPIC_VERSION),
178            // `ApiProtocol` is `#[non_exhaustive]`, so a protocol added to the
179            // SDK later lands here. Bearer is the right guess for anything
180            // OpenAI-shaped, and a wrong one costs a fallback to typing a name.
181            _ => request.header("Authorization", format!("Bearer {api_key}")),
182        };
183
184        let response = request
185            .send()
186            .await
187            .map_err(|err| ListError::Transport(err.to_string()))?;
188
189        let status = response.status().as_u16();
190        if !response.status().is_success() {
191            return Err(classify(status));
192        }
193
194        // Bounded, not `text()`. This is an endpoint the user typed at a
195        // prompt, and drep is holding a key while it asks - so the body has a
196        // ceiling for the same reason the registry document does.
197        let body = crate::http::read_bounded(response, self.max_bytes)
198            .await
199            .map_err(|err| match err {
200                crate::http::ReadError::Transport(msg) => ListError::Transport(msg),
201                crate::http::ReadError::Malformed(msg) => ListError::Malformed(msg),
202            })?;
203        parse(&body)
204    }
205}
206
207/// The listing URL for `endpoint`.
208///
209/// `{base_url}/models` for both protocols - verified against all three
210/// subscription endpoints, whose base URLs already carry whatever version
211/// segment they use (`/api/coding/paas/v4`, `/anthropic/v1`, `/coding/v1`).
212/// A trailing slash on the configured endpoint would otherwise produce `//`,
213/// which some gateways answer with a redirect and others with a 404.
214fn url(endpoint: &str) -> String {
215    format!("{}/models", endpoint.trim_end_matches('/'))
216}
217
218/// Map an HTTP status onto the reason the caller reports.
219///
220/// 404 and 405 are the endpoint saying it has no such route, which is the
221/// ordinary case for a local server rather than a fault. 401 and 403 are worth
222/// separating because they mean the key is wrong - the user is about to store
223/// it, and finding out now beats finding out on the first push.
224fn classify(status: u16) -> ListError {
225    match status {
226        404 | 405 | 501 => ListError::Unsupported,
227        401 | 403 => ListError::Unauthorized(status),
228        other => ListError::Transport(format!("HTTP {other}")),
229    }
230}
231
232/// The half of a listing response drep reads.
233#[derive(Debug, Deserialize)]
234struct Listing {
235    data: Vec<Entry>,
236}
237
238/// One entry. Every other field the vendors send is ignored by serde.
239#[derive(Debug, Deserialize)]
240struct Entry {
241    id: String,
242    #[serde(default)]
243    display_name: Option<String>,
244}
245
246/// Parse a listing body into models, in the order the endpoint sent them.
247///
248/// Order is preserved rather than sorted: every one of these endpoints lists
249/// its newest model first, which is the one a user setting drep up almost
250/// always wants, and alphabetical order would bury it (`MiniMax-M2` sorts above
251/// `MiniMax-M3`; `glm-4.5` above `glm-5.3`).
252///
253/// An empty list is [`ListError::Unsupported`] rather than an empty menu: a
254/// prompt offering nothing is worse than the free-text prompt it replaced.
255fn parse(body: &str) -> Result<Vec<Model>, ListError> {
256    let listing: Listing = serde_json::from_str(body)
257        .map_err(|err| ListError::Malformed(crate::text::excerpt(&err.to_string(), 120)))?;
258
259    let models: Vec<Model> = listing
260        .data
261        .into_iter()
262        .filter(|entry| !entry.id.is_empty())
263        .map(|entry| Model {
264            id: entry.id,
265            display_name: entry.display_name,
266        })
267        .collect();
268
269    if models.is_empty() {
270        return Err(ListError::Unsupported);
271    }
272    Ok(models)
273}
274
275#[cfg(test)]
276mod tests;