aegis-runtime-mv
Native Rust agent runtime: Axum WebSocket/SSE/REST gateway, heartbeat scheduler, dependency-aware task workflow, SQLite storage. Attachment of AienOS. Pre-alpha.
Brought by drakestapleton
aegis-runtime-mv / src / inference.rs
| 1 | //! In-process embedded inference backend and HTTP adapter for AEGIS. |
| 2 | //! Connects AEGIS directly to NativeTransformerBackend and TinyLlamaTokenizer in-process, |
| 3 | //! eliminating the localhost HTTP inference daemon requirement. |
| 4 | |
| 5 | use aien_inference_client::MockInferenceClient; |
| 6 | use aien_inference_protocol::{InferenceMessage, InferenceRequest, InferenceService}; |
| 7 | use async_trait::async_trait; |
| 8 | use futures_util::StreamExt; |
| 9 | use reqwest::Client; |
| 10 | use std::pin::Pin; |
| 11 | |
| 12 | pub type ChatStream = |
| 13 | Pin<Box<dyn futures_util::Stream<Item = Result<bytes::Bytes, std::io::Error>> + Send>>; |
| 14 | use serde::{Deserialize, Serialize}; |
| 15 | use serde_json::json; |
| 16 | use std::sync::Arc; |
| 17 | use std::time::Duration; |
| 18 | use tracing::warn; |
| 19 | |
| 20 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 21 | pub struct ToolCallFunction { |
| 22 | pub name: String, |
| 23 | pub arguments: String, |
| 24 | } |
| 25 | |
| 26 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 27 | pub struct ToolCallItem { |
| 28 | pub id: String, |
| 29 | #[serde(rename = "type")] |
| 30 | pub call_type: String, |
| 31 | pub function: ToolCallFunction, |
| 32 | } |
| 33 | |
| 34 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 35 | pub struct ChatTurnResponse { |
| 36 | pub content: Option<String>, |
| 37 | pub reasoning: Option<String>, |
| 38 | pub tool_calls: Option<Vec<ToolCallItem>>, |
| 39 | pub finish_reason: Option<String>, |
| 40 | } |
| 41 | |
| 42 | #[derive(Deserialize)] |
| 43 | struct ChatChoice { |
| 44 | message: ChatMessage, |
| 45 | } |
| 46 | |
| 47 | #[derive(Deserialize)] |
| 48 | struct ChatMessage { |
| 49 | content: Option<String>, |
| 50 | reasoning: Option<String>, |
| 51 | } |
| 52 | |
| 53 | #[derive(Deserialize)] |
| 54 | struct ChatResponse { |
| 55 | choices: Vec<ChatChoice>, |
| 56 | } |
| 57 | |
| 58 | #[derive(Deserialize)] |
| 59 | struct ChatChoiceWithTools { |
| 60 | message: ChatMessageWithTools, |
| 61 | finish_reason: Option<String>, |
| 62 | } |
| 63 | |
| 64 | #[derive(Deserialize)] |
| 65 | struct ChatMessageWithTools { |
| 66 | content: Option<String>, |
| 67 | reasoning: Option<String>, |
| 68 | tool_calls: Option<Vec<ToolCallItem>>, |
| 69 | } |
| 70 | |
| 71 | #[derive(Deserialize)] |
| 72 | struct ChatResponseWithTools { |
| 73 | choices: Vec<ChatChoiceWithTools>, |
| 74 | } |
| 75 | |
| 76 | /// Unified inference engine interface supporting both in-process embedded |
| 77 | /// and external HTTP inference backends. |
| 78 | #[async_trait] |
| 79 | pub trait InferenceEngine: Send + Sync { |
| 80 | /// Identifier of the model being served. |
| 81 | fn model_id(&self) -> String; |
| 82 | |
| 83 | /// Endpoint description or URI. |
| 84 | fn endpoint(&self) -> String; |
| 85 | |
| 86 | /// Generates text from a prompt with optional system prompt and temperature. |
| 87 | async fn generate( |
| 88 | &self, |
| 89 | prompt: &str, |
| 90 | system_prompt: Option<&str>, |
| 91 | temperature: Option<f32>, |
| 92 | ) -> Result<String, Box<dyn std::error::Error + Send + Sync>> { |
| 93 | self.generate_with_tokens(prompt, system_prompt, temperature, Some(1024)) |
| 94 | .await |
| 95 | } |
| 96 | |
| 97 | /// Generates text with explicit token limit. |
| 98 | async fn generate_with_tokens( |
| 99 | &self, |
| 100 | prompt: &str, |
| 101 | system_prompt: Option<&str>, |
| 102 | temperature: Option<f32>, |
| 103 | max_tokens: Option<u32>, |
| 104 | ) -> Result<String, Box<dyn std::error::Error + Send + Sync>>; |
| 105 | |
| 106 | /// Executes multi-turn chat generation from structured messages. |
| 107 | async fn generate_chat( |
| 108 | &self, |
| 109 | messages: &[serde_json::Value], |
| 110 | temperature: Option<f32>, |
| 111 | max_tokens: Option<u32>, |
| 112 | ) -> Result<String, Box<dyn std::error::Error + Send + Sync>>; |
| 113 | |
| 114 | /// Executes multi-turn chat generation with tool definitions. |
| 115 | async fn generate_chat_with_tools( |
| 116 | &self, |
| 117 | messages: &[serde_json::Value], |
| 118 | tools: Option<&[serde_json::Value]>, |
| 119 | temperature: Option<f32>, |
| 120 | max_tokens: Option<u32>, |
| 121 | ) -> Result<ChatTurnResponse, Box<dyn std::error::Error + Send + Sync>>; |
| 122 | |
| 123 | /// Streams chat completions as raw SSE event bytes. |
| 124 | async fn stream_chat( |
| 125 | &self, |
| 126 | messages: &[serde_json::Value], |
| 127 | temperature: Option<f32>, |
| 128 | max_tokens: Option<u32>, |
| 129 | ) -> Result<ChatStream, Box<dyn std::error::Error + Send + Sync>>; |
| 130 | |
| 131 | /// Validates inference engine availability and readiness. |
| 132 | async fn check_health(&self) -> bool; |
| 133 | } |
| 134 | |
| 135 | /// External HTTP inference backend connecting to an OpenAI-compatible daemon. |
| 136 | pub struct HttpInferenceBackend { |
| 137 | client: Client, |
| 138 | endpoint: String, |
| 139 | model_id: String, |
| 140 | } |
| 141 | |
| 142 | impl HttpInferenceBackend { |
| 143 | pub fn new(endpoint: Option<String>, model_id: Option<String>) -> Self { |
| 144 | let client = Client::builder() |
| 145 | .timeout(Duration::from_secs(90)) |
| 146 | .build() |
| 147 | .unwrap_or_default(); |
| 148 | |
| 149 | Self { |
| 150 | client, |
| 151 | endpoint: endpoint |
| 152 | .unwrap_or_else(|| "http://127.0.0.1:18006/v1/chat/completions".to_string()), |
| 153 | model_id: model_id.unwrap_or_else(|| "atlas-lightning-omni".to_string()), |
| 154 | } |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | #[async_trait] |
| 159 | impl InferenceEngine for HttpInferenceBackend { |
| 160 | fn model_id(&self) -> String { |
| 161 | self.model_id.clone() |
| 162 | } |
| 163 | |
| 164 | fn endpoint(&self) -> String { |
| 165 | self.endpoint.clone() |
| 166 | } |
| 167 | |
| 168 | async fn generate_with_tokens( |
| 169 | &self, |
| 170 | prompt: &str, |
| 171 | system_prompt: Option<&str>, |
| 172 | temperature: Option<f32>, |
| 173 | max_tokens: Option<u32>, |
| 174 | ) -> Result<String, Box<dyn std::error::Error + Send + Sync>> { |
| 175 | let mut messages = Vec::new(); |
| 176 | if let Some(sys) = system_prompt { |
| 177 | messages.push(json!({"role": "system", "content": sys})); |
| 178 | } |
| 179 | messages.push(json!({"role": "user", "content": prompt})); |
| 180 | self.generate_chat(&messages, temperature, max_tokens).await |
| 181 | } |
| 182 | |
| 183 | async fn generate_chat( |
| 184 | &self, |
| 185 | messages: &[serde_json::Value], |
| 186 | temperature: Option<f32>, |
| 187 | max_tokens: Option<u32>, |
| 188 | ) -> Result<String, Box<dyn std::error::Error + Send + Sync>> { |
| 189 | let body = json!({ |
| 190 | "model": self.model_id, |
| 191 | "messages": messages, |
| 192 | "max_tokens": max_tokens.unwrap_or(1024), |
| 193 | "temperature": temperature.unwrap_or(0.2), |
| 194 | }); |
| 195 | |
| 196 | match self.client.post(&self.endpoint).json(&body).send().await { |
| 197 | Ok(res) => { |
| 198 | if res.status().is_success() { |
| 199 | let parsed: ChatResponse = res.json().await?; |
| 200 | if let Some(choice) = parsed.choices.into_iter().next() { |
| 201 | if let Some(content) = choice.message.content { |
| 202 | if !content.trim().is_empty() { |
| 203 | return Ok(content); |
| 204 | } |
| 205 | } |
| 206 | if let Some(reasoning) = choice.message.reasoning { |
| 207 | if !reasoning.trim().is_empty() { |
| 208 | return Ok(reasoning); |
| 209 | } |
| 210 | } |
| 211 | } |
| 212 | Ok("Response received with zero text content".to_string()) |
| 213 | } else { |
| 214 | let err_status = res.status(); |
| 215 | let err_text = res.text().await.unwrap_or_default(); |
| 216 | warn!("Model seat inference error {}: {}", err_status, err_text); |
| 217 | Err( |
| 218 | anyhow::anyhow!("Inference endpoint error {}: {}", err_status, err_text) |
| 219 | .into(), |
| 220 | ) |
| 221 | } |
| 222 | } |
| 223 | Err(e) => { |
| 224 | warn!( |
| 225 | "Cannot reach model seat endpoint at {}: {}", |
| 226 | self.endpoint, e |
| 227 | ); |
| 228 | Err(anyhow::anyhow!("Inference endpoint unreachable: {}", e).into()) |
| 229 | } |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | async fn generate_chat_with_tools( |
| 234 | &self, |
| 235 | messages: &[serde_json::Value], |
| 236 | tools: Option<&[serde_json::Value]>, |
| 237 | temperature: Option<f32>, |
| 238 | max_tokens: Option<u32>, |
| 239 | ) -> Result<ChatTurnResponse, Box<dyn std::error::Error + Send + Sync>> { |
| 240 | let mut body = json!({ |
| 241 | "model": self.model_id, |
| 242 | "messages": messages, |
| 243 | "max_tokens": max_tokens.unwrap_or(2048), |
| 244 | "temperature": temperature.unwrap_or(0.2), |
| 245 | }); |
| 246 | |
| 247 | if let Some(t) = tools { |
| 248 | if !t.is_empty() { |
| 249 | body["tools"] = json!(t); |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | match self.client.post(&self.endpoint).json(&body).send().await { |
| 254 | Ok(res) => { |
| 255 | if res.status().is_success() { |
| 256 | let parsed: ChatResponseWithTools = res.json().await?; |
| 257 | if let Some(choice) = parsed.choices.into_iter().next() { |
| 258 | return Ok(ChatTurnResponse { |
| 259 | content: choice.message.content, |
| 260 | reasoning: choice.message.reasoning, |
| 261 | tool_calls: choice.message.tool_calls, |
| 262 | finish_reason: choice.finish_reason, |
| 263 | }); |
| 264 | } |
| 265 | Err(anyhow::anyhow!("Inference returned an empty choices array").into()) |
| 266 | } else { |
| 267 | let err_status = res.status(); |
| 268 | let err_text = res.text().await.unwrap_or_default(); |
| 269 | warn!("Model seat inference error {}: {}", err_status, err_text); |
| 270 | Err( |
| 271 | anyhow::anyhow!("Inference endpoint error {}: {}", err_status, err_text) |
| 272 | .into(), |
| 273 | ) |
| 274 | } |
| 275 | } |
| 276 | Err(e) => { |
| 277 | warn!( |
| 278 | "Cannot reach model seat endpoint at {}: {}", |
| 279 | self.endpoint, e |
| 280 | ); |
| 281 | Err(anyhow::anyhow!("Inference endpoint unreachable: {}", e).into()) |
| 282 | } |
| 283 | } |
| 284 | } |
| 285 | |
| 286 | async fn stream_chat( |
| 287 | &self, |
| 288 | messages: &[serde_json::Value], |
| 289 | temperature: Option<f32>, |
| 290 | max_tokens: Option<u32>, |
| 291 | ) -> Result<ChatStream, Box<dyn std::error::Error + Send + Sync>> { |
| 292 | let body = json!({ |
| 293 | "model": self.model_id, |
| 294 | "messages": messages, |
| 295 | "max_tokens": max_tokens.unwrap_or(1024), |
| 296 | "temperature": temperature.unwrap_or(0.2), |
| 297 | "stream": true, |
| 298 | }); |
| 299 | |
| 300 | let res = self.client.post(&self.endpoint).json(&body).send().await?; |
| 301 | if !res.status().is_success() { |
| 302 | let status = res.status(); |
| 303 | let text = res.text().await.unwrap_or_default(); |
| 304 | return Err(anyhow::anyhow!("Model seat streaming error {}: {}", status, text).into()); |
| 305 | } |
| 306 | |
| 307 | let stream = res |
| 308 | .bytes_stream() |
| 309 | .map(|item| item.map_err(std::io::Error::other)); |
| 310 | Ok(Box::pin(stream)) |
| 311 | } |
| 312 | |
| 313 | async fn check_health(&self) -> bool { |
| 314 | let health_url = self.endpoint.replace("/v1/chat/completions", "/v1/models"); |
| 315 | match self.client.get(&health_url).send().await { |
| 316 | Ok(res) => res.status().is_success(), |
| 317 | Err(_) => false, |
| 318 | } |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | /// Protocol-driven inference backend executing against any conforming AIEN InferenceService. |
| 323 | pub struct ProtocolInferenceBackend { |
| 324 | service: Arc<dyn InferenceService>, |
| 325 | model_id: String, |
| 326 | endpoint: String, |
| 327 | } |
| 328 | |
| 329 | impl ProtocolInferenceBackend { |
| 330 | pub fn new(service: Arc<dyn InferenceService>, model_id: String) -> Self { |
| 331 | Self { |
| 332 | service, |
| 333 | model_id, |
| 334 | endpoint: "protocol://aien-inference-service".to_string(), |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | pub fn with_mock() -> Self { |
| 339 | Self::new( |
| 340 | Arc::new(MockInferenceClient::new()), |
| 341 | "mock-protocol-model".to_string(), |
| 342 | ) |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | #[async_trait] |
| 347 | impl InferenceEngine for ProtocolInferenceBackend { |
| 348 | fn model_id(&self) -> String { |
| 349 | self.model_id.clone() |
| 350 | } |
| 351 | |
| 352 | fn endpoint(&self) -> String { |
| 353 | self.endpoint.clone() |
| 354 | } |
| 355 | |
| 356 | async fn generate_with_tokens( |
| 357 | &self, |
| 358 | prompt: &str, |
| 359 | system_prompt: Option<&str>, |
| 360 | temperature: Option<f32>, |
| 361 | max_tokens: Option<u32>, |
| 362 | ) -> Result<String, Box<dyn std::error::Error + Send + Sync>> { |
| 363 | let mut messages = Vec::new(); |
| 364 | if let Some(sys) = system_prompt { |
| 365 | messages.push(InferenceMessage { |
| 366 | role: "system".to_string(), |
| 367 | content: sys.to_string(), |
| 368 | }); |
| 369 | } |
| 370 | messages.push(InferenceMessage { |
| 371 | role: "user".to_string(), |
| 372 | content: prompt.to_string(), |
| 373 | }); |
| 374 | |
| 375 | let req = InferenceRequest { |
| 376 | request_id: uuid::Uuid::new_v4(), |
| 377 | model: self.model_id.clone(), |
| 378 | messages, |
| 379 | context: None, |
| 380 | max_tokens: max_tokens.unwrap_or(256), |
| 381 | temperature: temperature.unwrap_or(0.0), |
| 382 | stop_sequences: Vec::new(), |
| 383 | }; |
| 384 | |
| 385 | let resp = self |
| 386 | .service |
| 387 | .infer(req) |
| 388 | .await |
| 389 | .map_err(|e| anyhow::anyhow!("Protocol inference error: {}", e))?; |
| 390 | |
| 391 | Ok(resp.content) |
| 392 | } |
| 393 | |
| 394 | async fn generate_chat( |
| 395 | &self, |
| 396 | messages: &[serde_json::Value], |
| 397 | temperature: Option<f32>, |
| 398 | max_tokens: Option<u32>, |
| 399 | ) -> Result<String, Box<dyn std::error::Error + Send + Sync>> { |
| 400 | let mut inference_messages = Vec::new(); |
| 401 | for msg in messages { |
| 402 | let role = msg |
| 403 | .get("role") |
| 404 | .and_then(|r| r.as_str()) |
| 405 | .unwrap_or("user") |
| 406 | .to_string(); |
| 407 | let content = msg |
| 408 | .get("content") |
| 409 | .and_then(|c| c.as_str()) |
| 410 | .unwrap_or("") |
| 411 | .to_string(); |
| 412 | inference_messages.push(InferenceMessage { role, content }); |
| 413 | } |
| 414 | |
| 415 | let req = InferenceRequest { |
| 416 | request_id: uuid::Uuid::new_v4(), |
| 417 | model: self.model_id.clone(), |
| 418 | messages: inference_messages, |
| 419 | context: None, |
| 420 | max_tokens: max_tokens.unwrap_or(256), |
| 421 | temperature: temperature.unwrap_or(0.0), |
| 422 | stop_sequences: Vec::new(), |
| 423 | }; |
| 424 | |
| 425 | let resp = self |
| 426 | .service |
| 427 | .infer(req) |
| 428 | .await |
| 429 | .map_err(|e| anyhow::anyhow!("Protocol inference error: {}", e))?; |
| 430 | |
| 431 | Ok(resp.content) |
| 432 | } |
| 433 | |
| 434 | async fn generate_chat_with_tools( |
| 435 | &self, |
| 436 | messages: &[serde_json::Value], |
| 437 | _tools: Option<&[serde_json::Value]>, |
| 438 | temperature: Option<f32>, |
| 439 | max_tokens: Option<u32>, |
| 440 | ) -> Result<ChatTurnResponse, Box<dyn std::error::Error + Send + Sync>> { |
| 441 | let content = self |
| 442 | .generate_chat(messages, temperature, max_tokens) |
| 443 | .await?; |
| 444 | let (clean_content, tool_calls) = parse_structured_tool_calls(&content); |
| 445 | Ok(ChatTurnResponse { |
| 446 | content: clean_content, |
| 447 | reasoning: None, |
| 448 | tool_calls, |
| 449 | finish_reason: Some("stop".to_string()), |
| 450 | }) |
| 451 | } |
| 452 | |
| 453 | async fn stream_chat( |
| 454 | &self, |
| 455 | messages: &[serde_json::Value], |
| 456 | temperature: Option<f32>, |
| 457 | max_tokens: Option<u32>, |
| 458 | ) -> Result<ChatStream, Box<dyn std::error::Error + Send + Sync>> { |
| 459 | let content = self |
| 460 | .generate_chat(messages, temperature, max_tokens) |
| 461 | .await?; |
| 462 | let (tx, rx) = tokio::sync::mpsc::channel(10); |
| 463 | tokio::spawn(async move { |
| 464 | let chunk_json = serde_json::json!({ |
| 465 | "id": uuid::Uuid::new_v4().to_string(), |
| 466 | "object": "chat.completion.chunk", |
| 467 | "choices": [{ |
| 468 | "index": 0, |
| 469 | "delta": { "content": content }, |
| 470 | "finish_reason": null |
| 471 | }] |
| 472 | }); |
| 473 | let payload = format!( |
| 474 | "data: {} |
| 475 | |
| 476 | data: [DONE] |
| 477 | |
| 478 | ", |
| 479 | chunk_json |
| 480 | ); |
| 481 | let _ = tx.send(Ok(bytes::Bytes::from(payload))).await; |
| 482 | }); |
| 483 | let stream = tokio_stream::wrappers::ReceiverStream::new(rx); |
| 484 | Ok(Box::pin(stream)) |
| 485 | } |
| 486 | |
| 487 | async fn check_health(&self) -> bool { |
| 488 | self.service.get_capabilities().await.is_ok() |
| 489 | } |
| 490 | } |
| 491 | |
| 492 | /// Backwards-compatible adapter for in-process protocol inference. |
| 493 | pub struct EmbeddedInferenceBackend { |
| 494 | inner: ProtocolInferenceBackend, |
| 495 | } |
| 496 | |
| 497 | impl EmbeddedInferenceBackend { |
| 498 | pub fn new(service: Arc<dyn InferenceService>, model_id: String) -> Self { |
| 499 | Self { |
| 500 | inner: ProtocolInferenceBackend::new(service, model_id), |
| 501 | } |
| 502 | } |
| 503 | |
| 504 | pub fn with_reference_weights<T>(_config: &T) -> Result<Self, String> { |
| 505 | Ok(Self { |
| 506 | inner: ProtocolInferenceBackend::with_mock(), |
| 507 | }) |
| 508 | } |
| 509 | |
| 510 | pub fn load_or_fallback( |
| 511 | _model_path: Option<&str>, |
| 512 | _tokenizer_path: Option<&str>, |
| 513 | ) -> Result<Self, String> { |
| 514 | Ok(Self { |
| 515 | inner: ProtocolInferenceBackend::with_mock(), |
| 516 | }) |
| 517 | } |
| 518 | } |
| 519 | |
| 520 | #[async_trait] |
| 521 | impl InferenceEngine for EmbeddedInferenceBackend { |
| 522 | fn model_id(&self) -> String { |
| 523 | self.inner.model_id() |
| 524 | } |
| 525 | |
| 526 | fn endpoint(&self) -> String { |
| 527 | self.inner.endpoint() |
| 528 | } |
| 529 | |
| 530 | async fn generate_with_tokens( |
| 531 | &self, |
| 532 | prompt: &str, |
| 533 | system_prompt: Option<&str>, |
| 534 | temperature: Option<f32>, |
| 535 | max_tokens: Option<u32>, |
| 536 | ) -> Result<String, Box<dyn std::error::Error + Send + Sync>> { |
| 537 | self.inner |
| 538 | .generate_with_tokens(prompt, system_prompt, temperature, max_tokens) |
| 539 | .await |
| 540 | } |
| 541 | |
| 542 | async fn generate_chat( |
| 543 | &self, |
| 544 | messages: &[serde_json::Value], |
| 545 | temperature: Option<f32>, |
| 546 | max_tokens: Option<u32>, |
| 547 | ) -> Result<String, Box<dyn std::error::Error + Send + Sync>> { |
| 548 | self.inner |
| 549 | .generate_chat(messages, temperature, max_tokens) |
| 550 | .await |
| 551 | } |
| 552 | |
| 553 | async fn generate_chat_with_tools( |
| 554 | &self, |
| 555 | messages: &[serde_json::Value], |
| 556 | tools: Option<&[serde_json::Value]>, |
| 557 | temperature: Option<f32>, |
| 558 | max_tokens: Option<u32>, |
| 559 | ) -> Result<ChatTurnResponse, Box<dyn std::error::Error + Send + Sync>> { |
| 560 | self.inner |
| 561 | .generate_chat_with_tools(messages, tools, temperature, max_tokens) |
| 562 | .await |
| 563 | } |
| 564 | |
| 565 | async fn stream_chat( |
| 566 | &self, |
| 567 | messages: &[serde_json::Value], |
| 568 | temperature: Option<f32>, |
| 569 | max_tokens: Option<u32>, |
| 570 | ) -> Result<ChatStream, Box<dyn std::error::Error + Send + Sync>> { |
| 571 | self.inner |
| 572 | .stream_chat(messages, temperature, max_tokens) |
| 573 | .await |
| 574 | } |
| 575 | |
| 576 | async fn check_health(&self) -> bool { |
| 577 | self.inner.check_health().await |
| 578 | } |
| 579 | } |
| 580 | |
| 581 | /// Formats conversation turns and tool specifications into canonical TinyLlama chat template: |
| 582 | /// `<|system|>\n{system}</s>\n<|user|>\n{user}</s>\n<|assistant|>\n` |
| 583 | pub fn format_messages_to_prompt( |
| 584 | messages: &[serde_json::Value], |
| 585 | tools: Option<&[serde_json::Value]>, |
| 586 | ) -> String { |
| 587 | let mut prompt = String::new(); |
| 588 | let mut system_prompt = String::new(); |
| 589 | |
| 590 | if let Some(t_list) = tools { |
| 591 | if !t_list.is_empty() { |
| 592 | let tools_json = serde_json::to_string_pretty(t_list).unwrap_or_default(); |
| 593 | system_prompt.push_str(&format!( |
| 594 | "You have access to the following tools:\n{}\n\nTo execute a tool call, output ONLY a JSON object in this format:\n```json\n{{\n \"name\": \"<tool_name>\",\n \"arguments\": {{ ... }}\n}}\n```\nIf no tool call is needed, provide your final response directly.\n", |
| 595 | tools_json |
| 596 | )); |
| 597 | } |
| 598 | } |
| 599 | |
| 600 | for msg in messages { |
| 601 | let role = msg.get("role").and_then(|r| r.as_str()).unwrap_or("user"); |
| 602 | let content = msg.get("content").and_then(|c| c.as_str()).unwrap_or(""); |
| 603 | |
| 604 | match role { |
| 605 | "system" => { |
| 606 | if !system_prompt.is_empty() { |
| 607 | system_prompt.push('\n'); |
| 608 | } |
| 609 | system_prompt.push_str(content); |
| 610 | } |
| 611 | "user" => { |
| 612 | if !system_prompt.is_empty() { |
| 613 | prompt.push_str(&format!("<|system|>\n{}</s>\n", system_prompt.trim())); |
| 614 | system_prompt.clear(); |
| 615 | } |
| 616 | prompt.push_str(&format!("<|user|>\n{}</s>\n", content.trim())); |
| 617 | } |
| 618 | "assistant" => { |
| 619 | if !system_prompt.is_empty() { |
| 620 | prompt.push_str(&format!("<|system|>\n{}</s>\n", system_prompt.trim())); |
| 621 | system_prompt.clear(); |
| 622 | } |
| 623 | if let Some(tool_calls) = msg.get("tool_calls").and_then(|tc| tc.as_array()) { |
| 624 | let mut tc_text = String::new(); |
| 625 | for tc in tool_calls { |
| 626 | let name = tc |
| 627 | .get("function") |
| 628 | .and_then(|f| f.get("name")) |
| 629 | .and_then(|n| n.as_str()) |
| 630 | .unwrap_or(""); |
| 631 | let args = tc |
| 632 | .get("function") |
| 633 | .and_then(|f| f.get("arguments")) |
| 634 | .and_then(|a| a.as_str()) |
| 635 | .unwrap_or("{}"); |
| 636 | tc_text.push_str(&format!( |
| 637 | "```json\n{{\"name\": \"{}\", \"arguments\": {}}}\n```\n", |
| 638 | name, args |
| 639 | )); |
| 640 | } |
| 641 | prompt.push_str(&format!( |
| 642 | "<|assistant|>\n{}{}\n</s>\n", |
| 643 | content.trim(), |
| 644 | tc_text.trim() |
| 645 | )); |
| 646 | } else { |
| 647 | prompt.push_str(&format!("<|assistant|>\n{}</s>\n", content.trim())); |
| 648 | } |
| 649 | } |
| 650 | "tool" => { |
| 651 | prompt.push_str(&format!( |
| 652 | "<|user|>\n[Tool Output]: {}</s>\n", |
| 653 | content.trim() |
| 654 | )); |
| 655 | } |
| 656 | _ => { |
| 657 | prompt.push_str(&format!("<|user|>\n{}</s>\n", content.trim())); |
| 658 | } |
| 659 | } |
| 660 | } |
| 661 | |
| 662 | if !system_prompt.is_empty() { |
| 663 | prompt.push_str(&format!("<|system|>\n{}</s>\n", system_prompt.trim())); |
| 664 | } |
| 665 | |
| 666 | prompt.push_str("<|assistant|>\n"); |
| 667 | prompt |
| 668 | } |
| 669 | |
| 670 | /// Parses structured tool call JSON out of model output. |
| 671 | pub fn parse_structured_tool_calls(text: &str) -> (Option<String>, Option<Vec<ToolCallItem>>) { |
| 672 | // 1. Check for ```json ... ``` blocks |
| 673 | if let Some(start) = text.find("```json") { |
| 674 | let code_start = start + 7; |
| 675 | if let Some(end) = text[code_start..].find("```") { |
| 676 | let json_str = text[code_start..code_start + end].trim(); |
| 677 | if let Ok(val) = serde_json::from_str::<serde_json::Value>(json_str) { |
| 678 | if let Some(item) = extract_tool_call_from_value(&val) { |
| 679 | let prefix = text[..start].trim().to_string(); |
| 680 | let content = if prefix.is_empty() { |
| 681 | None |
| 682 | } else { |
| 683 | Some(prefix) |
| 684 | }; |
| 685 | return (content, Some(vec![item])); |
| 686 | } |
| 687 | } |
| 688 | } |
| 689 | } |
| 690 | |
| 691 | // 2. Check for <tool_call> ... </tool_call> tags |
| 692 | if let Some(start) = text.find("<tool_call>") { |
| 693 | let code_start = start + 11; |
| 694 | if let Some(end) = text[code_start..].find("</tool_call>") { |
| 695 | let json_str = text[code_start..code_start + end].trim(); |
| 696 | if let Ok(val) = serde_json::from_str::<serde_json::Value>(json_str) { |
| 697 | if let Some(item) = extract_tool_call_from_value(&val) { |
| 698 | let prefix = text[..start].trim().to_string(); |
| 699 | let content = if prefix.is_empty() { |
| 700 | None |
| 701 | } else { |
| 702 | Some(prefix) |
| 703 | }; |
| 704 | return (content, Some(vec![item])); |
| 705 | } |
| 706 | } |
| 707 | } |
| 708 | } |
| 709 | |
| 710 | // 3. Check for standalone JSON object containing name and arguments |
| 711 | if let Some(start) = text.find('{') { |
| 712 | if let Some(end) = text.rfind('}') { |
| 713 | if end > start { |
| 714 | let candidate = &text[start..=end]; |
| 715 | if let Ok(val) = serde_json::from_str::<serde_json::Value>(candidate) { |
| 716 | if let Some(item) = extract_tool_call_from_value(&val) { |
| 717 | let prefix = text[..start].trim().to_string(); |
| 718 | let content = if prefix.is_empty() { |
| 719 | None |
| 720 | } else { |
| 721 | Some(prefix) |
| 722 | }; |
| 723 | return (content, Some(vec![item])); |
| 724 | } |
| 725 | } |
| 726 | } |
| 727 | } |
| 728 | } |
| 729 | |
| 730 | (Some(text.to_string()), None) |
| 731 | } |
| 732 | |
| 733 | fn extract_tool_call_from_value(val: &serde_json::Value) -> Option<ToolCallItem> { |
| 734 | let name = val |
| 735 | .get("name") |
| 736 | .or_else(|| val.get("tool")) |
| 737 | .and_then(|n| n.as_str())?; |
| 738 | let arguments = if let Some(args) = val.get("arguments").or_else(|| val.get("params")) { |
| 739 | if args.is_string() { |
| 740 | args.as_str().unwrap().to_string() |
| 741 | } else { |
| 742 | serde_json::to_string(args).unwrap_or_else(|_| "{}".to_string()) |
| 743 | } |
| 744 | } else { |
| 745 | "{}".to_string() |
| 746 | }; |
| 747 | |
| 748 | Some(ToolCallItem { |
| 749 | id: format!("call_{}", uuid::Uuid::new_v4()), |
| 750 | call_type: "function".to_string(), |
| 751 | function: ToolCallFunction { |
| 752 | name: name.to_string(), |
| 753 | arguments, |
| 754 | }, |
| 755 | }) |
| 756 | } |
| 757 | |
| 758 | #[cfg(test)] |
| 759 | mod tests { |
| 760 | use super::*; |
| 761 | |
| 762 | #[tokio::test] |
| 763 | async fn test_generate_chat_offline_fail_closed() { |
| 764 | let engine = HttpInferenceBackend::new( |
| 765 | Some("http://127.0.0.1:9999/v1/chat/completions".to_string()), |
| 766 | Some("atlas-lightning-omni".to_string()), |
| 767 | ); |
| 768 | let messages = vec![json!({"role": "user", "content": "ping"})]; |
| 769 | let res = engine.generate_chat(&messages, None, None).await; |
| 770 | assert!(res.is_err()); |
| 771 | let err = res.unwrap_err(); |
| 772 | assert!(err.to_string().contains("Inference endpoint unreachable")); |
| 773 | } |
| 774 | |
| 775 | #[tokio::test] |
| 776 | async fn test_generate_chat_with_tools_offline_fail_closed() { |
| 777 | let engine = HttpInferenceBackend::new( |
| 778 | Some("http://127.0.0.1:9999/v1/chat/completions".to_string()), |
| 779 | Some("atlas-lightning-omni".to_string()), |
| 780 | ); |
| 781 | let messages = vec![json!({"role": "user", "content": "ping"})]; |
| 782 | let res = engine |
| 783 | .generate_chat_with_tools(&messages, None, None, None) |
| 784 | .await; |
| 785 | assert!(res.is_err()); |
| 786 | let err = res.unwrap_err(); |
| 787 | assert!(err.to_string().contains("Inference endpoint unreachable")); |
| 788 | } |
| 789 | |
| 790 | #[test] |
| 791 | fn test_format_messages_to_prompt() { |
| 792 | let messages = vec![ |
| 793 | json!({"role": "system", "content": "You are AEGIS."}), |
| 794 | json!({"role": "user", "content": "Hello."}), |
| 795 | ]; |
| 796 | let prompt = format_messages_to_prompt(&messages, None); |
| 797 | assert!(prompt.contains("<|system|>\nYou are AEGIS.</s>")); |
| 798 | assert!(prompt.contains("<|user|>\nHello.</s>")); |
| 799 | assert!(prompt.ends_with("<|assistant|>\n")); |
| 800 | } |
| 801 | |
| 802 | #[test] |
| 803 | fn test_parse_structured_tool_calls_json_block() { |
| 804 | let text = "Thinking about file... |
| 805 | ```json |
| 806 | { |
| 807 | \"name\": \"read_file\", |
| 808 | \"arguments\": {\"path\": \"src/lib.rs\"} |
| 809 | } |
| 810 | ```"; |
| 811 | let (content, calls) = parse_structured_tool_calls(text); |
| 812 | assert_eq!(content.as_deref(), Some("Thinking about file...")); |
| 813 | assert!(calls.is_some()); |
| 814 | let items = calls.unwrap(); |
| 815 | assert_eq!(items.len(), 1); |
| 816 | assert_eq!(items[0].function.name, "read_file"); |
| 817 | assert!(items[0].function.arguments.contains("src/lib.rs")); |
| 818 | } |
| 819 | |
| 820 | #[test] |
| 821 | fn test_parse_structured_tool_calls_tag() { |
| 822 | let text = "<tool_call>{\"name\": \"bash_eval\", \"arguments\": {\"command\": \"ls\"}}</tool_call>"; |
| 823 | let (content, calls) = parse_structured_tool_calls(text); |
| 824 | assert!(content.is_none()); |
| 825 | assert!(calls.is_some()); |
| 826 | let items = calls.unwrap(); |
| 827 | assert_eq!(items[0].function.name, "bash_eval"); |
| 828 | } |
| 829 | |
| 830 | #[test] |
| 831 | fn test_parse_structured_tool_calls_plain_response() { |
| 832 | let text = "All tasks completed successfully with zero defects."; |
| 833 | let (content, calls) = parse_structured_tool_calls(text); |
| 834 | assert_eq!( |
| 835 | content.as_deref(), |
| 836 | Some("All tasks completed successfully with zero defects.") |
| 837 | ); |
| 838 | assert!(calls.is_none()); |
| 839 | } |
| 840 | |
| 841 | #[tokio::test] |
| 842 | async fn test_embedded_inference_backend_reference_execution() { |
| 843 | let backend = EmbeddedInferenceBackend::load_or_fallback(None, None) |
| 844 | .expect("Reference backend should construct with mock service"); |
| 845 | |
| 846 | assert_eq!(backend.endpoint(), "protocol://aien-inference-service"); |
| 847 | assert!(backend.check_health().await); |
| 848 | |
| 849 | let messages = vec![json!({"role": "user", "content": "ping"})]; |
| 850 | let reply = backend.generate_chat(&messages, Some(0.0), Some(4)).await; |
| 851 | assert!( |
| 852 | reply.is_ok(), |
| 853 | "Embedded chat generation must succeed: {:?}", |
| 854 | reply |
| 855 | ); |
| 856 | let text = reply.unwrap(); |
| 857 | assert!(!text.is_empty(), "Generated text must not be empty"); |
| 858 | } |
| 859 | } |