use anyhow::Result; use serde::{Deserialize, Serialize}; use std::time::Duration; use tracing::{debug, error}; use crate::core::config; use crate::core::llm::function_calling::LLM_CLIENT; #[derive(Debug, Serialize)] struct ChatRequest { model: String, messages: Vec, temperature: f32, max_tokens: u32, stream: bool, } #[derive(Debug, Serialize, Deserialize)] struct ChatMessage { role: String, content: String, } #[derive(Debug, Deserialize)] struct ChatResponse { choices: Vec, } #[derive(Debug, Deserialize)] struct Choice { message: ChatMessage, } pub async fn ask_llm(prompt: &str, system_prompt: &str) -> Result { let req = serde_json::json!({ "model": (*config::llm::SUMMARY_MODEL).clone(), "messages": [ { "role": "system", "content": system_prompt.to_string(), }, { "role": "user", "content": prompt.to_string(), }, ], "temperature": 0.1, "max_tokens": 512, "stream": false, "chat_template_kwargs": {"enable_thinking": false} }); debug!("Calling LLM: {}", *config::llm::SUMMARY_URL); let res = LLM_CLIENT .post(&*config::llm::SUMMARY_URL) .json(&req) .timeout(Duration::from_secs(*config::llm::SUMMARY_TIMEOUT_SECS)) .send() .await?; if !res.status().is_success() { error!("LLM API error: {}", res.status()); let text = res.text().await.unwrap_or_default(); anyhow::bail!("LLM API error: {}", text); } #[derive(Debug, Deserialize)] struct ChatResponseExt { choices: Vec, } #[derive(Debug, Deserialize)] struct ChoiceExt { message: ChatMessageExt, finish_reason: Option, } #[derive(Debug, Deserialize)] struct ChatMessageExt { content: Option, } let chat_res: ChatResponseExt = res.json().await?; if let Some(choice) = chat_res.choices.first() { if choice.finish_reason.as_deref() == Some("length") { anyhow::bail!("LLM returned truncated response (finish_reason=length)"); } } if let Some(choice) = chat_res.choices.into_iter().next() { let content = choice.message.content.filter(|s| !s.trim().is_empty()).unwrap_or_default(); if content.trim().is_empty() { anyhow::bail!("Empty response from LLM"); } Ok(content.trim().to_string()) } else { anyhow::bail!("Empty response from LLM"); } }