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::collections::BTreeMap;
39use std::time::Duration;
40
41use futures::StreamExt;
42use open_agent::retry::{RetryConfig, retry_with_backoff_conditional};
43use open_agent::{AgentOptions, ApiProtocol, ContentBlock, FinishReason, StreamEvent, query};
44
45use crate::config::LlmConfig;
46use crate::llm::error::LlmError;
47use crate::llm::json_parsing::{Extracted, extract_json};
48use crate::text::excerpt;
49
50/// How much of a model response reaches an error message.
51///
52/// Generous: unlike a URL, the useful signal in a refusal or a prose preamble
53/// is often a sentence or two in.
54const RESPONSE_EXCERPT_MAX: usize = 200;
55
56/// A configured LLM client ready to issue requests.
57///
58/// Built once per process from `LlmConfig`; `complete_json` is the only
59/// entry point the analyzer uses.
60///
61/// Fields are `pub(crate)` so the test submodules can construct clients
62/// with a non-default retry config (the production default sleeps 1s
63/// between attempts, which would make the retry tests take seconds). They
64/// are not part of the public API.
65pub struct LlmClient {
66 pub(crate) base_url: String,
67 pub(crate) model: String,
68 pub(crate) api_key: String,
69 /// The wire protocol this endpoint speaks. Selects the request path, the auth
70 /// header, the body shape and the streaming vocabulary together - the SDK
71 /// resolves all four from this one value.
72 pub(crate) protocol: ApiProtocol,
73 /// `None` sends no `temperature` at all. Two of the four models drep ships a
74 /// preset for reject the parameter outright, and a 400 neither fails over nor
75 /// retries, so "omit it" had to be expressible rather than approximated by a
76 /// low value.
77 pub(crate) temperature: Option<f32>,
78 /// `None` means "no ceiling": since open-agent-sdk 0.7.0 an unset
79 /// `max_tokens` is omitted from the request entirely and the server decides.
80 /// Before 0.7.0 the builder substituted 4096, which truncated reasoning
81 /// models mid-thought, and drep had to pass a large sentinel instead.
82 pub(crate) max_tokens: Option<u32>,
83 pub(crate) timeout_secs: u64,
84 /// Exactly the headers this client sends, default included.
85 ///
86 /// The effective set rather than the configured one, resolved once in
87 /// [`crate::config::effective_headers`]. Applying the default inside the
88 /// request instead left three readers disagreeing about the same question:
89 /// a config naming one header printed one here and in `doctor` while the
90 /// request carried two, and a config naming none printed an empty set while
91 /// the request still carried a `User-Agent`. That is the divergence
92 /// `auth::source_of` exists to prevent one module over.
93 pub(crate) headers: BTreeMap<String, String>,
94 /// Precomputed because every reviewed file asks for the same provider's
95 /// cache identity. It may depend on credential-bearing header values, so it
96 /// is deliberately omitted from `Debug`.
97 request_identity: String,
98 pub(crate) retry_config: RetryConfig,
99}
100
101/// Hand-written so the API key cannot reach a log.
102///
103/// A derived `Debug` prints every field, so any `{:?}`, `dbg!` or tracing line
104/// touching the client would emit a live credential.
105impl std::fmt::Debug for LlmClient {
106 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107 f.debug_struct("LlmClient")
108 .field("base_url", &self.base_url)
109 .field("model", &self.model)
110 .field("api_key", &"<redacted>")
111 .field("protocol", &self.protocol.as_str())
112 .field("temperature", &self.temperature)
113 .field("max_tokens", &self.max_tokens)
114 .field("timeout_secs", &self.timeout_secs)
115 // Names only, spelled exactly as `LlmConfig`'s `Debug` spells it. A
116 // header value is as likely to be a credential as `api_key` is, and
117 // this impl exists precisely so no `{:?}` emits one.
118 .field(
119 "headers",
120 &self.headers.keys().map(String::as_str).collect::<Vec<_>>(),
121 )
122 .finish()
123 }
124}
125
126impl LlmClient {
127 /// The model this client asks for.
128 ///
129 /// An accessor rather than a second copy on the caller: the cache key is
130 /// computed from the model, and a struct holding its own `model` string is
131 /// exactly what lets a request go to one model while the key names
132 /// another.
133 pub fn model(&self) -> &str {
134 &self.model
135 }
136
137 /// The base URL this client talks to. For display - `doctor` and the
138 /// failover report name the endpoint a provider used.
139 pub fn endpoint(&self) -> &str {
140 &self.base_url
141 }
142
143 /// The sampling temperature, or `None` when none is sent. Part of the cache
144 /// key, for the same reason [`Self::model`] is - and `None` has to key
145 /// differently from any value, because the answers genuinely differ.
146 pub fn temperature(&self) -> Option<f32> {
147 self.temperature
148 }
149
150 /// Every HTTP request option that can change the answer while the endpoint
151 /// and model stay the same.
152 ///
153 /// Header names are canonicalised to lower case because HTTP compares them
154 /// case-insensitively. Values remain exact: an arbitrary header can select a
155 /// tenant, model route or feature variant, and drep cannot infer from its
156 /// name whether changing it changes the answer. The returned digest is fed
157 /// into the cache hash and is never logged.
158 pub fn request_identity(&self) -> &str {
159 &self.request_identity
160 }
161
162 /// The wire protocol this client speaks. For display, and for the cache key:
163 /// the same model at the same endpoint over two protocols is two requests.
164 pub fn protocol(&self) -> ApiProtocol {
165 self.protocol
166 }
167
168 /// Build a client from a validated `LlmConfig`.
169 ///
170 /// Returns [`LlmError::NotConfigured`] when the config does not name an
171 /// endpoint, a model, or has `enabled = false`. We do not default an
172 /// endpoint - "LLM was disabled" and "LLM is enabled but misconfigured"
173 /// are both fatal here, and inventing a value would mask a broken
174 /// install.
175 pub fn new(cfg: &LlmConfig) -> Result<Self, LlmError> {
176 if !cfg.enabled {
177 return Err(LlmError::NotConfigured(
178 "LLM is disabled in config (set `enabled = true`)".to_string(),
179 ));
180 }
181 let endpoint = cfg.endpoint.clone().ok_or_else(|| {
182 LlmError::NotConfigured("LLM endpoint is not set in config".to_string())
183 })?;
184 let model = cfg
185 .model
186 .clone()
187 .ok_or_else(|| LlmError::NotConfigured("LLM model is not set in config".to_string()))?;
188
189 // The SDK deliberately omits protocol authentication for an empty key.
190 // This is what lets a gateway authenticate entirely through a custom
191 // header rather than receiving a fabricated `Bearer not-needed` or
192 // `x-api-key: not-needed` beside its real credential.
193 let api_key = cfg.api_key.clone().unwrap_or_default();
194
195 // `config::load` already rejected an unknown name, so this cannot fail for a
196 // config that came through the loader. It is re-checked rather than unwrapped
197 // because `LlmClient::new` is also reachable from tests that build an
198 // `LlmConfig` directly, and a silent default here would post
199 // chat-completions bytes to a `/messages` endpoint.
200 let protocol = crate::config::parse_protocol(cfg.protocol.as_deref()).ok_or_else(|| {
201 LlmError::NotConfigured(format!(
202 "unknown protocol `{}`; expected `openai` or `anthropic`",
203 cfg.protocol.as_deref().unwrap_or_default()
204 ))
205 })?;
206
207 // max_retries is a total attempt count; the floor is 1 so a config of
208 // 0 still performs exactly one attempt. See the spec's note on the
209 // bogus "no exception was captured" failure.
210 let max_attempts = cfg.max_retries.max(1);
211
212 let headers = crate::config::effective_headers(&cfg.headers);
213 let request_identity = build_request_identity(protocol, cfg.max_tokens, &headers)?;
214
215 Ok(LlmClient {
216 base_url: endpoint,
217 model,
218 api_key,
219 protocol,
220 temperature: cfg.temperature,
221 max_tokens: cfg.max_tokens,
222 timeout_secs: cfg.timeout_secs,
223 headers,
224 request_identity,
225 retry_config: RetryConfig {
226 max_attempts,
227 initial_delay: Duration::from_secs(1),
228 max_delay: Duration::from_secs(60),
229 backoff_multiplier: 2.0,
230 jitter_factor: 0.1,
231 },
232 })
233 }
234
235 /// Send one prompt and return the extracted JSON.
236 ///
237 /// Concatenates `ContentBlock::Text` blocks in arrival order; other block
238 /// variants are ignored. An empty response body is **retried** as a
239 /// transport failure and, if it keeps coming back empty, surfaces as
240 /// [`LlmError::Transport`] - see `run_one_query` for why "the model
241 /// returned nothing" is not the deterministic outcome it looks like.
242 ///
243 /// A non-empty body that yields **no JSON at all** is retried up to
244 /// [`NO_JSON_ATTEMPTS`] times and then becomes [`LlmError::Unparseable`],
245 /// carrying an excerpt of what actually came back. A body that parsed only
246 /// after brace-balancing ([`Extracted::Truncated`]) is returned
247 /// immediately and never retried - that is the genuinely deterministic
248 /// case, and the one the "never retry" rule was written for.
249 pub async fn complete_json(
250 &self,
251 system_prompt: &str,
252 user_content: &str,
253 ) -> Result<Extracted, LlmError> {
254 // Build options per request. The SDK doesn't expose a way to set
255 // `system_prompt` after `build()`, and the retry closure needs to
256 // borrow the same options across attempts.
257 let builder = AgentOptions::builder()
258 .model(&self.model)
259 .base_url(&self.base_url)
260 .api_key(&self.api_key)
261 .system_prompt(system_prompt)
262 .protocol(self.protocol)
263 .timeout(self.timeout_secs);
264
265 // Only send a temperature when one was configured. An unset value means the
266 // field is omitted entirely, which is the only thing that works against a
267 // model that rejects the parameter.
268 let builder = match self.temperature {
269 Some(temperature) => builder.temperature(temperature),
270 None => builder,
271 };
272
273 // Only set a ceiling when the user asked for one. open-agent-sdk 0.7.0
274 // omits `max_tokens` from the request when the setter is never called,
275 // so "unset" genuinely means "let the server decide" rather than the
276 // implicit 4096 earlier versions substituted.
277 let builder = match self.max_tokens {
278 Some(limit) => builder.max_tokens(limit),
279 None => builder,
280 };
281
282 // No ordering rule here, and that is the point: `self.headers` is
283 // already the effective set, resolved once when the client was built, so
284 // this loop cannot get the precedence between drep's own `User-Agent`
285 // and an operator's replacement for it wrong.
286 let mut builder = builder;
287 for (name, value) in &self.headers {
288 builder = builder.header(name, value);
289 }
290
291 let options = builder
292 .build()
293 .map_err(|e| LlmError::NotConfigured(format!("AgentOptions build failed: {e}")))?;
294
295 let prompt = user_content.to_string();
296
297 // The no-JSON retry is drep's own loop, deliberately *outside* the
298 // SDK's. Handing "no JSON" to the SDK by returning `Err` would work,
299 // but it would surface as `LlmError::Transport` once the attempts ran
300 // out - and `Transport` fails over to the next provider and demotes
301 // this one for the whole run. A model that answered in prose has told
302 // us nothing about the endpoint: after these response retries the
303 // chain may ask a fallback for this file, but must not demote this
304 // provider.
305 //
306 // The SDK's own retry still runs inside each pass, so a transport
307 // failure is handled by the layer that classifies it.
308 let mut last_body = String::new();
309 for _ in 0..NO_JSON_ATTEMPTS {
310 let result: open_agent::Result<Answer> =
311 retry_with_backoff_conditional(self.retry_config.clone(), || {
312 self.run_one_query(&prompt, &options)
313 })
314 .await;
315
316 match result {
317 Ok(Answer::Parsed(extracted)) => return Ok(extracted),
318 // The server said why it stopped, and the reason rules out a
319 // retry: the request hit a limit, so the same request hits the
320 // same limit. This is the genuinely deterministic case the
321 // original "never retry a non-empty body" rule was reaching
322 // for - it just used "no JSON in the body" as the proxy, which
323 // is not the same question.
324 Ok(Answer::NoJson { text, finish }) if !worth_asking_again(&finish) => {
325 return Err(LlmError::ModelStopped {
326 finish: finish.as_str().to_owned(),
327 message: stopped_message(&finish, &text),
328 });
329 }
330 Ok(Answer::NoJson { text, .. }) => last_body = text,
331 Err(e) => {
332 // The SDK exposes the status code separately (via
333 // `status_code`); reading it before formatting means the
334 // number survives as a number, and a later caller can
335 // branch on it rather than parsing the message.
336 let status = e.status_code();
337 let message = format!("{e}");
338 return Err(LlmError::Transport { status, message });
339 }
340 }
341 }
342
343 Err(LlmError::Unparseable(format!(
344 "no JSON in the response after {NO_JSON_ATTEMPTS} attempts; \
345 the model answered: {}",
346 excerpt(&last_body, RESPONSE_EXCERPT_MAX)
347 )))
348 }
349
350 /// One attempt: stream the response, concatenate text, parse.
351 ///
352 /// Returns [`Answer::NoJson`] carrying the raw text when the query
353 /// produced something we could not parse at all - the SDK's retry layer
354 /// sees `Ok` and stops, leaving the decision to `complete_json`. Returns
355 /// `Err(SdkError)` for a transport-level failure, including an unexplained
356 /// empty response. An empty response with a terminal `Length` or
357 /// `ContentFilter` reason stays [`Answer::NoJson`], because the reason says
358 /// the same request cannot benefit from a retry.
359 async fn run_one_query(
360 &self,
361 prompt: &str,
362 options: &AgentOptions,
363 ) -> open_agent::Result<Answer> {
364 let mut stream = query(prompt, options).await?;
365 let mut text = String::new();
366 // `Unspecified` is the right default rather than a panic-if-absent:
367 // several OpenAI-compatible servers never report a reason at all, and
368 // "no information" is a distinct answer from "stopped normally".
369 let mut finish = FinishReason::Unspecified;
370 while let Some(event) = stream.next().await {
371 match event? {
372 // Image, ToolUse, ToolResult are not used here.
373 StreamEvent::Block(ContentBlock::Text(t)) => text.push_str(&t.text),
374 StreamEvent::Finish(reason) => finish = reason,
375 // Everything else is discarded, and that is the contract:
376 // `text` holds assistant text and nothing else. It covers the
377 // non-text blocks drep has no use for, the `Reasoning` side
378 // channel (opt-in, and drep does not opt in - chain-of-thought
379 // must never reach the text drep parses as JSON), and any
380 // variant a later SDK adds, since `StreamEvent` is
381 // `#[non_exhaustive]`. Spelled as one arm because a separate
382 // `Reasoning(_) => {}` above it does the same nothing, and an
383 // arm indistinguishable from the wildcard is dead code.
384 _ => {}
385 }
386 }
387
388 // An empty body is a **transport** failure, not a parse failure.
389 //
390 // An empty response is provider flakiness, not a deterministic parse
391 // failure for the prompt. Repeating the same request can immediately
392 // succeed with findings.
393 //
394 // `Error::stream` is classified retryable by the SDK, which is both
395 // accurate (the stream completed carrying no content) and nearly free:
396 // a response with no output tokens cost nothing to produce, so asking
397 // again is cheap. A *non-empty* body we cannot parse still returns
398 // `Ok(None)` and still does not retry - that is the deterministic case
399 // the split was built for, and re-sending it burns a full reasoning
400 // call for the same answer.
401 if text.trim().is_empty() && worth_asking_again(&finish) {
402 return Err(open_agent::Error::stream(
403 "the model returned an empty response",
404 ));
405 }
406
407 Ok(match extract_json(&text) {
408 Some(extracted) => Answer::Parsed(extracted),
409 // The text is carried out rather than dropped. It was discarded
410 // behind the constant "response contained no parseable JSON",
411 // which made every occurrence of this failure look identical and
412 // left no way to tell a refusal from a prose preamble from
413 // reasoning that leaked into the content channel.
414 None => Answer::NoJson { text, finish },
415 })
416 }
417}
418
419/// Build the fixed digest nested inside the response-cache key.
420///
421/// Length-prefixing through the cache's own encoder handles arbitrary UTF-8
422/// header values without reserving an escaping byte. Only the digest is kept;
423/// the framed credential-bearing text is never stored or logged.
424fn build_request_identity(
425 protocol: ApiProtocol,
426 max_tokens: Option<u32>,
427 headers: &BTreeMap<String, String>,
428) -> Result<String, LlmError> {
429 use crate::llm::cache::write_field;
430
431 let mut identity = blake3::Hasher::new();
432 write_field(&mut identity, protocol.as_str().as_bytes());
433 match max_tokens {
434 Some(limit) => {
435 write_field(&mut identity, b"set");
436 write_field(&mut identity, &limit.to_be_bytes());
437 }
438 None => write_field(&mut identity, b"unset"),
439 }
440
441 let mut canonical_headers = headers
442 .iter()
443 .map(|(name, value)| {
444 let canonical =
445 reqwest::header::HeaderName::from_bytes(name.as_bytes()).map_err(|_| {
446 LlmError::NotConfigured(format!("header name `{name}` cannot be encoded"))
447 })?;
448 Ok((canonical, value))
449 })
450 .collect::<Result<Vec<_>, LlmError>>()?;
451 canonical_headers.sort_by(|left, right| left.0.as_str().cmp(right.0.as_str()));
452 let header_count = u64::try_from(canonical_headers.len())
453 .expect("the process cannot hold more than u64::MAX headers");
454 write_field(&mut identity, &header_count.to_be_bytes());
455 for (name, value) in canonical_headers {
456 write_field(&mut identity, name.as_str().as_bytes());
457 write_field(&mut identity, value.as_bytes());
458 }
459 Ok(identity.finalize().to_hex().to_string())
460}
461
462/// What one query produced, before the retry decision.
463///
464/// `NoJson` carries the body so the failure can be diagnosed and so
465/// `complete_json` can decide whether to ask again. The SDK's retry layer
466/// treats both variants as success and stops, which is what keeps the
467/// no-JSON decision here rather than inside it.
468enum Answer {
469 Parsed(Extracted),
470 /// No JSON at all, with why generation stopped. The reason decides whether
471 /// asking again can possibly help.
472 NoJson {
473 text: String,
474 finish: FinishReason,
475 },
476}
477
478/// How many times a response carrying no JSON at all is asked for again.
479///
480/// Not the same question as the SDK's transport retry, and deliberately a
481/// small number: each attempt is a full reasoning call. The rule this replaced
482/// never retried, justified as "the same prompt truncates the same way" - but
483/// that is [`Extracted::Truncated`], a different branch. A response with *no
484/// JSON at all* did not truncate an answer, it never produced one, and in
485/// practice it does not repeat: drep's own gated push failed on a different
486/// file each run, and each failing file analyzed cleanly when asked again.
487///
488/// Three total attempts, so two local retries before the provider chain may
489/// ask a fallback. Production output has been visibly garbled twice in a row
490/// and then parsed unchanged on a later run; the third attempt salvages that
491/// case without demoting an otherwise healthy provider.
492pub const NO_JSON_ATTEMPTS: u32 = 3;
493
494/// Whether asking the same question again could produce a different answer.
495///
496/// `false` for the reasons that are a property of the *request*: a token cap is
497/// hit identically every time, and a content filter that refused this payload
498/// refuses it again. `true` where the server told us nothing useful, because a
499/// model at temperature above zero can simply answer differently - which is
500/// what drep's own gated push demonstrated, failing on a different file each
501/// run with every failing file analyzing cleanly when asked again.
502fn worth_asking_again(finish: &FinishReason) -> bool {
503 // Written as a negated match on the two request-shaped reasons rather than
504 // as an enumeration of the rest. `FinishReason` is `#[non_exhaustive]`, so
505 // a wildcard arm is required either way - and an enumerated "everything
506 // else is retryable" arm sitting above it is behaviourally identical to the
507 // wildcard, which makes it undeletable-but-unobservable: exactly the dead
508 // code the mutation gate exists to find.
509 //
510 // The consequence of the wildcard is deliberate: a reason a later SDK adds
511 // defaults to retrying. The retry is bounded and cheap to be wrong about,
512 // whereas refusing to retry something transient fails a commit outright.
513 !matches!(
514 finish,
515 // A token cap is hit identically every time - drep sends no
516 // `max_tokens`, so the cap is the server's. A content filter that
517 // refused this payload refuses it again.
518 FinishReason::Length | FinishReason::ContentFilter
519 )
520}
521
522/// A sentence a user can act on, for the reasons that end the attempt.
523///
524/// The two cases want different actions - one is "this file is too big for this
525/// model in one pass", the other is "this provider refused the content" - so
526/// they do not share a message.
527fn stopped_message(finish: &FinishReason, text: &str) -> String {
528 match finish {
529 FinishReason::Length => format!(
530 "the model hit its output token limit before producing any JSON. \
531 This file is too large for this model to review in one request - \
532 split it, or use a provider with a larger output budget. \
533 It managed: {}",
534 excerpt(text, RESPONSE_EXCERPT_MAX)
535 ),
536 _ => format!(
537 "the model stopped ({}) before producing any JSON: {}",
538 finish.as_str(),
539 excerpt(text, RESPONSE_EXCERPT_MAX)
540 ),
541 }
542}
543
544#[cfg(test)]
545mod tests;