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 / tests / embedded_inference_tests.rs
| 1 | //! End-to-End Test Suite for In-Process Inference in AEGIS. |
| 2 | //! Verifies: |
| 3 | //! 1. In-process EmbeddedInferenceBackend initialization. |
| 4 | //! 2. ProtocolInferenceBackend contract execution. |
| 5 | //! 3. Pure-Rust TinyLlama chat template formatting. |
| 6 | //! 4. Structured tool calling (model -> structured tool call -> AEGIS tool -> model). |
| 7 | //! 5. AgentEngine integration using Arc<dyn InferenceEngine>. |
| 8 | //! 6. Gateway streaming chat completions over SSE. |
| 9 | |
| 10 | use aegis::inference::{ |
| 11 | format_messages_to_prompt, parse_structured_tool_calls, EmbeddedInferenceBackend, |
| 12 | InferenceEngine, |
| 13 | }; |
| 14 | use aegis::{AgentEngine, SkillExecutionRequest, SkillRegistry}; |
| 15 | use futures_util::StreamExt; |
| 16 | use serde_json::json; |
| 17 | use std::sync::Arc; |
| 18 | |
| 19 | #[tokio::test] |
| 20 | async fn test_embedded_model_reference_creation() { |
| 21 | let config = json!({ |
| 22 | "num_layers": 2, |
| 23 | "num_heads": 4, |
| 24 | "vocab_size": 256 |
| 25 | }); |
| 26 | |
| 27 | let backend = EmbeddedInferenceBackend::with_reference_weights(&config) |
| 28 | .expect("EmbeddedInferenceBackend must construct with reference weights"); |
| 29 | |
| 30 | assert_eq!(backend.endpoint(), "protocol://aien-inference-service"); |
| 31 | assert!(backend.check_health().await); |
| 32 | } |
| 33 | |
| 34 | #[tokio::test] |
| 35 | async fn test_pure_rust_chat_template_formatting() { |
| 36 | let messages = vec![ |
| 37 | json!({"role": "system", "content": "You are a helpful assistant."}), |
| 38 | json!({"role": "user", "content": "Hello!"}), |
| 39 | json!({"role": "assistant", "content": "Greetings! How can I assist?"}), |
| 40 | json!({"role": "user", "content": "What is 2+2?"}), |
| 41 | ]; |
| 42 | |
| 43 | let prompt = format_messages_to_prompt(&messages, None); |
| 44 | assert!(prompt.starts_with("<|system|>\nYou are a helpful assistant.</s>\n")); |
| 45 | assert!(prompt.contains("<|user|>\nHello!</s>\n")); |
| 46 | assert!(prompt.contains("<|assistant|>\nGreetings! How can I assist?</s>\n")); |
| 47 | assert!(prompt.ends_with("<|user|>\nWhat is 2+2?</s>\n<|assistant|>\n")); |
| 48 | } |
| 49 | |
| 50 | #[tokio::test] |
| 51 | async fn test_embedded_structured_tool_calling_flow() { |
| 52 | let registry = SkillRegistry::new(); |
| 53 | let tools = registry.to_openai_tools(); |
| 54 | assert!(!tools.is_empty()); |
| 55 | |
| 56 | let simulated_model_output = r#"I need to check system health. |
| 57 | ```json |
| 58 | { |
| 59 | "name": "bash_eval", |
| 60 | "arguments": {"command": "ls"} |
| 61 | } |
| 62 | ```"#; |
| 63 | |
| 64 | let (content, tool_calls) = parse_structured_tool_calls(simulated_model_output); |
| 65 | assert_eq!(content.as_deref(), Some("I need to check system health.")); |
| 66 | assert!( |
| 67 | tool_calls.is_some(), |
| 68 | "Tool call must be extracted from model output" |
| 69 | ); |
| 70 | |
| 71 | let calls = tool_calls.unwrap(); |
| 72 | assert_eq!(calls.len(), 1); |
| 73 | let call = &calls[0]; |
| 74 | assert_eq!(call.function.name, "bash_eval"); |
| 75 | |
| 76 | let args: serde_json::Value = serde_json::from_str(&call.function.arguments).unwrap(); |
| 77 | let req = SkillExecutionRequest { |
| 78 | skill_name: call.function.name.clone(), |
| 79 | arguments: args, |
| 80 | }; |
| 81 | let exec_res = registry.execute(&req); |
| 82 | assert!( |
| 83 | exec_res.success, |
| 84 | "Catalogued local command must succeed: {:?}", |
| 85 | exec_res.error |
| 86 | ); |
| 87 | let tool_output = exec_res.output; |
| 88 | assert!(!tool_output.is_empty()); |
| 89 | |
| 90 | let multi_turn_messages = vec![ |
| 91 | json!({"role": "user", "content": "Ping the system"}), |
| 92 | json!({ |
| 93 | "role": "assistant", |
| 94 | "content": content.unwrap_or_default(), |
| 95 | "tool_calls": [{ |
| 96 | "id": call.id, |
| 97 | "type": "function", |
| 98 | "function": { |
| 99 | "name": call.function.name, |
| 100 | "arguments": call.function.arguments |
| 101 | } |
| 102 | }] |
| 103 | }), |
| 104 | json!({"role": "tool", "content": tool_output}), |
| 105 | ]; |
| 106 | |
| 107 | let second_turn_prompt = format_messages_to_prompt(&multi_turn_messages, Some(&tools)); |
| 108 | assert!(second_turn_prompt.contains("[Tool Output]:")); |
| 109 | let sample = tool_output.lines().next().unwrap_or(""); |
| 110 | assert!(!sample.is_empty()); |
| 111 | assert!(second_turn_prompt.contains(sample)); |
| 112 | assert!(second_turn_prompt.ends_with("<|assistant|>\n")); |
| 113 | } |
| 114 | |
| 115 | #[tokio::test] |
| 116 | async fn test_agent_engine_with_embedded_backend_trait() { |
| 117 | let config = json!({}); |
| 118 | let embedded_backend = EmbeddedInferenceBackend::with_reference_weights(&config).unwrap(); |
| 119 | let inference: Arc<dyn InferenceEngine> = Arc::new(embedded_backend); |
| 120 | let skills = Arc::new(SkillRegistry::new()); |
| 121 | |
| 122 | let _agent = AgentEngine::new(inference.clone(), skills, None); |
| 123 | assert_eq!(inference.endpoint(), "protocol://aien-inference-service"); |
| 124 | |
| 125 | let mut history = vec![ |
| 126 | json!({"role": "system", "content": "System prompt"}), |
| 127 | json!({"role": "user", "content": "User goal"}), |
| 128 | json!({"role": "assistant", "content": "Thought"}), |
| 129 | json!({"role": "tool", "content": "Tool output"}), |
| 130 | ]; |
| 131 | let pruned = AgentEngine::prune_context_window(&mut history, 5); |
| 132 | assert!(pruned); |
| 133 | assert_eq!(history.len(), 2); |
| 134 | } |
| 135 | |
| 136 | #[tokio::test] |
| 137 | async fn test_real_model_embedded_execution_if_present() { |
| 138 | let backend = EmbeddedInferenceBackend::load_or_fallback(None, None); |
| 139 | assert!( |
| 140 | backend.is_ok(), |
| 141 | "EmbeddedInferenceBackend must load successfully: {:?}", |
| 142 | backend.err() |
| 143 | ); |
| 144 | |
| 145 | let backend = backend.unwrap(); |
| 146 | let res = backend.generate("Hello world", None, None).await; |
| 147 | assert!(res.is_ok(), "Generation must succeed: {:?}", res.err()); |
| 148 | let text = res.unwrap(); |
| 149 | assert!(!text.is_empty()); |
| 150 | } |
| 151 | |
| 152 | #[tokio::test] |
| 153 | async fn test_embedded_inference_chat_streaming() { |
| 154 | let config = json!({}); |
| 155 | let backend = EmbeddedInferenceBackend::with_reference_weights(&config).unwrap(); |
| 156 | let messages = vec![ |
| 157 | json!({"role": "system", "content": "You are a helpful sovereign agent."}), |
| 158 | json!({"role": "user", "content": "Status check"}), |
| 159 | ]; |
| 160 | |
| 161 | let stream_res = backend.stream_chat(&messages, Some(0.0), Some(4)).await; |
| 162 | assert!( |
| 163 | stream_res.is_ok(), |
| 164 | "Streaming failed: {:?}", |
| 165 | stream_res.err() |
| 166 | ); |
| 167 | let mut stream = stream_res.unwrap(); |
| 168 | |
| 169 | let mut full_sse = String::new(); |
| 170 | while let Some(chunk) = stream.next().await { |
| 171 | assert!(chunk.is_ok(), "Chunk read failed: {:?}", chunk.err()); |
| 172 | let bytes = chunk.unwrap(); |
| 173 | let chunk_str = String::from_utf8_lossy(&bytes); |
| 174 | full_sse.push_str(&chunk_str); |
| 175 | } |
| 176 | |
| 177 | assert!( |
| 178 | full_sse.contains("data: "), |
| 179 | "SSE payload must contain data: prefix" |
| 180 | ); |
| 181 | assert!( |
| 182 | full_sse.contains("chat.completion.chunk"), |
| 183 | "SSE payload must contain chat.completion.chunk" |
| 184 | ); |
| 185 | assert!( |
| 186 | full_sse.contains("data: [DONE]"), |
| 187 | "SSE payload must terminate with [DONE]" |
| 188 | ); |
| 189 | } |
| 190 | |
| 191 | #[tokio::test] |
| 192 | async fn test_gateway_with_embedded_inference_streaming() { |
| 193 | use aegis::create_router; |
| 194 | use aegis::heartbeat::HeartbeatEngine; |
| 195 | use aegis::persistence::Database; |
| 196 | use aegis::GatewayState; |
| 197 | use axum::body::Body; |
| 198 | use axum::http::{Request, StatusCode}; |
| 199 | use tower::ServiceExt; |
| 200 | |
| 201 | let config = json!({}); |
| 202 | let embedded_backend = |
| 203 | Arc::new(EmbeddedInferenceBackend::with_reference_weights(&config).unwrap()); |
| 204 | let db = Arc::new(Database::open_in_memory().unwrap()); |
| 205 | let heartbeat = Arc::new(HeartbeatEngine::with_inference( |
| 206 | 60, |
| 207 | db.clone(), |
| 208 | embedded_backend.clone(), |
| 209 | )); |
| 210 | let skills = Arc::new(SkillRegistry::new()); |
| 211 | let agent = Arc::new(AgentEngine::new( |
| 212 | embedded_backend.clone(), |
| 213 | skills.clone(), |
| 214 | None, |
| 215 | )); |
| 216 | |
| 217 | let state = GatewayState { |
| 218 | start_time: std::time::Instant::now(), |
| 219 | inference: embedded_backend, |
| 220 | db, |
| 221 | heartbeat, |
| 222 | skills, |
| 223 | agent, |
| 224 | operator: aegis::OperatorAuth::with_token("embedded-test-operator-token-0123456789") |
| 225 | .unwrap(), |
| 226 | }; |
| 227 | let app = create_router(state); |
| 228 | |
| 229 | let req_payload = serde_json::json!({ |
| 230 | "model": "atlas-lightning-omni", |
| 231 | "messages": [ |
| 232 | {"role": "user", "content": "hello"} |
| 233 | ], |
| 234 | "stream": true, |
| 235 | "max_tokens": 4 |
| 236 | }); |
| 237 | |
| 238 | let response = app |
| 239 | .oneshot( |
| 240 | Request::builder() |
| 241 | .method("POST") |
| 242 | .uri("/v1/chat/completions") |
| 243 | .header( |
| 244 | "Authorization", |
| 245 | "Bearer embedded-test-operator-token-0123456789", |
| 246 | ) |
| 247 | .header("Content-Type", "application/json") |
| 248 | .body(Body::from(req_payload.to_string())) |
| 249 | .unwrap(), |
| 250 | ) |
| 251 | .await |
| 252 | .unwrap(); |
| 253 | |
| 254 | assert_eq!(response.status(), StatusCode::OK); |
| 255 | assert_eq!( |
| 256 | response.headers().get("content-type").unwrap(), |
| 257 | "text/event-stream" |
| 258 | ); |
| 259 | |
| 260 | let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) |
| 261 | .await |
| 262 | .unwrap(); |
| 263 | let text = String::from_utf8_lossy(&bytes); |
| 264 | assert!( |
| 265 | text.contains("data: "), |
| 266 | "Gateway SSE output must contain data: prefix" |
| 267 | ); |
| 268 | assert!( |
| 269 | text.contains("chat.completion.chunk"), |
| 270 | "Gateway SSE output must contain chat.completion.chunk" |
| 271 | ); |
| 272 | assert!( |
| 273 | text.contains("data: [DONE]"), |
| 274 | "Gateway SSE output must terminate with [DONE]" |
| 275 | ); |
| 276 | } |