diff --git a/nah_chat/CHANGELOG b/nah_chat/CHANGELOG index a8ff769..7b0b812 100644 --- a/nah_chat/CHANGELOG +++ b/nah_chat/CHANGELOG @@ -4,6 +4,12 @@ CHANGELOG of nah_chat * Add OpenAI Responses API support: `responses()`, `responses_stream()`, `create_responses_request()`, `ResponsesInput`, `ResponseInputItem`, `ResponseOutputItem`, `ResponseObject`, `ResponseUsage`, `ResponsesStreamEvent`, `ResponsesParamsBuilder`. +* Fix stream event loss in `chat_completion_stream` when SSE events are split across network chunks + (buffered SSE parsing; previously up to 60% of deltas could be dropped with typical chunk sizes). +* Fix non-stream `chat_completion` dropping `reasoning_content` (the JSON field was serialized as + `reasoningContent`; it is now `reasoning_content`, matching DeepSeek/Qwen etc.). +* Return the server HTTP error body from non-stream `chat_completion` on 4xx/5xx responses + instead of a misleading "missing choices field" parse error. * Fix infinite loop in `chat_completion_stream` when the server closes the connection without sending `data: [DONE]`. ## v0.5.0 diff --git a/nah_chat/src/lib.rs b/nah_chat/src/lib.rs index 3755e78..d950494 100644 --- a/nah_chat/src/lib.rs +++ b/nah_chat/src/lib.rs @@ -69,6 +69,8 @@ pub use responses::*; use async_stream::stream; use futures_core::stream::Stream; use serde_json::{Number, Value, json}; + +use responses::SseBuffer; /** * A builder for creating parameters for chat completion requests. */ @@ -248,7 +250,20 @@ impl ChatClient { M: IntoIterator, { let req = self.create_chat_completion_request(model, messages, false, params); - let res_text = req.send().await?.text().await?; + let res = req.send().await?; + if !res.status().is_success() { + let code = res.status().as_u16(); + let error_content = res.text().await.unwrap(); + return Err(Error { + kind: ErrorKind::ModelServerError, + message: Some(format!( + "Model server responded with error: HTTP status {}, error message = {}", + code, error_content + )), + cause: None, + }); + } + let res_text = res.text().await?; let mut response_data: Value = serde_json::from_str(&res_text).map_err(|e| Error { kind: ErrorKind::ModelServerError, message: Some("Failed to parse model server response".to_string()), @@ -328,25 +343,14 @@ impl ChatClient { } let stream = stream! { + let mut buffer = SseBuffer::new(); let mut reach_done = false; while !reach_done { let Some(chunk_data) = res.chunk().await? else { break; }; - let chunk_data_str = match String::from_utf8(chunk_data.to_vec()) { - Ok(v) => v, - Err(e) => { - yield Err(Error { - kind: ErrorKind::ModelServerError, - message: Some("Failed to decode model server response".to_string()), - cause: Some(Box::new(e)) - }); - return; - } - }; - let chunks = chunk_data_str.split("\n\n"); - for chunk in chunks { - let delta = self.get_model_response_chunk(chunk); + for message in buffer.push(&chunk_data) { + let delta = self.get_model_response_chunk(&message); match delta { Some(ChatResponseChunk::Delta(d)) => { yield Ok(d); @@ -358,22 +362,28 @@ impl ChatClient { } } } + for message in buffer.finish() { + if let Some(ChatResponseChunk::Delta(d)) = self.get_model_response_chunk(&message) { + yield Ok(d); + } + } }; Ok(stream) } /** - * Parse the stream data from the stream chat completion API to obtain a chunk delta. + * Parse one complete SSE message (payload between blank lines) from the stream + * chat completion API to obtain a chunk delta. */ - fn get_model_response_chunk(&self, data_str: &str) -> Option { - if !data_str.starts_with("data: ") { - return None; - } - if data_str.starts_with("data: [DONE]") { + fn get_model_response_chunk(&self, message: &str) -> Option { + let data_str = message + .lines() + .find_map(|line| line.strip_prefix("data:")) + .map(str::trim)?; + if data_str == "[DONE]" { return Some(ChatResponseChunk::Done); } - let trim_data = data_str.strip_prefix("data: ").unwrap().trim(); - let chunk_value: Value = match serde_json::from_str(trim_data) { + let chunk_value: Value = match serde_json::from_str(data_str) { Ok(v) => v, Err(_) => return None, }; diff --git a/nah_chat/src/message.rs b/nah_chat/src/message.rs index 4ce4508..4051129 100644 --- a/nah_chat/src/message.rs +++ b/nah_chat/src/message.rs @@ -92,7 +92,7 @@ pub struct ChatMessage { pub content: ChatMessageContentValue, /** Reasoning content in string */ - #[serde(rename = "reasoningContent", skip_serializing_if = "Option::is_none")] + #[serde(rename = "reasoning_content", skip_serializing_if = "Option::is_none")] pub reasoning_content: Option, /** * Which tool call this message is responding to. diff --git a/nah_chat/src/tests.rs b/nah_chat/src/tests.rs index 5c4afa6..1b37653 100644 --- a/nah_chat/src/tests.rs +++ b/nah_chat/src/tests.rs @@ -200,3 +200,88 @@ fn test_responses_request_body() { assert_eq!(body["instructions"], "You are helpful."); assert_eq!(body["reasoning"]["effort"], "high"); } + +#[test] +fn test_chat_stream_chunk_split_reassembly() { + // SSE events split across network chunks must not be lost. + use crate::responses::SseBuffer; + let client = ChatClient::init("http://localhost".to_string(), None); + let delta1 = r#"{"choices":[{"delta":{"role":"assistant","content":"Hello"}}]}"#; + let delta2 = r#"{"choices":[{"delta":{"content":" world"}}]}"#; + let fixture = format!("data: {}\n\ndata: {}\n\ndata: [DONE]\n", delta1, delta2); + + let mut buffer = SseBuffer::new(); + let mut deltas: Vec = Vec::new(); + let mut done = false; + + // Cut the first delta payload in half; the boundary falls inside an event. + let split_at = fixture.find("Hello").unwrap(); + for message in buffer.push(&fixture.as_bytes()[..split_at]) { + match client.get_model_response_chunk(&message) { + Some(ChatResponseChunk::Delta(d)) => { + if let Some(content) = d.content { + deltas.push(content); + } + } + Some(ChatResponseChunk::Done) => done = true, + None => {} + } + } + assert!( + deltas.is_empty(), + "no complete event should be emitted before the split point" + ); + + for message in buffer.push(&fixture.as_bytes()[split_at..]) { + match client.get_model_response_chunk(&message) { + Some(ChatResponseChunk::Delta(d)) => { + if let Some(content) = d.content { + deltas.push(content); + } + } + Some(ChatResponseChunk::Done) => done = true, + None => {} + } + } + for message in buffer.finish() { + match client.get_model_response_chunk(&message) { + Some(ChatResponseChunk::Delta(d)) => { + if let Some(content) = d.content { + deltas.push(content); + } + } + Some(ChatResponseChunk::Done) => done = true, + None => {} + } + } + + assert_eq!(deltas, vec!["Hello".to_string(), " world".to_string()]); + assert!(done, "the [DONE] marker must be detected"); +} + +#[test] +fn test_deserialize_reasoning_content_snake_case() { + // DeepSeek (and most OpenAI-compatible providers) send `reasoning_content`. + let data = r#"{ + "role": "assistant", + "content": "Hi", + "reasoning_content": "think a bit" + } + "#; + let message: ChatMessage = serde_json::from_str(data).unwrap(); + assert_eq!(message.reasoning_content.as_deref(), Some("think a bit")); +} + +#[test] +fn test_serialize_reasoning_content_snake_case() { + let message = ChatMessage { + role: "assistant".to_owned(), + content: ChatMessageContentValue::Text("Hi".to_owned()), + reasoning_content: Some("think".to_owned()), + tool_call_id: None, + tool_calls: None, + }; + let value = serde_json::to_value(&message).unwrap(); + assert_eq!(value["reasoning_content"], "think"); + assert!(value.get("reasoningContent").is_none()); +}