#![allow(warnings)]
use serde::{Serialize, Deserialize};
use serde::de::DeserializeOwned;
use indexmap::IndexMap;
use atlas_http::{HttpClient, HttpBody, HttpRequest};
use regex::Regex;
use std::io;
#[cfg(feature = "tools")]
pub mod tools;
#[cfg(feature = "tools")]
const MAX_TOOL_CALLS: usize = 20;
#[derive(Default, Clone, Serialize, Deserialize)]
pub struct LlmProfile {
pub provider: LlmProvider, pub api_key: String, pub model_name: String, pub temperature: Option<f32>, pub max_tokens: Option<usize>, pub api_url: String, }
#[derive(Default, Clone, Serialize, Deserialize, Eq, PartialEq, Hash)]
pub enum LlmProvider {
#[default]
ollama,
openai,
anthropic,
google,
xai,
mistral,
deepseek,
groq,
together,
openrouter,
openai_responses, other
}
#[derive(Serialize, Deserialize, Clone)]
struct ChatMessage {
role: String,
#[serde(skip_serializing_if = "Option::is_none")]
content: Option<String>,
#[cfg(feature = "tools")]
#[serde(skip_serializing_if = "Option::is_none")]
tool_calls: Option<Vec<tools::ToolCall>>,
#[cfg(feature = "tools")]
#[serde(skip_serializing_if = "Option::is_none")]
tool_call_id: Option<String>,
}
#[derive(Serialize, Deserialize)]
struct ChatRequest {
model: String, messages: Vec<ChatMessage>, temperature: Option<f32>, max_tokens: Option<usize>, #[cfg(feature = "tools")]
#[serde(skip_serializing_if = "Option::is_none")]
tools: Option<Vec<tools::ToolDefinition>>,
}
#[derive(Serialize, Deserialize)]
struct ChatRequest_Ollama {
model: String, messages: Vec<ChatMessage>, stream: bool, temperature: Option<f32>, max_tokens: Option<usize>, #[cfg(feature = "tools")]
#[serde(skip_serializing_if = "Option::is_none")]
tools: Option<Vec<tools::ToolDefinition>>,
}
#[derive(Serialize, Deserialize)]
struct ChatRequest_OpenAIResponses {
model: String, input: Vec<ChatMessage>, #[serde(skip_serializing_if = "Option::is_none")]
max_output_tokens: Option<usize>, store: bool, }
#[derive(Deserialize)]
struct ResponsesApiResponse {
#[serde(default)]
status: Option<String>,
#[serde(default)]
output: Vec<ResponsesOutputItem>,
#[serde(default)]
error: Option<ResponsesError>,
#[serde(default)]
incomplete_details: Option<ResponsesIncompleteDetails>,
}
#[derive(Deserialize)]
struct ResponsesOutputItem {
#[serde(rename = "type")]
item_type: String,
#[serde(default)]
content: Option<Vec<ResponsesContent>>,
}
#[derive(Deserialize)]
struct ResponsesContent {
#[serde(rename = "type")]
content_type: String,
#[serde(default)]
text: Option<String>,
#[serde(default)]
refusal: Option<String>,
}
#[derive(Deserialize)]
struct ResponsesError {
#[serde(default)]
code: Option<String>,
#[serde(default)]
message: Option<String>,
}
#[derive(Deserialize)]
struct ResponsesIncompleteDetails {
#[serde(default)]
reason: Option<String>,
}
#[derive(Serialize, Deserialize)]
struct ChatChoice {
message: ChatMessage,
}
#[derive(Serialize, Deserialize)]
struct ChatResponse {
choices: Vec<ChatChoice>, }
impl LlmProfile {
pub fn send_single(&self, message: &str) -> Result<String, io::Error> {
if self.provider == LlmProvider::ollama {
return self.send_ollama(message);
}
if self.provider == LlmProvider::openai_responses {
return self.send_openai_responses(message);
}
let request = ChatRequest {
model: self.model_name.clone(),
messages: vec![ChatMessage {
role: "user".to_string(),
content: Some(message.to_string()),
#[cfg(feature = "tools")]
tool_calls: None,
#[cfg(feature = "tools")]
tool_call_id: None,
}],
temperature: self.temperature,
max_tokens: self.max_tokens,
#[cfg(feature = "tools")]
tools: None,
};
let json_str = serde_json::to_string(&request)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?;
self.send(&json_str)
}
pub fn send_ollama(&self, message: &str) -> Result<String, io::Error> {
let request = ChatRequest_Ollama {
model: self.model_name.clone(),
stream: false, messages: vec![ChatMessage {
role: "user".to_string(),
content: Some(message.to_string()),
#[cfg(feature = "tools")]
tool_calls: None,
#[cfg(feature = "tools")]
tool_call_id: None,
}],
temperature: self.temperature,
max_tokens: self.max_tokens,
#[cfg(feature = "tools")]
tools: None,
};
let json_str = serde_json::to_string(&request)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?;
self.send(&json_str)
}
pub fn send_openai_responses(&self, message: &str) -> Result<String, io::Error> {
let messages = vec![ChatMessage {
role: "user".to_string(),
content: Some(message.to_string()),
#[cfg(feature = "tools")]
tool_calls: None,
#[cfg(feature = "tools")]
tool_call_id: None,
}];
let json_str = self.build_openai_responses_request(messages)?;
self.send(&json_str)
}
fn build_openai_responses_request(&self, messages: Vec<ChatMessage>) -> Result<String, io::Error> {
let request = ChatRequest_OpenAIResponses {
model: self.model_name.clone(),
input: messages,
max_output_tokens: self.max_tokens,
store: false,
};
serde_json::to_string(&request)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))
}
fn parse_openai_responses(body: &str) -> Result<String, io::Error> {
let res: ResponsesApiResponse = serde_json::from_str(body)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?;
if let Some(err) = res.error {
return Err(io::Error::new(
io::ErrorKind::Other,
format!(
"OpenAI error ({}): {}",
err.code.unwrap_or_default(),
err.message.unwrap_or_default()
),
));
}
let mut text = String::new();
let mut refusal: Option<String> = None;
for item in res.output.iter().filter(|i| i.item_type == "message") {
for part in item.content.iter().flatten() {
match part.content_type.as_str() {
"output_text" => text.push_str(part.text.as_deref().unwrap_or_default()),
"refusal" => refusal = part.refusal.clone(),
_ => {}
}
}
}
if !text.is_empty() {
return Ok(text);
}
if let Some(r) = refusal {
return Err(io::Error::new(io::ErrorKind::Other, format!("Model refused: {}", r)));
}
if res.status.as_deref() == Some("incomplete") {
let reason = res.incomplete_details
.and_then(|d| d.reason)
.unwrap_or_else(|| "unknown".to_string());
return Err(io::Error::new(
io::ErrorKind::Other,
format!("Incomplete response with no output text (reason: {})", reason),
));
}
Err(io::Error::new(io::ErrorKind::Other, "No output text in response"))
}
fn send(&self, json_str: &str) -> Result<String, io::Error> {
let body = HttpBody::from_raw_str(json_str);
let auth_line = format!("Authorization: Bearer {}", self.api_key);
let auth_header = vec![
auth_line.as_str(),
"Content-type: application/json"
];
let mut url = if self.api_url.is_empty() {
self.provider.get_completion_url()
} else {
self.api_url.clone()
};
url = url.replace("~model~", &self.model_name);
url = url.replace("~api_key~", &self.api_key);
let req = HttpRequest::new("POST", &url, &auth_header, &body);
let mut http = HttpClient::builder().browser().build_sync();
let res = http.send(&req)
.map_err(|e| io::Error::new(io::ErrorKind::Other, e.to_string()))?;
if res.status_code() != 200 {
return Err(io::Error::new(
io::ErrorKind::Other,
format!("HTTP error: {}", res.status_code())
));
}
if self.provider == LlmProvider::ollama {
let json_res: ChatChoice = serde_json::from_str(&res.body())
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?;
Ok(json_res.message.content.clone().unwrap_or_default())
} else if self.provider == LlmProvider::openai_responses {
Self::parse_openai_responses(&res.body())
} else {
let json_res: ChatResponse = serde_json::from_str(&res.body())
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?;
if json_res.choices.is_empty() {
return Err(io::Error::new(
io::ErrorKind::Other,
"No choices in response"
));
}
Ok(json_res.choices[0].message.content.clone().unwrap_or_default())
}
}
#[cfg(feature = "tools")]
pub fn send_with_tools(&self, message: &str, ollama_api_key: &str) -> Result<String, io::Error> {
self.send_with_tools_inner(message, ollama_api_key, None)
}
#[cfg(feature = "tools")]
pub fn send_with_tools_timeout(&self, message: &str, ollama_api_key: &str, timeout: std::time::Duration) -> Result<String, io::Error> {
let deadline = std::time::Instant::now() + timeout;
let (profile, message, api_key) = (self.clone(), message.to_string(), ollama_api_key.to_string());
let (tx, rx) = std::sync::mpsc::channel();
std::thread::Builder::new().name("sermo-llm".to_string()).spawn(move || {
let _ = tx.send(profile.send_with_tools_inner(&message, &api_key, Some(deadline)));
})?;
match rx.recv_timeout(timeout) {
Ok(res) => res,
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => Err(io::Error::new(io::ErrorKind::TimedOut, format!("LLM request timed out after {}s", timeout.as_secs_f32()))),
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => Err(io::Error::new(io::ErrorKind::Other, "LLM worker thread panicked")),
}
}
#[cfg(feature = "tools")]
fn send_with_tools_inner(&self, message: &str, ollama_api_key: &str, deadline: Option<std::time::Instant>) -> Result<String, io::Error> {
use tools::{Tool, web_search::WebSearchTool, web_fetch::WebFetchTool};
let web_search = WebSearchTool::new(ollama_api_key.to_string());
let web_fetch = WebFetchTool::new();
let tools_desc = r#"You have access to tools. When you need current information, use a tool by responding with ONLY a JSON object in this exact format:
{"tool": "<tool_name>", "parameters": {...}}
Available tools:
1. web_search - Search the web for current information
Parameters: {"query": "search query string"}
Example: {"tool": "web_search", "parameters": {"query": "latest news"}}
2. web_fetch - Fetch and read a web page
Parameters: {"url": "https://example.com"}
Example: {"tool": "web_fetch", "parameters": {"url": "https://example.com/page"}}
IMPORTANT: When using a tool, respond with ONLY the JSON object, nothing else - no explanations, no markdown code fences, just the raw JSON.
After you receive the tool result, you can then provide your final answer to the user."#;
let system_msg = format!("You are a helpful assistant.\n\n{}", tools_desc);
let mut messages = vec![
ChatMessage {
role: "system".to_string(),
content: Some(system_msg),
#[cfg(feature = "tools")]
tool_calls: None,
#[cfg(feature = "tools")]
tool_call_id: None,
},
ChatMessage {
role: "user".to_string(),
content: Some(message.to_string()),
#[cfg(feature = "tools")]
tool_calls: None,
#[cfg(feature = "tools")]
tool_call_id: None,
}
];
for iteration in 0..MAX_TOOL_CALLS {
if deadline.map_or(false, |d| std::time::Instant::now() >= d) {
return Err(io::Error::new(io::ErrorKind::TimedOut, "LLM request deadline reached"));
}
let json_str = if self.provider == LlmProvider::ollama {
let request = ChatRequest_Ollama {
model: self.model_name.clone(),
stream: false,
messages: messages.clone(),
temperature: self.temperature,
max_tokens: self.max_tokens,
#[cfg(feature = "tools")]
tools: None, };
serde_json::to_string(&request)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?
} else if self.provider == LlmProvider::openai_responses {
self.build_openai_responses_request(messages.clone())?
} else {
let request = ChatRequest {
model: self.model_name.clone(),
messages: messages.clone(),
temperature: self.temperature,
max_tokens: self.max_tokens,
#[cfg(feature = "tools")]
tools: None, };
serde_json::to_string(&request)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?
};
let body = HttpBody::from_raw_str(&json_str);
let auth_line = format!("Authorization: Bearer {}", self.api_key);
let auth_header = vec![auth_line.as_str(), "Content-type: application/json"];
let mut url = if self.api_url.is_empty() {
self.provider.get_completion_url()
} else {
self.api_url.clone()
};
url = url.replace("~model~", &self.model_name);
url = url.replace("~api_key~", &self.api_key);
let req = HttpRequest::new("POST", &url, &auth_header, &body);
let mut http = match deadline {
Some(d) => HttpClient::builder().browser().read_timeout(d.saturating_duration_since(std::time::Instant::now()).as_secs_f32().ceil() as u64).build_sync(),
None => HttpClient::builder().browser().build_sync(),
};
let res = http.send(&req)
.map_err(|e| io::Error::new(io::ErrorKind::Other, e.to_string()))?;
if res.status_code() != 200 {
return Err(io::Error::new(
io::ErrorKind::Other,
format!("HTTP error: {}", res.status_code())
));
}
let assistant_message = if self.provider == LlmProvider::ollama {
let json_res: ChatChoice = serde_json::from_str(&res.body())
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?;
json_res.message
} else if self.provider == LlmProvider::openai_responses {
ChatMessage {
role: "assistant".to_string(),
content: Some(Self::parse_openai_responses(&res.body())?),
#[cfg(feature = "tools")]
tool_calls: None,
#[cfg(feature = "tools")]
tool_call_id: None,
}
} else {
let json_res: ChatResponse = serde_json::from_str(&res.body())
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?;
if json_res.choices.is_empty() {
return Err(io::Error::new(io::ErrorKind::Other, "No choices in response"));
}
json_res.choices[0].message.clone()
};
let response_text = assistant_message.content.unwrap_or_default();
#[derive(serde::Deserialize)]
struct ToolRequest {
tool: String,
parameters: serde_json::Value,
}
let tool_request: Option<ToolRequest> = self.extract_json_flexible(&response_text);
if let Some(tool_req) = tool_request {
println!("Tool call detected: {}", tool_req.tool);
messages.push(ChatMessage {
role: "assistant".to_string(),
content: Some(response_text.clone()),
#[cfg(feature = "tools")]
tool_calls: None,
#[cfg(feature = "tools")]
tool_call_id: None,
});
let params_str = tool_req.parameters.to_string();
let result = match tool_req.tool.as_str() {
"web_search" => std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| web_search.execute(¶ms_str))).unwrap_or_else(|_| Err(io::Error::new(io::ErrorKind::Other, "web_search failed unexpectedly (network unavailable?)"))),
"web_fetch" => std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| web_fetch.execute(¶ms_str))).unwrap_or_else(|_| Err(io::Error::new(io::ErrorKind::Other, "web_fetch failed unexpectedly (network unavailable?)"))),
_ => Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("Unknown tool: {}", tool_req.tool)
)),
};
let tool_result_content = match result {
Ok(content) => content,
Err(e) => format!("Error executing {}: {}", tool_req.tool, e),
};
messages.push(ChatMessage {
role: "user".to_string(), content: Some(format!("Tool result:\n{}", tool_result_content)),
#[cfg(feature = "tools")]
tool_calls: None,
#[cfg(feature = "tools")]
tool_call_id: None,
});
} else {
return Ok(response_text);
}
}
Err(io::Error::new(
io::ErrorKind::Other,
format!("Maximum tool call iterations ({}) reached", MAX_TOOL_CALLS)
))
}
pub fn extract_json<T: DeserializeOwned>(&self, input: &str, is_object: bool) -> Option<T> {
let start_char = if is_object { '{' } else { '[' };
let start_idx = input.find(start_char)?;
let mut depth = 0;
let end_char = if is_object { '}' } else { ']' };
let mut end_idx = 0;
for (i, c) in input[start_idx..].char_indices() {
if c == start_char {
depth += 1;
} else if c == end_char {
depth -= 1;
if depth == 0 {
end_idx = start_idx + i + 1;
break;
}
}
}
if end_idx == 0 || depth != 0 {
return None;
}
let json_str = &input[start_idx..end_idx];
serde_json::from_str(json_str).ok()
}
pub fn extract_json_flexible<T: DeserializeOwned>(&self, input: &str) -> Option<T> {
if let Some(result) = self.extract_json::<T>(input, true) {
return Some(result);
}
if let Some(result) = self.extract_json::<T>(input, false) {
return Some(result);
}
let re_string = Regex::new(r#""([^"\\]|\\[\s\S])*""#).ok()?;
if let Some(m) = re_string.find(input) {
if let Ok(value) = serde_json::from_str::<T>(m.as_str()) {
return Some(value);
}
}
let re_scalar = Regex::new(r"\b(true|false|null|-?\d+(\.\d+)?([eE][+-]?\d+)?)\b").ok()?;
if let Some(m) = re_scalar.find(input) {
if let Ok(value) = serde_json::from_str::<T>(m.as_str()) {
return Some(value);
}
}
None
}
pub fn from_str(
provider_slug: &str,
model_name: &str,
api_key: &str,
temperature: Option<f32>,
max_tokens: Option<usize>,
) -> Self {
LlmProfile {
provider: LlmProvider::from_str(provider_slug),
api_key: api_key.to_string(),
model_name: model_name.to_string(),
temperature,
max_tokens,
api_url: String::new(), }
}
}
impl LlmProvider {
pub fn from_usize(value: usize) -> Self {
match value {
0 => Self::ollama,
1 => Self::openai,
2 => Self::anthropic,
3 => Self::google,
4 => Self::xai,
5 => Self::mistral,
6 => Self::deepseek,
7 => Self::groq,
8 => Self::together,
9 => Self::openai_responses,
_ => Self::other
}
}
pub fn to_string(&self) -> String {
match self {
Self::ollama => "Ollama".to_string(),
Self::openai => "OpenAI".to_string(),
Self::anthropic => "Anthropic".to_string(),
Self::google => "Google Gemini".to_string(),
Self::xai => "X.ai".to_string(),
Self::mistral => "Mistral".to_string(),
Self::deepseek => "Deepseek".to_string(),
Self::groq => "Groq".to_string(),
Self::together => "TogetherAI".to_string(),
Self::openai_responses => "OpenAI 5.6+".to_string(),
_ => "Other".to_string()
}
}
pub fn to_slug(&self) -> String {
match self {
Self::ollama => "ollama".to_string(),
Self::openai => "openai".to_string(),
Self::anthropic => "anthropic".to_string(),
Self::google => "google".to_string(),
Self::xai => "xai".to_string(),
Self::mistral => "mistral".to_string(),
Self::deepseek => "deepseek".to_string(),
Self::groq => "groq".to_string(),
Self::together => "together".to_string(),
Self::openai_responses => "openai_responses".to_string(),
_ => "other".to_string()
}
}
pub fn get_indexmap_options() -> IndexMap<String, String> {
let mut options = IndexMap::new();
for x in 1..10 {
let val = Self::from_usize(x);
options.insert(format!("{}", x), val.to_string());
}
options
}
fn get_completion_url(&self) -> String {
match self {
LlmProvider::ollama => "http://localhost:11434/api/chat".to_string(),
LlmProvider::openai => "https://api.openai.com/v1/chat/completions".to_string(),
LlmProvider::anthropic => "https://api.anthropic.com/v1/messages".to_string(),
LlmProvider::google => "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions".to_string(),
LlmProvider::xai => "https://api.x.ai/v1/chat/completions".to_string(),
LlmProvider::mistral => "https://api.mixtral.ai/v1/chat/completions".to_string(),
LlmProvider::deepseek => "https://api.deepseek.com/v1/chat/completions".to_string(),
LlmProvider::groq => "https://api.groq.com/openai/v1/chat/completions".to_string(),
LlmProvider::together => "https://api.together.xyz/v1/chat/completions".to_string(),
LlmProvider::openrouter => "https://openrouter.ai/api/v1/chat/completions".to_string(),
LlmProvider::openai_responses => "https://api.openai.com/v1/responses".to_string(),
LlmProvider::other => "http://localhost:8000/v1/chat/completions".to_string(),
}
}
fn from_str(slug: &str) -> Self {
match slug.to_lowercase().as_str() {
"ollama" => LlmProvider::ollama,
"openai" => LlmProvider::openai,
"anthropic" => LlmProvider::anthropic,
"google" => LlmProvider::google,
"xai" => LlmProvider::xai,
"mistral" => LlmProvider::mistral,
"deepseek" => LlmProvider::deepseek,
"groq" => LlmProvider::groq,
"together" => LlmProvider::together,
"openrouter" => Self::openrouter,
"openai_responses" => Self::openai_responses,
_ => LlmProvider::other,
}
}
}