| 1 | use serde_json::{Value, json}; |
| 2 | |
| 3 | use crate::profile::{AgentBackend, AgentProfile}; |
| 4 | |
| 5 | const TURN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(120); |
| 6 | const PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15); |
| 7 | const ANTHROPIC_VERSION: &str = "2023-06-01"; |
| 8 | const ANTHROPIC_URL: &str = "https://api.anthropic.com/v1/messages"; |
| 9 | const MAX_TOKENS: u32 = 4096; |
| 10 | |
| 11 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 12 | pub struct ToolSpec { |
| 13 | pub name: String, |
| 14 | pub description: String, |
| 15 | pub parameters: Value, |
| 16 | } |
| 17 | |
| 18 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 19 | pub struct ToolCall { |
| 20 | pub id: String, |
| 21 | pub name: String, |
| 22 | pub arguments: String, |
| 23 | } |
| 24 | |
| 25 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 26 | pub enum ChatRole { |
| 27 | User, |
| 28 | Assistant, |
| 29 | Tool, |
| 30 | } |
| 31 | |
| 32 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 33 | pub struct ChatMessage { |
| 34 | pub role: ChatRole, |
| 35 | pub text: String, |
| 36 | pub tool_calls: Vec<ToolCall>, |
| 37 | pub tool_call_id: String, |
| 38 | } |
| 39 | |
| 40 | impl ChatMessage { |
| 41 | pub fn user(text: impl Into<String>) -> Self { |
| 42 | Self { |
| 43 | role: ChatRole::User, |
| 44 | text: text.into(), |
| 45 | tool_calls: Vec::new(), |
| 46 | tool_call_id: String::new(), |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | pub fn assistant(text: impl Into<String>, tool_calls: Vec<ToolCall>) -> Self { |
| 51 | Self { |
| 52 | role: ChatRole::Assistant, |
| 53 | text: text.into(), |
| 54 | tool_calls, |
| 55 | tool_call_id: String::new(), |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | pub fn tool(id: impl Into<String>, text: impl Into<String>) -> Self { |
| 60 | Self { |
| 61 | role: ChatRole::Tool, |
| 62 | text: text.into(), |
| 63 | tool_calls: Vec::new(), |
| 64 | tool_call_id: id.into(), |
| 65 | } |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 70 | pub enum ChatReply { |
| 71 | Text(String), |
| 72 | Tools { text: String, calls: Vec<ToolCall> }, |
| 73 | } |
| 74 | |
| 75 | pub async fn complete_text( |
| 76 | profile: &AgentProfile, |
| 77 | system: &str, |
| 78 | user: &str, |
| 79 | ) -> Result<String, String> { |
| 80 | match next_turn(profile, system, &[ChatMessage::user(user)], &[]).await? { |
| 81 | ChatReply::Text(text) => Ok(text), |
| 82 | ChatReply::Tools { text, .. } => Ok(text), |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | pub async fn next_turn( |
| 87 | profile: &AgentProfile, |
| 88 | system: &str, |
| 89 | messages: &[ChatMessage], |
| 90 | tools: &[ToolSpec], |
| 91 | ) -> Result<ChatReply, String> { |
| 92 | let body = match &profile.backend { |
| 93 | AgentBackend::OpenAi { .. } => openai_body(system, messages, tools), |
| 94 | AgentBackend::Anthropic { .. } => anthropic_body(profile, system, messages, tools)?, |
| 95 | AgentBackend::Command => return Err("this agent is a command, not a chat API".to_owned()), |
| 96 | }; |
| 97 | let value = post(profile, &body).await?; |
| 98 | match &profile.backend { |
| 99 | AgentBackend::OpenAi { .. } => parse_openai(&value), |
| 100 | AgentBackend::Anthropic { .. } => parse_anthropic(&value), |
| 101 | AgentBackend::Command => unreachable!(), |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | const MODEL_LIST_LIMIT: usize = 400; |
| 106 | |
| 107 | pub async fn list_models(profile: &AgentProfile) -> Result<Vec<String>, String> { |
| 108 | let (url, key, anthropic) = models_endpoint(profile)?; |
| 109 | let value = get(&key, &url, anthropic).await?; |
| 110 | let mut names = model_names(&value); |
| 111 | names.sort_by(|left, right| left.to_ascii_lowercase().cmp(&right.to_ascii_lowercase())); |
| 112 | names.dedup(); |
| 113 | names.truncate(MODEL_LIST_LIMIT); |
| 114 | if names.is_empty() { |
| 115 | return Err("the endpoint listed no models".to_owned()); |
| 116 | } |
| 117 | Ok(names) |
| 118 | } |
| 119 | |
| 120 | pub async fn probe_backend(profile: &AgentProfile) -> Result<String, String> { |
| 121 | let names = list_models(profile).await?; |
| 122 | Ok(match names.len() { |
| 123 | 1 => names[0].clone(), |
| 124 | 2..=4 => names.join(", "), |
| 125 | count => format!("{count} models"), |
| 126 | }) |
| 127 | } |
| 128 | |
| 129 | fn models_endpoint(profile: &AgentProfile) -> Result<(String, String, bool), String> { |
| 130 | match &profile.backend { |
| 131 | AgentBackend::OpenAi { |
| 132 | base_url, api_key, .. |
| 133 | } => Ok((models_url(base_url), api_key.clone(), false)), |
| 134 | AgentBackend::Anthropic { api_key, .. } => { |
| 135 | if api_key.trim().is_empty() { |
| 136 | return Err("the Anthropic key is empty".to_owned()); |
| 137 | } |
| 138 | Ok(( |
| 139 | "https://api.anthropic.com/v1/models".to_owned(), |
| 140 | api_key.clone(), |
| 141 | true, |
| 142 | )) |
| 143 | } |
| 144 | AgentBackend::Command => Err("this agent is a command".to_owned()), |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | fn openai_body(system: &str, messages: &[ChatMessage], tools: &[ToolSpec]) -> Value { |
| 149 | let mut chat = Vec::new(); |
| 150 | if !system.is_empty() { |
| 151 | chat.push(json!({"role": "system", "content": system})); |
| 152 | } |
| 153 | for message in messages { |
| 154 | match message.role { |
| 155 | ChatRole::User => chat.push(json!({"role": "user", "content": message.text})), |
| 156 | ChatRole::Tool => chat.push(json!({ |
| 157 | "role": "tool", |
| 158 | "tool_call_id": message.tool_call_id, |
| 159 | "content": message.text, |
| 160 | })), |
| 161 | ChatRole::Assistant => { |
| 162 | let mut row = json!({"role": "assistant", "content": message.text}); |
| 163 | if !message.tool_calls.is_empty() { |
| 164 | row["tool_calls"] = Value::Array( |
| 165 | message |
| 166 | .tool_calls |
| 167 | .iter() |
| 168 | .map(|call| { |
| 169 | json!({ |
| 170 | "id": call.id, |
| 171 | "type": "function", |
| 172 | "function": { "name": call.name, "arguments": call.arguments }, |
| 173 | }) |
| 174 | }) |
| 175 | .collect(), |
| 176 | ); |
| 177 | } |
| 178 | chat.push(row); |
| 179 | } |
| 180 | } |
| 181 | } |
| 182 | let mut body = json!({"messages": chat, "stream": false}); |
| 183 | if !tools.is_empty() { |
| 184 | body["tools"] = Value::Array( |
| 185 | tools |
| 186 | .iter() |
| 187 | .map(|tool| { |
| 188 | json!({ |
| 189 | "type": "function", |
| 190 | "function": { |
| 191 | "name": tool.name, |
| 192 | "description": tool.description, |
| 193 | "parameters": tool.parameters, |
| 194 | } |
| 195 | }) |
| 196 | }) |
| 197 | .collect(), |
| 198 | ); |
| 199 | } |
| 200 | body |
| 201 | } |
| 202 | |
| 203 | fn anthropic_body( |
| 204 | profile: &AgentProfile, |
| 205 | system: &str, |
| 206 | messages: &[ChatMessage], |
| 207 | tools: &[ToolSpec], |
| 208 | ) -> Result<Value, String> { |
| 209 | let AgentBackend::Anthropic { model, .. } = &profile.backend else { |
| 210 | return Err("not an Anthropic profile".to_owned()); |
| 211 | }; |
| 212 | let mut chat = Vec::new(); |
| 213 | for message in messages { |
| 214 | match message.role { |
| 215 | ChatRole::User => chat.push(json!({"role": "user", "content": message.text})), |
| 216 | ChatRole::Tool => chat.push(json!({ |
| 217 | "role": "user", |
| 218 | "content": [{ |
| 219 | "type": "tool_result", |
| 220 | "tool_use_id": message.tool_call_id, |
| 221 | "content": message.text, |
| 222 | }] |
| 223 | })), |
| 224 | ChatRole::Assistant => { |
| 225 | let mut content = Vec::new(); |
| 226 | if !message.text.is_empty() { |
| 227 | content.push(json!({"type": "text", "text": message.text})); |
| 228 | } |
| 229 | for call in &message.tool_calls { |
| 230 | let input = serde_json::from_str::<Value>(&call.arguments) |
| 231 | .unwrap_or(Value::Object(Default::default())); |
| 232 | content.push(json!({ |
| 233 | "type": "tool_use", |
| 234 | "id": call.id, |
| 235 | "name": call.name, |
| 236 | "input": input, |
| 237 | })); |
| 238 | } |
| 239 | chat.push(json!({"role": "assistant", "content": content})); |
| 240 | } |
| 241 | } |
| 242 | } |
| 243 | let mut body = json!({ |
| 244 | "model": model, |
| 245 | "max_tokens": MAX_TOKENS, |
| 246 | "messages": chat, |
| 247 | }); |
| 248 | if !system.is_empty() { |
| 249 | body["system"] = Value::String(system.to_owned()); |
| 250 | } |
| 251 | if !tools.is_empty() { |
| 252 | body["tools"] = Value::Array( |
| 253 | tools |
| 254 | .iter() |
| 255 | .map(|tool| { |
| 256 | json!({ |
| 257 | "name": tool.name, |
| 258 | "description": tool.description, |
| 259 | "input_schema": tool.parameters, |
| 260 | }) |
| 261 | }) |
| 262 | .collect(), |
| 263 | ); |
| 264 | } |
| 265 | Ok(body) |
| 266 | } |
| 267 | |
| 268 | fn chat_url(base_url: &str) -> String { |
| 269 | let base = base_url.trim().trim_end_matches('/'); |
| 270 | if base.ends_with("/chat/completions") { |
| 271 | return base.to_owned(); |
| 272 | } |
| 273 | // Ollama answers the OpenAI route only under /v1. The model list also |
| 274 | // accepts the bare port, so a base without /v1 still has to land there. |
| 275 | if base.contains(":11434") { |
| 276 | let origin = base.strip_suffix("/v1").unwrap_or(base); |
| 277 | return format!("{origin}/v1/chat/completions"); |
| 278 | } |
| 279 | format!("{base}/chat/completions") |
| 280 | } |
| 281 | |
| 282 | fn models_url(base_url: &str) -> String { |
| 283 | let base = base_url.trim().trim_end_matches('/'); |
| 284 | if base.contains(":11434") { |
| 285 | let origin = base.trim_end_matches("/v1"); |
| 286 | format!("{origin}/api/tags") |
| 287 | } else { |
| 288 | format!("{base}/models") |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | async fn post(profile: &AgentProfile, body: &Value) -> Result<Value, String> { |
| 293 | let (url, key, anthropic, model) = endpoint(profile)?; |
| 294 | let mut payload = body.clone(); |
| 295 | if !anthropic { |
| 296 | payload["model"] = Value::String(model); |
| 297 | } |
| 298 | let client = client(TURN_TIMEOUT)?; |
| 299 | let mut request = client.post(url).json(&payload); |
| 300 | request = authorize(request, &key, anthropic); |
| 301 | read_json(request).await |
| 302 | } |
| 303 | |
| 304 | async fn get(key: &str, url: &str, anthropic: bool) -> Result<Value, String> { |
| 305 | let client = client(PROBE_TIMEOUT)?; |
| 306 | let request = authorize(client.get(url), key, anthropic); |
| 307 | read_json(request).await |
| 308 | } |
| 309 | |
| 310 | fn endpoint(profile: &AgentProfile) -> Result<(String, String, bool, String), String> { |
| 311 | match &profile.backend { |
| 312 | AgentBackend::OpenAi { |
| 313 | base_url, |
| 314 | model, |
| 315 | api_key, |
| 316 | } => { |
| 317 | if model.trim().is_empty() { |
| 318 | return Err("choose a model first".to_owned()); |
| 319 | } |
| 320 | Ok((chat_url(base_url), api_key.clone(), false, model.clone())) |
| 321 | } |
| 322 | AgentBackend::Anthropic { model, api_key } => { |
| 323 | if api_key.trim().is_empty() { |
| 324 | return Err("the Anthropic key is empty".to_owned()); |
| 325 | } |
| 326 | if model.trim().is_empty() { |
| 327 | return Err("choose a model first".to_owned()); |
| 328 | } |
| 329 | Ok(( |
| 330 | ANTHROPIC_URL.to_owned(), |
| 331 | api_key.clone(), |
| 332 | true, |
| 333 | model.clone(), |
| 334 | )) |
| 335 | } |
| 336 | AgentBackend::Command => Err("this agent is a command".to_owned()), |
| 337 | } |
| 338 | } |
| 339 | |
| 340 | fn client(timeout: std::time::Duration) -> Result<reqwest::Client, String> { |
| 341 | reqwest::Client::builder() |
| 342 | .timeout(timeout) |
| 343 | .build() |
| 344 | .map_err(|error| error.to_string()) |
| 345 | } |
| 346 | |
| 347 | fn authorize( |
| 348 | request: reqwest::RequestBuilder, |
| 349 | key: &str, |
| 350 | anthropic: bool, |
| 351 | ) -> reqwest::RequestBuilder { |
| 352 | if anthropic { |
| 353 | return request |
| 354 | .header("x-api-key", key) |
| 355 | .header("anthropic-version", ANTHROPIC_VERSION); |
| 356 | } |
| 357 | if key.trim().is_empty() { |
| 358 | request |
| 359 | } else { |
| 360 | request.bearer_auth(key) |
| 361 | } |
| 362 | } |
| 363 | |
| 364 | async fn read_json(request: reqwest::RequestBuilder) -> Result<Value, String> { |
| 365 | let response = request.send().await.map_err(|error| error.to_string())?; |
| 366 | let status = response.status(); |
| 367 | let bytes = response.bytes().await.map_err(|error| error.to_string())?; |
| 368 | let value: Value = serde_json::from_slice(&bytes).map_err(|_| { |
| 369 | let body = String::from_utf8_lossy(&bytes); |
| 370 | let snippet: String = body.trim().chars().take(180).collect(); |
| 371 | if snippet.is_empty() { |
| 372 | format!("HTTP {status} with an empty body") |
| 373 | } else { |
| 374 | format!("HTTP {status}: {snippet}") |
| 375 | } |
| 376 | })?; |
| 377 | if !status.is_success() { |
| 378 | return Err(api_error(&value).unwrap_or_else(|| format!("HTTP {status}"))); |
| 379 | } |
| 380 | Ok(value) |
| 381 | } |
| 382 | |
| 383 | fn api_error(value: &Value) -> Option<String> { |
| 384 | value["error"]["message"] |
| 385 | .as_str() |
| 386 | .or_else(|| value["error"].as_str()) |
| 387 | .map(str::to_owned) |
| 388 | } |
| 389 | |
| 390 | pub(crate) fn parse_openai(value: &Value) -> Result<ChatReply, String> { |
| 391 | if let Some(message) = api_error(value) { |
| 392 | return Err(message); |
| 393 | } |
| 394 | let message = &value["choices"][0]["message"]; |
| 395 | let text = message["content"].as_str().unwrap_or("").trim().to_owned(); |
| 396 | let calls = message["tool_calls"] |
| 397 | .as_array() |
| 398 | .map(|calls| { |
| 399 | calls |
| 400 | .iter() |
| 401 | .filter_map(|call| { |
| 402 | let name = call["function"]["name"].as_str()?; |
| 403 | let arguments = call["function"]["arguments"].as_str().unwrap_or("{}"); |
| 404 | Some(ToolCall { |
| 405 | id: call["id"].as_str().unwrap_or(name).to_owned(), |
| 406 | name: name.to_owned(), |
| 407 | arguments: arguments.to_owned(), |
| 408 | }) |
| 409 | }) |
| 410 | .collect::<Vec<_>>() |
| 411 | }) |
| 412 | .unwrap_or_default(); |
| 413 | if calls.is_empty() { |
| 414 | if text.is_empty() { |
| 415 | return Err("the model returned an empty answer".to_owned()); |
| 416 | } |
| 417 | Ok(ChatReply::Text(text)) |
| 418 | } else { |
| 419 | Ok(ChatReply::Tools { text, calls }) |
| 420 | } |
| 421 | } |
| 422 | |
| 423 | pub(crate) fn parse_anthropic(value: &Value) -> Result<ChatReply, String> { |
| 424 | if let Some(message) = api_error(value) { |
| 425 | return Err(message); |
| 426 | } |
| 427 | let mut text = String::new(); |
| 428 | let mut calls = Vec::new(); |
| 429 | for block in value["content"].as_array().into_iter().flatten() { |
| 430 | match block["type"].as_str() { |
| 431 | Some("text") => { |
| 432 | if !text.is_empty() { |
| 433 | text.push('\n'); |
| 434 | } |
| 435 | text.push_str(block["text"].as_str().unwrap_or("")); |
| 436 | } |
| 437 | Some("tool_use") => { |
| 438 | let name = block["name"].as_str().unwrap_or(""); |
| 439 | if name.is_empty() { |
| 440 | continue; |
| 441 | } |
| 442 | let input = &block["input"]; |
| 443 | calls.push(ToolCall { |
| 444 | id: block["id"].as_str().unwrap_or(name).to_owned(), |
| 445 | name: name.to_owned(), |
| 446 | arguments: input.to_string(), |
| 447 | }); |
| 448 | } |
| 449 | _ => {} |
| 450 | } |
| 451 | } |
| 452 | let text = text.trim().to_owned(); |
| 453 | if calls.is_empty() { |
| 454 | if text.is_empty() { |
| 455 | return Err("the model returned an empty answer".to_owned()); |
| 456 | } |
| 457 | Ok(ChatReply::Text(text)) |
| 458 | } else { |
| 459 | Ok(ChatReply::Tools { text, calls }) |
| 460 | } |
| 461 | } |
| 462 | |
| 463 | fn model_names(value: &Value) -> Vec<String> { |
| 464 | let list = value["models"] |
| 465 | .as_array() |
| 466 | .or_else(|| value["data"].as_array()); |
| 467 | list.map(|models| { |
| 468 | models |
| 469 | .iter() |
| 470 | .filter_map(|model| { |
| 471 | model["name"] |
| 472 | .as_str() |
| 473 | .or_else(|| model["id"].as_str()) |
| 474 | .map(str::to_owned) |
| 475 | }) |
| 476 | .collect() |
| 477 | }) |
| 478 | .unwrap_or_default() |
| 479 | } |
| 480 | |
| 481 | #[cfg(test)] |
| 482 | mod tests { |
| 483 | use super::*; |
| 484 | |
| 485 | #[test] |
| 486 | fn openai_text_and_tool_calls_parse() { |
| 487 | let text = parse_openai(&json!({ |
| 488 | "choices": [{"message": {"content": " hello "}}] |
| 489 | })) |
| 490 | .unwrap(); |
| 491 | assert_eq!(text, ChatReply::Text("hello".to_owned())); |
| 492 | let tools = parse_openai(&json!({ |
| 493 | "choices": [{"message": { |
| 494 | "content": "", |
| 495 | "tool_calls": [{ |
| 496 | "id": "c1", |
| 497 | "function": {"name": "propose_message", "arguments": "{\"text\":\"hi\"}"} |
| 498 | }] |
| 499 | }}] |
| 500 | })) |
| 501 | .unwrap(); |
| 502 | assert_eq!( |
| 503 | tools, |
| 504 | ChatReply::Tools { |
| 505 | text: String::new(), |
| 506 | calls: vec![ToolCall { |
| 507 | id: "c1".to_owned(), |
| 508 | name: "propose_message".to_owned(), |
| 509 | arguments: "{\"text\":\"hi\"}".to_owned(), |
| 510 | }], |
| 511 | } |
| 512 | ); |
| 513 | } |
| 514 | |
| 515 | #[test] |
| 516 | fn anthropic_text_and_tool_use_parse() { |
| 517 | let text = parse_anthropic(&json!({ |
| 518 | "content": [{"type": "text", "text": "done"}] |
| 519 | })) |
| 520 | .unwrap(); |
| 521 | assert_eq!(text, ChatReply::Text("done".to_owned())); |
| 522 | let tools = parse_anthropic(&json!({ |
| 523 | "content": [ |
| 524 | {"type": "text", "text": "looking"}, |
| 525 | {"type": "tool_use", "id": "t1", "name": "list_chats", "input": {"limit": 1}} |
| 526 | ] |
| 527 | })) |
| 528 | .unwrap(); |
| 529 | match tools { |
| 530 | ChatReply::Tools { text, calls } => { |
| 531 | assert_eq!(text, "looking"); |
| 532 | assert_eq!(calls[0].name, "list_chats"); |
| 533 | assert_eq!(calls[0].arguments, "{\"limit\":1}"); |
| 534 | } |
| 535 | other => panic!("{other:?}"), |
| 536 | } |
| 537 | } |
| 538 | |
| 539 | #[test] |
| 540 | fn model_lists_keep_ollama_names_and_openai_ids() { |
| 541 | let ollama = model_names(&json!({ |
| 542 | "models": [{"name": "llama3.2:latest"}, {"name": "qwen2.5:7b"}] |
| 543 | })); |
| 544 | assert_eq!(ollama, ["llama3.2:latest", "qwen2.5:7b"]); |
| 545 | let openai = model_names(&json!({"data": [{"id": "gpt-4o"}, {"id": "gpt-4o-mini"}]})); |
| 546 | assert_eq!(openai, ["gpt-4o", "gpt-4o-mini"]); |
| 547 | let many = model_names(&json!({ |
| 548 | "data": (0..12).map(|index| json!({"id": format!("m{index}")})).collect::<Vec<_>>() |
| 549 | })); |
| 550 | assert_eq!(many.len(), 12); |
| 551 | } |
| 552 | |
| 553 | #[test] |
| 554 | fn ollama_models_use_the_native_tags_path() { |
| 555 | assert_eq!( |
| 556 | models_url("http://127.0.0.1:11434/v1"), |
| 557 | "http://127.0.0.1:11434/api/tags" |
| 558 | ); |
| 559 | assert_eq!( |
| 560 | chat_url("http://127.0.0.1:11434/v1"), |
| 561 | "http://127.0.0.1:11434/v1/chat/completions" |
| 562 | ); |
| 563 | assert_eq!( |
| 564 | chat_url("http://mac-01.lan:11434"), |
| 565 | "http://mac-01.lan:11434/v1/chat/completions" |
| 566 | ); |
| 567 | } |
| 568 | } |