diff --git a/Cargo.lock b/Cargo.lock index ea77369..93b85fa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1429,6 +1429,7 @@ dependencies = [ "anyhow", "async-trait", "axum", + "bytes", "chrono", "clap", "futures-util", diff --git a/Cargo.toml b/Cargo.toml index e680680..bbfc80f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,6 +30,7 @@ aien-kv-cache = { path = "../aien-sovereign-core/crates/aien-kv-cache" } aien-scheduler = { path = "../aien-sovereign-core/crates/aien-scheduler" } async-trait = "0.1" parking_lot = "0.12" +bytes = "1.6" [dev-dependencies] diff --git a/src/gateway.rs b/src/gateway.rs index 16a7a3b..ce51c2b 100644 --- a/src/gateway.rs +++ b/src/gateway.rs @@ -234,8 +234,7 @@ pub async fn openai_completions_handler( .stream_chat(&messages_json, payload.temperature, payload.max_tokens) .await { - Ok(res) => { - let stream = res.bytes_stream(); + Ok(stream) => { let body = Body::from_stream(stream); Response::builder() .header(header::CONTENT_TYPE, "text/event-stream") diff --git a/src/inference.rs b/src/inference.rs index 4930986..a1dbe97 100644 --- a/src/inference.rs +++ b/src/inference.rs @@ -12,7 +12,11 @@ use aien_kv_cache::SharedKvManager; use aien_scheduler::AienScheduler; use async_trait::async_trait; use parking_lot::{Mutex, RwLock}; -use reqwest::{Client, Response}; +use futures_util::StreamExt; +use reqwest::Client; +use std::pin::Pin; + +pub type ChatStream = Pin> + Send>>; use serde::{Deserialize, Serialize}; use serde_json::json; use std::path::{Path, PathBuf}; @@ -123,15 +127,13 @@ pub trait InferenceEngine: Send + Sync { max_tokens: Option, ) -> Result>; - /// Streams chat completions over HTTP (supported on HTTP backend). + /// Streams chat completions as raw SSE event bytes. async fn stream_chat( &self, - _messages: &[serde_json::Value], - _temperature: Option, - _max_tokens: Option, - ) -> Result> { - Err(anyhow::anyhow!("Streaming is not supported on embedded inference backend").into()) - } + messages: &[serde_json::Value], + temperature: Option, + max_tokens: Option, + ) -> Result>; /// Validates inference engine availability and readiness. async fn check_health(&self) -> bool; @@ -286,7 +288,7 @@ impl InferenceEngine for HttpInferenceBackend { messages: &[serde_json::Value], temperature: Option, max_tokens: Option, - ) -> Result> { + ) -> Result> { let body = json!({ "model": self.model_id, "messages": messages, @@ -296,7 +298,16 @@ impl InferenceEngine for HttpInferenceBackend { }); let res = self.client.post(&self.endpoint).json(&body).send().await?; - Ok(res) + if !res.status().is_success() { + let status = res.status(); + let text = res.text().await.unwrap_or_default(); + return Err(anyhow::anyhow!("MAX streaming error {}: {}", status, text).into()); + } + + let stream = res.bytes_stream().map(|item| { + item.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e)) + }); + Ok(Box::pin(stream)) } async fn check_health(&self) -> bool { @@ -427,6 +438,42 @@ impl EmbeddedModel { } } + /// Generates text completion streaming token text pieces via a callback. + pub fn generate_stream( + &mut self, + prompt: &str, + max_tokens: usize, + temperature: f32, + mut on_token: F, + ) -> Result<(), String> + where + F: FnMut(&str) -> bool, + { + let prompt_tokens = self.tokenizer.encode(prompt) + .map_err(|e| format!("Encoding failed: {}", e))?; + + let seq_id = generate_sequence_id(); + let stop_tokens = [ + TinyLlamaTokenizer::EOS_TOKEN_ID, + TinyLlamaTokenizer::UNK_TOKEN_ID, + ]; + + self.transformer.generate_tokens_streaming( + seq_id, + &prompt_tokens, + max_tokens, + temperature, + &stop_tokens, + |tok| { + if let Ok(piece) = self.tokenizer.decode(&[tok]) { + on_token(&piece) + } else { + true + } + }, + ) + } + /// Generates text completion from raw prompt string. pub fn generate(&mut self, prompt: &str, max_tokens: usize, temperature: f32) -> Result { let prompt_tokens = self.tokenizer.encode(prompt) @@ -619,6 +666,71 @@ impl InferenceEngine for EmbeddedInferenceBackend { Ok(result) } + async fn stream_chat( + &self, + messages: &[serde_json::Value], + temperature: Option, + max_tokens: Option, + ) -> Result> { + let model = self.model.clone(); + let prompt_str = format_messages_to_prompt(messages, None); + let max_toks = max_tokens.unwrap_or(256) as usize; + let temp = temperature.unwrap_or(0.0); + let model_id = self.model_id.clone(); + + let (tx, rx) = tokio::sync::mpsc::channel::>(32); + + tokio::task::spawn_blocking(move || { + let chunk_id = format!("chatcmpl-{}", uuid::Uuid::new_v4()); + let created = chrono::Utc::now().timestamp(); + let mut guard = model.lock(); + + let gen_res = guard.generate_stream(&prompt_str, max_toks, temp, |delta| { + let chunk_json = json!({ + "id": &chunk_id, + "object": "chat.completion.chunk", + "created": created, + "model": &model_id, + "choices": [{ + "index": 0, + "delta": { "content": delta }, + "finish_reason": null + }] + }); + let payload = format!("data: {} + +", chunk_json); + tx.blocking_send(Ok(bytes::Bytes::from(payload))).is_ok() + }); + + if let Err(e) = gen_res { + let _ = tx.blocking_send(Err(std::io::Error::new(std::io::ErrorKind::Other, e))); + return; + } + + let term_chunk = json!({ + "id": chunk_id, + "object": "chat.completion.chunk", + "created": created, + "model": model_id, + "choices": [{ + "index": 0, + "delta": {}, + "finish_reason": "stop" + }] + }); + let term_payload = format!("data: {} + +data: [DONE] + +", term_chunk); + let _ = tx.blocking_send(Ok(bytes::Bytes::from(term_payload))); + }); + + let stream = tokio_stream::wrappers::ReceiverStream::new(rx); + Ok(Box::pin(stream)) + } + async fn check_health(&self) -> bool { true } diff --git a/src/lib.rs b/src/lib.rs index c8b08ab..8120182 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -11,7 +11,7 @@ pub mod vault; pub use agent::{AgentEngine, AgentExecutionResult, AgentStep}; pub use gateway::{create_router, start_gateway, GatewayState, HealthResponse}; pub use heartbeat::{HeartbeatEngine, PulseReceipt}; -pub use inference::{ChatTurnResponse, EmbeddedInferenceBackend, EmbeddedModel, HttpInferenceBackend, InferenceEngine, ToolCallFunction, ToolCallItem}; +pub use inference::{ChatStream, ChatTurnResponse, EmbeddedInferenceBackend, EmbeddedModel, HttpInferenceBackend, InferenceEngine, ToolCallFunction, ToolCallItem}; pub use mojo_bridge::MojoSimdBridge; pub use persistence::{CrumbRecord, Database, TaskRecord, TurnRecord}; pub use security::{SecurityError, WorkspaceCapability}; diff --git a/tests/embedded_inference_tests.rs b/tests/embedded_inference_tests.rs index fb1900d..2dcbb49 100644 --- a/tests/embedded_inference_tests.rs +++ b/tests/embedded_inference_tests.rs @@ -14,6 +14,7 @@ use openclaw::inference::{ }; use openclaw::{AgentEngine, SkillExecutionRequest, SkillRegistry}; use serde_json::json; +use futures_util::StreamExt; use std::sync::Arc; #[tokio::test] @@ -183,3 +184,118 @@ async fn test_real_model_embedded_execution_if_present() { let text = res.unwrap(); println!("Generated text preview: {}", text); } + +#[tokio::test] +async fn test_embedded_inference_chat_streaming() { + let config = ModelConfig { + num_layers: 2, + num_heads: 4, + num_kv_heads: 2, + head_dim: 16, + hidden_dim: 64, + intermediate_dim: 128, + vocab_size: 256, + block_size: 16, + ..Default::default() + }; + + let backend = EmbeddedInferenceBackend::with_reference_weights(&config).unwrap(); + let messages = vec![ + json!({"role": "system", "content": "You are a helpful sovereign agent."}), + json!({"role": "user", "content": "Status check"}), + ]; + + let stream_res = backend.stream_chat(&messages, Some(0.0), Some(4)).await; + assert!(stream_res.is_ok(), "Streaming failed: {:?}", stream_res.err()); + let mut stream = stream_res.unwrap(); + + let mut full_sse = String::new(); + while let Some(chunk) = stream.next().await { + assert!(chunk.is_ok(), "Chunk read failed: {:?}", chunk.err()); + let bytes = chunk.unwrap(); + let chunk_str = String::from_utf8_lossy(&bytes); + full_sse.push_str(&chunk_str); + } + + assert!(full_sse.contains("data: "), "SSE payload must contain data: prefix"); + assert!(full_sse.contains("chat.completion.chunk"), "SSE payload must contain chat.completion.chunk"); + assert!(full_sse.contains("data: [DONE]"), "SSE payload must terminate with [DONE]"); +} + +#[tokio::test] +async fn test_gateway_with_embedded_inference_streaming() { + use axum::body::Body; + use axum::http::{Request, StatusCode}; + use openclaw::create_router; + use openclaw::GatewayState; + use openclaw::persistence::Database; + use openclaw::heartbeat::HeartbeatEngine; + use tower::ServiceExt; + + let config = ModelConfig { + num_layers: 2, + num_heads: 4, + num_kv_heads: 2, + head_dim: 16, + hidden_dim: 64, + intermediate_dim: 128, + vocab_size: 256, + block_size: 16, + ..Default::default() + }; + + let embedded_backend = Arc::new(EmbeddedInferenceBackend::with_reference_weights(&config).unwrap()); + let db = Arc::new(Database::open_in_memory().unwrap()); + let heartbeat = Arc::new(HeartbeatEngine::with_inference( + 60, + db.clone(), + embedded_backend.clone(), + )); + let skills = Arc::new(SkillRegistry::new()); + let agent = Arc::new(AgentEngine::new(embedded_backend.clone(), skills.clone(), None)); + + let state = GatewayState { + start_time: std::time::Instant::now(), + inference: embedded_backend, + db, + heartbeat, + skills, + agent, + }; + let app = create_router(state); + + let req_payload = serde_json::json!({ + "model": "atlas-lightning-omni", + "messages": [ + {"role": "user", "content": "hello"} + ], + "stream": true, + "max_tokens": 4 + }); + + let response = app + .oneshot( + Request::builder() + .method("POST") + .uri("/v1/chat/completions") + .header("Content-Type", "application/json") + .body(Body::from(req_payload.to_string())) + .unwrap(), + ) + .await + .unwrap(); + + assert_eq!(response.status(), StatusCode::OK); + assert_eq!( + response.headers().get("content-type").unwrap(), + "text/event-stream" + ); + + let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + let text = String::from_utf8_lossy(&bytes); + assert!(text.contains("data: "), "Gateway SSE output must contain data: prefix"); + assert!(text.contains("chat.completion.chunk"), "Gateway SSE output must contain chat.completion.chunk"); + assert!(text.contains("data: [DONE]"), "Gateway SSE output must terminate with [DONE]"); +}