Skip to main content

drep/llm/client/
mod.rs

1//! The LLM client.
2//!
3//! One boundary: `LlmClient::complete_json` takes a system prompt and a user
4//! payload, sends them to the configured OpenAI-compatible endpoint, and
5//! returns the JSON value the model produced. Cache and concurrency limiting
6//! live above this single-provider request boundary.
7//!
8//! ## What is deliberately delegated to the SDK
9//!
10//! - **Streaming.** `open-agent-sdk` parses the SSE stream; drep concatenates
11//!   the `ContentBlock::Text` blocks it emits and ignores the rest. Since
12//!   0.10.0 those blocks are *fragments* - one event per delta, delivered
13//!   while the stream is open, where 0.9.x emitted the whole response as a
14//!   single block at the end. The types are identical either way, so nothing
15//!   here failed to compile and nothing here changed: the join in
16//!   `run_one_query` is what makes the assembled text independent of where
17//!   the deltas fall. Reading one block as the whole answer would now return a
18//!   prefix, and `src/llm/client/tests/streaming.rs` is what would notice.
19//! - **Transport retry.** `retry_with_backoff_conditional` decides per error
20//!   whether to retry (5xx, timeout, stream error) or fail fast (4xx, config
21//!   errors). drep adds no retry layer on top.
22//!
23//! ## What this module owns
24//!
25//! - **Parse retry.** The same prompt truncates the same way, so a parse
26//!   failure does NOT retry. The retry closure returns `Ok(None)` for an
27//!   unparseable body; the SDK's retry sees `Ok(...)` and stops.
28//! - **Attempt count floor.** `LlmConfig::max_retries` may be 0, but a
29//!   "zero attempts loop" would skip the request and report a bogus "no
30//!   exception was captured". The floor is 1.
31//! - **`max_tokens` pass-through.** The configured cap is forwarded only when
32//!   the user set one. open-agent-sdk 0.7.0 omits the field entirely otherwise,
33//!   so "unset" means the server decides - which is what a 256k-1M context
34//!   model needs. (Before 0.7.0 the builder substituted 4096 and truncated
35//!   reasoning models mid-thought; drep passed a large sentinel to work around
36//!   it. That workaround is gone.)
37
38use std::time::Duration;
39
40use futures::StreamExt;
41use open_agent::retry::{RetryConfig, retry_with_backoff_conditional};
42use open_agent::{AgentOptions, ApiProtocol, ContentBlock, FinishReason, StreamEvent, query};
43
44use crate::config::LlmConfig;
45use crate::llm::error::LlmError;
46use crate::llm::json_parsing::{Extracted, extract_json};
47use crate::text::excerpt;
48
49/// How much of a model response reaches an error message.
50///
51/// Generous: unlike a URL, the useful signal in a refusal or a prose preamble
52/// is often a sentence or two in.
53const RESPONSE_EXCERPT_MAX: usize = 200;
54
55/// A configured LLM client ready to issue requests.
56///
57/// Built once per process from `LlmConfig`; `complete_json` is the only
58/// entry point the analyzer uses.
59///
60/// Fields are `pub(crate)` so the test submodules can construct clients
61/// with a non-default retry config (the production default sleeps 1s
62/// between attempts, which would make the retry tests take seconds). They
63/// are not part of the public API.
64pub struct LlmClient {
65    pub(crate) base_url: String,
66    pub(crate) model: String,
67    pub(crate) api_key: String,
68    /// The wire protocol this endpoint speaks. Selects the request path, the auth
69    /// header, the body shape and the streaming vocabulary together - the SDK
70    /// resolves all four from this one value.
71    pub(crate) protocol: ApiProtocol,
72    /// `None` sends no `temperature` at all. Two of the four models drep ships a
73    /// preset for reject the parameter outright, and a 400 neither fails over nor
74    /// retries, so "omit it" had to be expressible rather than approximated by a
75    /// low value.
76    pub(crate) temperature: Option<f32>,
77    /// `None` means "no ceiling": since open-agent-sdk 0.7.0 an unset
78    /// `max_tokens` is omitted from the request entirely and the server decides.
79    /// Before 0.7.0 the builder substituted 4096, which truncated reasoning
80    /// models mid-thought, and drep had to pass a large sentinel instead.
81    pub(crate) max_tokens: Option<u32>,
82    pub(crate) timeout_secs: u64,
83    pub(crate) retry_config: RetryConfig,
84}
85
86/// Hand-written so the API key cannot reach a log.
87///
88/// A derived `Debug` prints every field, so any `{:?}`, `dbg!` or tracing line
89/// touching the client would emit a live credential.
90impl std::fmt::Debug for LlmClient {
91    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92        f.debug_struct("LlmClient")
93            .field("base_url", &self.base_url)
94            .field("model", &self.model)
95            .field("api_key", &"<redacted>")
96            .field("protocol", &self.protocol.as_str())
97            .field("temperature", &self.temperature)
98            .field("max_tokens", &self.max_tokens)
99            .field("timeout_secs", &self.timeout_secs)
100            .finish()
101    }
102}
103
104impl LlmClient {
105    /// The model this client asks for.
106    ///
107    /// An accessor rather than a second copy on the caller: the cache key is
108    /// computed from the model, and a struct holding its own `model` string is
109    /// exactly what lets a request go to one model while the key names
110    /// another.
111    pub fn model(&self) -> &str {
112        &self.model
113    }
114
115    /// The base URL this client talks to. For display - `doctor` and the
116    /// failover report name the endpoint a provider used.
117    pub fn endpoint(&self) -> &str {
118        &self.base_url
119    }
120
121    /// The sampling temperature, or `None` when none is sent. Part of the cache
122    /// key, for the same reason [`Self::model`] is - and `None` has to key
123    /// differently from any value, because the answers genuinely differ.
124    pub fn temperature(&self) -> Option<f32> {
125        self.temperature
126    }
127
128    /// The wire protocol this client speaks. For display, and for the cache key:
129    /// the same model at the same endpoint over two protocols is two requests.
130    pub fn protocol(&self) -> ApiProtocol {
131        self.protocol
132    }
133
134    /// Build a client from a validated `LlmConfig`.
135    ///
136    /// Returns [`LlmError::NotConfigured`] when the config does not name an
137    /// endpoint, a model, or has `enabled = false`. We do not default an
138    /// endpoint - "LLM was disabled" and "LLM is enabled but misconfigured"
139    /// are both fatal here, and inventing a value would mask a broken
140    /// install.
141    pub fn new(cfg: &LlmConfig) -> Result<Self, LlmError> {
142        if !cfg.enabled {
143            return Err(LlmError::NotConfigured(
144                "LLM is disabled in config (set `enabled = true`)".to_string(),
145            ));
146        }
147        let endpoint = cfg.endpoint.clone().ok_or_else(|| {
148            LlmError::NotConfigured("LLM endpoint is not set in config".to_string())
149        })?;
150        let model = cfg
151            .model
152            .clone()
153            .ok_or_else(|| LlmError::NotConfigured("LLM model is not set in config".to_string()))?;
154
155        let api_key = cfg
156            .api_key
157            .clone()
158            .unwrap_or_else(|| "not-needed".to_string());
159
160        // `config::load` already rejected an unknown name, so this cannot fail for a
161        // config that came through the loader. It is re-checked rather than unwrapped
162        // because `LlmClient::new` is also reachable from tests that build an
163        // `LlmConfig` directly, and a silent default here would post
164        // chat-completions bytes to a `/messages` endpoint.
165        let protocol = crate::config::parse_protocol(cfg.protocol.as_deref()).ok_or_else(|| {
166            LlmError::NotConfigured(format!(
167                "unknown protocol `{}`; expected `openai` or `anthropic`",
168                cfg.protocol.as_deref().unwrap_or_default()
169            ))
170        })?;
171
172        // max_retries is a total attempt count; the floor is 1 so a config of
173        // 0 still performs exactly one attempt. See the spec's note on the
174        // bogus "no exception was captured" failure.
175        let max_attempts = cfg.max_retries.max(1);
176
177        Ok(LlmClient {
178            base_url: endpoint,
179            model,
180            api_key,
181            protocol,
182            temperature: cfg.temperature,
183            max_tokens: cfg.max_tokens,
184            timeout_secs: cfg.timeout_secs,
185            retry_config: RetryConfig {
186                max_attempts,
187                initial_delay: Duration::from_secs(1),
188                max_delay: Duration::from_secs(60),
189                backoff_multiplier: 2.0,
190                jitter_factor: 0.1,
191            },
192        })
193    }
194
195    /// Send one prompt and return the extracted JSON.
196    ///
197    /// Concatenates `ContentBlock::Text` blocks in arrival order; other block
198    /// variants are ignored. An empty response body is **retried** as a
199    /// transport failure and, if it keeps coming back empty, surfaces as
200    /// [`LlmError::Transport`] - see `run_one_query` for why "the model
201    /// returned nothing" is not the deterministic outcome it looks like.
202    ///
203    /// A non-empty body that yields **no JSON at all** is retried up to
204    /// [`NO_JSON_ATTEMPTS`] times and then becomes [`LlmError::Unparseable`],
205    /// carrying an excerpt of what actually came back. A body that parsed only
206    /// after brace-balancing ([`Extracted::Truncated`]) is returned
207    /// immediately and never retried - that is the genuinely deterministic
208    /// case, and the one the "never retry" rule was written for.
209    pub async fn complete_json(
210        &self,
211        system_prompt: &str,
212        user_content: &str,
213    ) -> Result<Extracted, LlmError> {
214        // Build options per request. The SDK doesn't expose a way to set
215        // `system_prompt` after `build()`, and the retry closure needs to
216        // borrow the same options across attempts.
217        let builder = AgentOptions::builder()
218            .model(&self.model)
219            .base_url(&self.base_url)
220            .api_key(&self.api_key)
221            .system_prompt(system_prompt)
222            .protocol(self.protocol)
223            .timeout(self.timeout_secs);
224
225        // Only send a temperature when one was configured. An unset value means the
226        // field is omitted entirely, which is the only thing that works against a
227        // model that rejects the parameter.
228        let builder = match self.temperature {
229            Some(temperature) => builder.temperature(temperature),
230            None => builder,
231        };
232
233        // Only set a ceiling when the user asked for one. open-agent-sdk 0.7.0
234        // omits `max_tokens` from the request when the setter is never called,
235        // so "unset" genuinely means "let the server decide" rather than the
236        // implicit 4096 earlier versions substituted.
237        let builder = match self.max_tokens {
238            Some(limit) => builder.max_tokens(limit),
239            None => builder,
240        };
241
242        let options = builder
243            .build()
244            .map_err(|e| LlmError::NotConfigured(format!("AgentOptions build failed: {e}")))?;
245
246        let prompt = user_content.to_string();
247
248        // The no-JSON retry is drep's own loop, deliberately *outside* the
249        // SDK's. Handing "no JSON" to the SDK by returning `Err` would work,
250        // but it would surface as `LlmError::Transport` once the attempts ran
251        // out - and `Transport` fails over to the next provider and demotes
252        // this one for the whole run. A model that answered in prose has told
253        // us nothing about the endpoint: after these response retries the
254        // chain may ask a fallback for this file, but must not demote this
255        // provider.
256        //
257        // The SDK's own retry still runs inside each pass, so a transport
258        // failure is handled by the layer that classifies it.
259        let mut last_body = String::new();
260        for _ in 0..NO_JSON_ATTEMPTS {
261            let result: open_agent::Result<Answer> =
262                retry_with_backoff_conditional(self.retry_config.clone(), || {
263                    self.run_one_query(&prompt, &options)
264                })
265                .await;
266
267            match result {
268                Ok(Answer::Parsed(extracted)) => return Ok(extracted),
269                // The server said why it stopped, and the reason rules out a
270                // retry: the request hit a limit, so the same request hits the
271                // same limit. This is the genuinely deterministic case the
272                // original "never retry a non-empty body" rule was reaching
273                // for - it just used "no JSON in the body" as the proxy, which
274                // is not the same question.
275                Ok(Answer::NoJson { text, finish }) if !worth_asking_again(&finish) => {
276                    return Err(LlmError::ModelStopped {
277                        finish: finish.as_str().to_owned(),
278                        message: stopped_message(&finish, &text),
279                    });
280                }
281                Ok(Answer::NoJson { text, .. }) => last_body = text,
282                Err(e) => {
283                    // The SDK exposes the status code separately (via
284                    // `status_code`); reading it before formatting means the
285                    // number survives as a number, and a later caller can
286                    // branch on it rather than parsing the message.
287                    let status = e.status_code();
288                    let message = format!("{e}");
289                    return Err(LlmError::Transport { status, message });
290                }
291            }
292        }
293
294        Err(LlmError::Unparseable(format!(
295            "no JSON in the response after {NO_JSON_ATTEMPTS} attempts; \
296             the model answered: {}",
297            excerpt(&last_body, RESPONSE_EXCERPT_MAX)
298        )))
299    }
300
301    /// One attempt: stream the response, concatenate text, parse.
302    ///
303    /// Returns [`Answer::NoJson`] carrying the raw text when the query
304    /// produced something we could not parse at all - the SDK's retry layer
305    /// sees `Ok` and stops, leaving the decision to `complete_json`. Returns
306    /// `Err(SdkError)` for a transport-level failure, including an unexplained
307    /// empty response. An empty response with a terminal `Length` or
308    /// `ContentFilter` reason stays [`Answer::NoJson`], because the reason says
309    /// the same request cannot benefit from a retry.
310    async fn run_one_query(
311        &self,
312        prompt: &str,
313        options: &AgentOptions,
314    ) -> open_agent::Result<Answer> {
315        let mut stream = query(prompt, options).await?;
316        let mut text = String::new();
317        // `Unspecified` is the right default rather than a panic-if-absent:
318        // several OpenAI-compatible servers never report a reason at all, and
319        // "no information" is a distinct answer from "stopped normally".
320        let mut finish = FinishReason::Unspecified;
321        while let Some(event) = stream.next().await {
322            match event? {
323                // Image, ToolUse, ToolResult are not used here.
324                StreamEvent::Block(ContentBlock::Text(t)) => text.push_str(&t.text),
325                StreamEvent::Finish(reason) => finish = reason,
326                // Everything else is discarded, and that is the contract:
327                // `text` holds assistant text and nothing else. It covers the
328                // non-text blocks drep has no use for, the `Reasoning` side
329                // channel (opt-in, and drep does not opt in - chain-of-thought
330                // must never reach the text drep parses as JSON), and any
331                // variant a later SDK adds, since `StreamEvent` is
332                // `#[non_exhaustive]`. Spelled as one arm because a separate
333                // `Reasoning(_) => {}` above it does the same nothing, and an
334                // arm indistinguishable from the wildcard is dead code.
335                _ => {}
336            }
337        }
338
339        // An empty body is a **transport** failure, not a parse failure.
340        //
341        // An empty response is provider flakiness, not a deterministic parse
342        // failure for the prompt. Repeating the same request can immediately
343        // succeed with findings.
344        //
345        // `Error::stream` is classified retryable by the SDK, which is both
346        // accurate (the stream completed carrying no content) and nearly free:
347        // a response with no output tokens cost nothing to produce, so asking
348        // again is cheap. A *non-empty* body we cannot parse still returns
349        // `Ok(None)` and still does not retry - that is the deterministic case
350        // the split was built for, and re-sending it burns a full reasoning
351        // call for the same answer.
352        if text.trim().is_empty() && worth_asking_again(&finish) {
353            return Err(open_agent::Error::stream(
354                "the model returned an empty response",
355            ));
356        }
357
358        Ok(match extract_json(&text) {
359            Some(extracted) => Answer::Parsed(extracted),
360            // The text is carried out rather than dropped. It was discarded
361            // behind the constant "response contained no parseable JSON",
362            // which made every occurrence of this failure look identical and
363            // left no way to tell a refusal from a prose preamble from
364            // reasoning that leaked into the content channel.
365            None => Answer::NoJson { text, finish },
366        })
367    }
368}
369
370/// What one query produced, before the retry decision.
371///
372/// `NoJson` carries the body so the failure can be diagnosed and so
373/// `complete_json` can decide whether to ask again. The SDK's retry layer
374/// treats both variants as success and stops, which is what keeps the
375/// no-JSON decision here rather than inside it.
376enum Answer {
377    Parsed(Extracted),
378    /// No JSON at all, with why generation stopped. The reason decides whether
379    /// asking again can possibly help.
380    NoJson {
381        text: String,
382        finish: FinishReason,
383    },
384}
385
386/// How many times a response carrying no JSON at all is asked for again.
387///
388/// Not the same question as the SDK's transport retry, and deliberately a
389/// small number: each attempt is a full reasoning call. The rule this replaced
390/// never retried, justified as "the same prompt truncates the same way" - but
391/// that is [`Extracted::Truncated`], a different branch. A response with *no
392/// JSON at all* did not truncate an answer, it never produced one, and in
393/// practice it does not repeat: drep's own gated push failed on a different
394/// file each run, and each failing file analyzed cleanly when asked again.
395///
396/// Three total attempts, so two local retries before the provider chain may
397/// ask a fallback. Production output has been visibly garbled twice in a row
398/// and then parsed unchanged on a later run; the third attempt salvages that
399/// case without demoting an otherwise healthy provider.
400pub const NO_JSON_ATTEMPTS: u32 = 3;
401
402/// Whether asking the same question again could produce a different answer.
403///
404/// `false` for the reasons that are a property of the *request*: a token cap is
405/// hit identically every time, and a content filter that refused this payload
406/// refuses it again. `true` where the server told us nothing useful, because a
407/// model at temperature above zero can simply answer differently - which is
408/// what drep's own gated push demonstrated, failing on a different file each
409/// run with every failing file analyzing cleanly when asked again.
410fn worth_asking_again(finish: &FinishReason) -> bool {
411    // Written as a negated match on the two request-shaped reasons rather than
412    // as an enumeration of the rest. `FinishReason` is `#[non_exhaustive]`, so
413    // a wildcard arm is required either way - and an enumerated "everything
414    // else is retryable" arm sitting above it is behaviourally identical to the
415    // wildcard, which makes it undeletable-but-unobservable: exactly the dead
416    // code the mutation gate exists to find.
417    //
418    // The consequence of the wildcard is deliberate: a reason a later SDK adds
419    // defaults to retrying. The retry is bounded and cheap to be wrong about,
420    // whereas refusing to retry something transient fails a commit outright.
421    !matches!(
422        finish,
423        // A token cap is hit identically every time - drep sends no
424        // `max_tokens`, so the cap is the server's. A content filter that
425        // refused this payload refuses it again.
426        FinishReason::Length | FinishReason::ContentFilter
427    )
428}
429
430/// A sentence a user can act on, for the reasons that end the attempt.
431///
432/// The two cases want different actions - one is "this file is too big for this
433/// model in one pass", the other is "this provider refused the content" - so
434/// they do not share a message.
435fn stopped_message(finish: &FinishReason, text: &str) -> String {
436    match finish {
437        FinishReason::Length => format!(
438            "the model hit its output token limit before producing any JSON. \
439             This file is too large for this model to review in one request - \
440             split it, or use a provider with a larger output budget. \
441             It managed: {}",
442            excerpt(text, RESPONSE_EXCERPT_MAX)
443        ),
444        _ => format!(
445            "the model stopped ({}) before producing any JSON: {}",
446            finish.as_str(),
447            excerpt(text, RESPONSE_EXCERPT_MAX)
448        ),
449    }
450}
451
452#[cfg(test)]
453mod tests;