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