Files
pruefwerk/compliance-agent/src/llm/client.rs
T
sharang 7d73893485
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Skipped
CI / Deploy Dashboard (push) Successful in 4m21s
CI / Deploy MCP (push) Successful in 4m17s
CI / Deploy Agent (push) Successful in 8m51s
fix(llm): configurable call timeout; one failed triage call is not "model down" (#588)
2026-11-04 08:10:46 +00:00

492 lines
17 KiB
Rust

use secrecy::{ExposeSecret, SecretString};
use super::types::*;
use crate::error::AgentError;
#[derive(Clone)]
pub struct LlmClient {
pub(crate) base_url: String,
pub(crate) api_key: SecretString,
pub(crate) model: String,
pub(crate) embed_model: String,
pub(crate) http: reqwest::Client,
}
impl LlmClient {
pub fn new(
base_url: String,
api_key: SecretString,
model: String,
embed_model: String,
) -> Self {
Self {
base_url,
api_key,
model,
embed_model,
http: http_client(DEFAULT_TIMEOUT),
}
}
/// The same client with `timeout` for each call in total (connecting, the
/// gateway's queue and the answer).
pub fn with_timeout(mut self, timeout: std::time::Duration) -> Self {
self.http = http_client(timeout);
self
}
pub(crate) fn chat_url(&self) -> String {
format!(
"{}/v1/chat/completions",
self.base_url.trim_end_matches('/')
)
}
pub(crate) fn auth_header(&self) -> Option<String> {
let key = self.api_key.expose_secret();
if key.is_empty() {
None
} else {
Some(format!("Bearer {key}"))
}
}
/// Simple chat: system + user prompt → text response
pub async fn chat(
&self,
system_prompt: &str,
user_prompt: &str,
temperature: Option<f64>,
) -> Result<String, AgentError> {
let messages = vec![
ChatMessage {
role: "system".to_string(),
content: Some(system_prompt.to_string()),
tool_calls: None,
tool_call_id: None,
},
ChatMessage {
role: "user".to_string(),
content: Some(user_prompt.to_string()),
tool_calls: None,
tool_call_id: None,
},
];
let request_body = ChatCompletionRequest {
model: self.model.clone(),
messages,
temperature,
max_tokens: Some(4096),
tools: None,
};
self.send_chat_request(&request_body).await.map(|resp| {
match resp {
LlmResponse::Content(c) => c,
LlmResponse::ToolCalls { .. } => String::new(), // shouldn't happen without tools
}
})
}
/// Like [`Self::chat`], with a token budget of `max_tokens` (a reasoning
/// model spends it on thinking and the answer together), and whether the
/// answer was cut off at that budget (`finish_reason: length`): a cut-off
/// answer is returned as far as it got, for the caller to use what is
/// complete in it.
///
/// # Errors
///
/// As [`Self::chat`].
pub async fn chat_with_budget(
&self,
system_prompt: &str,
user_prompt: &str,
temperature: Option<f64>,
max_tokens: u32,
) -> Result<ChatAnswer, AgentError> {
let messages = vec![
ChatMessage {
role: "system".to_string(),
content: Some(system_prompt.to_string()),
tool_calls: None,
tool_call_id: None,
},
ChatMessage {
role: "user".to_string(),
content: Some(user_prompt.to_string()),
tool_calls: None,
tool_call_id: None,
},
];
let request_body = ChatCompletionRequest {
model: self.model.clone(),
messages,
temperature,
max_tokens: Some(max_tokens),
tools: None,
};
let (response, finish_reason) = self.send_chat_request_with_reason(&request_body).await?;
Ok(ChatAnswer {
content: match response {
LlmResponse::Content(c) => c,
LlmResponse::ToolCalls { .. } => String::new(),
},
cut_off: finish_reason.as_deref() == Some("length"),
})
}
/// Chat with a list of (role, content) messages → text response
#[allow(dead_code)]
pub async fn chat_with_messages(
&self,
messages: Vec<(String, String)>,
temperature: Option<f64>,
) -> Result<String, AgentError> {
let messages = messages
.into_iter()
.map(|(role, content)| ChatMessage {
role,
content: Some(content),
tool_calls: None,
tool_call_id: None,
})
.collect();
let request_body = ChatCompletionRequest {
model: self.model.clone(),
messages,
temperature,
max_tokens: Some(4096),
tools: None,
};
self.send_chat_request(&request_body)
.await
.map(|resp| match resp {
LlmResponse::Content(c) => c,
LlmResponse::ToolCalls { .. } => String::new(),
})
}
/// Chat with tool definitions — returns either content or tool calls.
/// Use this for the AI pentest orchestrator loop.
pub async fn chat_with_tools(
&self,
messages: Vec<ChatMessage>,
tools: &[ToolDefinition],
temperature: Option<f64>,
max_tokens: Option<u32>,
) -> Result<LlmResponse, AgentError> {
let tool_payloads: Vec<ToolDefinitionPayload> = tools
.iter()
.map(|t| ToolDefinitionPayload {
r#type: "function".to_string(),
function: ToolFunctionPayload {
name: t.name.clone(),
description: t.description.clone(),
parameters: t.parameters.clone(),
},
})
.collect();
let request_body = ChatCompletionRequest {
model: self.model.clone(),
messages,
temperature,
max_tokens: Some(max_tokens.unwrap_or(8192)),
tools: if tool_payloads.is_empty() {
None
} else {
Some(tool_payloads)
},
};
self.send_chat_request(&request_body).await
}
/// Send a chat completion request and parse the response.
///
/// A reasoning model can spend the whole token budget thinking and return
/// no answer (`finish_reason: length`, the content empty or an unclosed
/// `<think>` block). The request is then sent once more with
/// [`REASONING_RETRY_TOKENS`].
///
/// # Errors
///
/// The gateway's refusal, an unreadable response, or
/// [`REASONING_EXHAUSTED`] when even the larger budget gave no answer.
async fn send_chat_request(
&self,
request_body: &ChatCompletionRequest,
) -> Result<LlmResponse, AgentError> {
self.send_chat_request_with_reason(request_body)
.await
.map(|(response, _)| response)
}
/// [`Self::send_chat_request`], and the reason the model stopped.
async fn send_chat_request_with_reason(
&self,
request_body: &ChatCompletionRequest,
) -> Result<(LlmResponse, Option<String>), AgentError> {
let (response, finish_reason) = self.send_once(request_body).await?;
if !exhausted(&response, finish_reason.as_deref()) {
return Ok((response, finish_reason));
}
if request_body.max_tokens.unwrap_or(0) >= REASONING_RETRY_TOKENS {
return Err(AgentError::Other(REASONING_EXHAUSTED.to_string()));
}
tracing::info!(
budget = request_body.max_tokens,
retry = REASONING_RETRY_TOKENS,
"the model used its token budget reasoning and gave no answer; asking again with more"
);
let mut larger = serde_json::to_value(request_body)
.map_err(|e| AgentError::Other(format!("encode chat request: {e}")))?;
larger["max_tokens"] = serde_json::json!(REASONING_RETRY_TOKENS);
let (response, finish_reason) = self.send_once(&larger).await?;
if exhausted(&response, finish_reason.as_deref()) {
return Err(AgentError::Other(REASONING_EXHAUSTED.to_string()));
}
Ok((response, finish_reason))
}
/// One chat completion request, and the reason the model stopped.
async fn send_once<B: serde::Serialize + ?Sized>(
&self,
request_body: &B,
) -> Result<(LlmResponse, Option<String>), AgentError> {
if self.model.is_empty() {
return Err(AgentError::Other(NO_CHAT_MODEL.to_string()));
}
let mut req = self
.http
.post(self.chat_url())
.header("content-type", "application/json")
.json(request_body);
if let Some(auth) = self.auth_header() {
req = req.header("Authorization", auth);
}
let resp = req
.send()
.await
.map_err(|e| AgentError::Other(format!("LiteLLM request failed: {e}")))?;
if !resp.status().is_success() {
let status = resp.status();
let body = resp.text().await.unwrap_or_default();
return Err(AgentError::Other(format!(
"LiteLLM returned {status}: {body}"
)));
}
let body: ChatCompletionResponse = resp
.json()
.await
.map_err(|e| AgentError::Other(format!("Failed to parse LiteLLM response: {e}")))?;
let choice = body
.choices
.first()
.ok_or_else(|| AgentError::Other("Empty response from LiteLLM".to_string()))?;
let finish_reason = choice.finish_reason.clone();
// Check for tool calls first
if let Some(tool_calls) = &choice.message.tool_calls {
if !tool_calls.is_empty() {
let calls: Vec<LlmToolCall> = tool_calls
.iter()
.map(|tc| {
let arguments = serde_json::from_str(&tc.function.arguments)
.unwrap_or(serde_json::Value::Object(serde_json::Map::new()));
LlmToolCall {
id: tc.id.clone(),
name: tc.function.name.clone(),
arguments,
}
})
.collect();
// Capture any reasoning text the LLM included alongside tool calls
let reasoning = choice.message.content.clone().unwrap_or_default();
return Ok((LlmResponse::ToolCalls { calls, reasoning }, finish_reason));
}
}
// Otherwise return content
let content = choice.message.content.as_deref().unwrap_or_default();
Ok((
LlmResponse::Content(without_reasoning(content)),
finish_reason,
))
}
}
/// The error when no chat model is configured: the request is not sent.
pub(crate) const NO_CHAT_MODEL: &str = "LLM off: LITELLM_MODEL is not set";
/// A text answer, and whether the model stopped at its token budget.
#[derive(Debug, Clone, PartialEq)]
pub struct ChatAnswer {
/// The answer, without the model's reasoning.
pub content: String,
/// The model was cut off at its token budget: the answer may be partial.
pub cut_off: bool,
}
/// The token budget of the second request when the first ran out while the
/// model was still reasoning.
const REASONING_RETRY_TOKENS: u32 = 16384;
/// Total time per LLM call unless the deployment sets one (`LLM_TIMEOUT_SECS`):
/// our LiteLLM gateway's own request timeout.
const DEFAULT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(600);
fn http_client(timeout: std::time::Duration) -> reqwest::Client {
reqwest::Client::builder()
.timeout(timeout)
.connect_timeout(std::time::Duration::from_secs(10))
.build()
.unwrap_or_default()
}
/// The error when the model gave no answer even with
/// [`REASONING_RETRY_TOKENS`].
const REASONING_EXHAUSTED: &str =
"the model used its whole token budget reasoning and gave no answer (finish_reason=length)";
/// Whether a response is no answer because the model ran out of tokens.
fn exhausted(response: &LlmResponse, finish_reason: Option<&str>) -> bool {
matches!(response, LlmResponse::Content(c) if c.is_empty()) && finish_reason == Some("length")
}
/// `content` without a reasoning model's `<think>…</think>` blocks, which some
/// gateways return inline ahead of the answer; the callers parse the answer as
/// JSON. An unterminated block (the model ran out of tokens while thinking)
/// leaves nothing to parse, so it becomes empty.
fn without_reasoning(content: &str) -> String {
let mut rest = content;
let mut out = String::with_capacity(content.len());
while let Some(start) = rest.find("<think>") {
out.push_str(&rest[..start]);
match rest[start..].find("</think>") {
Some(end) => rest = &rest[start + end + "</think>".len()..],
None => {
rest = "";
break;
}
}
}
out.push_str(rest);
out.trim().to_string()
}
#[cfg(test)]
mod reasoning_tests {
use super::without_reasoning;
#[test]
fn a_reasoning_models_thinking_is_not_part_of_the_answer() {
assert_eq!(
without_reasoning(
"<think>the finding is in a test file</think>\n[{\"action\":\"dismiss\"}]"
),
"[{\"action\":\"dismiss\"}]"
);
assert_eq!(without_reasoning("[1, 2]"), "[1, 2]");
assert_eq!(without_reasoning("<think>still going"), "");
}
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod budget_tests {
use std::sync::{Arc, Mutex};
use axum::extract::State;
use axum::routing::post;
use axum::{Json, Router};
use super::*;
/// The `max_tokens` of every request a fake gateway received; it answers
/// "still thinking" until the budget reaches `answers_from`.
type Seen = Arc<Mutex<Vec<u64>>>;
async fn fake_gateway(seen: Seen, answers_from: u64) -> String {
let app = Router::new()
.route(
"/v1/chat/completions",
post(
move |State(seen): State<Seen>, Json(body): Json<serde_json::Value>| async move {
let budget = body["max_tokens"].as_u64().unwrap_or(0);
seen.lock().unwrap().push(budget);
let (content, finish) = if budget >= answers_from {
("<think>done</think>[{\"action\":\"confirm\"}]", "stop")
} else {
("<think>weighing the first finding against", "length")
};
Json(serde_json::json!({
"choices": [{ "message": { "content": content }, "finish_reason": finish }]
}))
},
),
)
.with_state(seen);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
format!("http://{addr}")
}
fn client(base: String) -> LlmClient {
LlmClient::new(
base,
SecretString::from(String::new()),
"m".into(),
"e".into(),
)
}
#[tokio::test]
async fn a_reasoning_model_out_of_tokens_is_asked_again_with_more() {
let seen: Seen = Arc::default();
let llm = client(fake_gateway(seen.clone(), u64::from(REASONING_RETRY_TOKENS)).await);
let answer = llm.chat("s", "u", None).await.unwrap();
assert_eq!(answer, "[{\"action\":\"confirm\"}]");
assert_eq!(*seen.lock().unwrap(), [4096, 16384]);
}
#[tokio::test]
async fn no_answer_even_with_more_says_why() {
let seen: Seen = Arc::default();
let llm = client(fake_gateway(seen.clone(), u64::MAX).await);
let err = llm.chat("s", "u", None).await.unwrap_err();
assert!(err.to_string().contains("finish_reason=length"), "{err}");
assert_eq!(seen.lock().unwrap().len(), 2);
}
#[tokio::test]
async fn no_chat_model_makes_no_request() {
let seen: Seen = Arc::default();
let mut llm = client(fake_gateway(seen.clone(), 0).await);
llm.model = String::new();
let err = llm.chat("s", "u", None).await.unwrap_err();
assert_eq!(err.to_string(), NO_CHAT_MODEL);
assert!(
seen.lock().unwrap().is_empty(),
"no request may reach the gateway"
);
}
#[tokio::test]
async fn an_answer_in_budget_is_one_request() {
let seen: Seen = Arc::default();
let llm = client(fake_gateway(seen.clone(), 0).await);
llm.chat("s", "u", None).await.unwrap();
assert_eq!(*seen.lock().unwrap(), [4096]);
}
}