From bd1d2044adfc7201f3355e703b849cce3d427c24 Mon Sep 17 00:00:00 2001 From: Mengxiao Lin Date: Mon, 14 Sep 2026 22:13:56 -0700 Subject: [PATCH] fix(nah_chat): replace (not append) tool call id/type in stream deltas Streamed chat completion deltas carry the tool call `id` and `type` as complete, server-assigned values, not token streams. Some providers resend the full value in every chunk of the same tool call; appending made the value grow unboundedly (e.g. "call_abccall_abc"), which breaks matching the tool call to its id. Merge `id` / `type` with last-non-empty-wins semantics instead: a later non-empty value replaces the accumulated one, and an empty string is treated as absent so a delta carrying `"id": ""` does not erase the real value. `function.arguments` / `function.name` keep accumulating, as those are genuine token streams. Add regression tests for the resend, replace, empty-string and per-index cases; they fail against the previous append behaviour. --- nah_chat/CHANGELOG | 4 + nah_chat/src/message.rs | 14 ++- nah_chat/src/tests.rs | 189 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 205 insertions(+), 2 deletions(-) diff --git a/nah_chat/CHANGELOG b/nah_chat/CHANGELOG index 2f82e89..3899743 100644 --- a/nah_chat/CHANGELOG +++ b/nah_chat/CHANGELOG @@ -7,6 +7,10 @@ CHANGELOG of nah_chat merging into an existing `reasoning` object (other keys, e.g. `summary`, are preserved). * Additive only — `insert()` / `reasoning(Value)` behaviour is unchanged; no new public types and no version bump. +* Fix tool call `id` / `type` duplication in streamed chat completion deltas. Some providers resend + the complete value in every chunk of the same tool call; it was concatenated and grew + (`call_abccall_abc`). `id` / `type` are complete scalars, so they now use last-non-empty-wins + semantics, while `function.arguments` / `function.name` keep accumulating. ## v0.8.0 * Add token usage support to the chat completion stream. `chat_completion_stream` now yields diff --git a/nah_chat/src/message.rs b/nah_chat/src/message.rs index ebdac42..30ef918 100644 --- a/nah_chat/src/message.rs +++ b/nah_chat/src/message.rs @@ -175,12 +175,22 @@ impl ChatMessage { }); } let object_to_apply = message_tool_calls.get_mut(idx).unwrap(); + // `id` and `type` are complete, server-assigned scalars, not token + // streams: the latest non-empty value wins. Some providers resend the + // full value in every chunk of the same tool call, so appending them + // would duplicate the value (e.g. "call_abccall_abc"). An empty string + // is treated as "absent" so that a delta carrying `"id": ""` does not + // erase the real id. tool_call.id.and_then(|id| { - object_to_apply.id.push_str(&id); + if !id.is_empty() { + object_to_apply.id = id; + } Some(()) }); tool_call._type.and_then(|t| { - object_to_apply._type.push_str(&t); + if !t.is_empty() { + object_to_apply._type = t; + } Some(()) }); tool_call.function.and_then(|fcall| { diff --git a/nah_chat/src/tests.rs b/nah_chat/src/tests.rs index b5f7937..f66af84 100644 --- a/nah_chat/src/tests.rs +++ b/nah_chat/src/tests.rs @@ -84,6 +84,195 @@ fn test_apply_tool_calls() { } } +/** + * Build a chunk delta that carries a single tool call at `index`. `None` leaves + * a field absent from the chunk, like a well-behaved streaming provider does for + * the fields it does not resend. + */ +fn tool_call_delta( + index: usize, + id: Option<&str>, + call_type: Option<&str>, + name: Option<&str>, + arguments: Option<&str>, +) -> ChatResponseChunkDelta { + let function = if name.is_some() || arguments.is_some() { + Some(FunctionCallRequestChunkDelta { + name: name.map(str::to_owned), + arguments: arguments.map(str::to_owned), + }) + } else { + None + }; + ChatResponseChunkDelta { + role: None, + content: None, + reasoning_content: None, + tool_calls: Some(vec![ToolCallRequestChunkDelta { + index, + id: id.map(str::to_owned), + _type: call_type.map(str::to_owned), + function, + }]), + } +} + +#[test] +fn test_apply_tool_call_repeated_id_and_type_are_not_duplicated() { + // Some providers resend the *complete* tool call `id` and `type` in every + // delta chunk of the same tool call. Replacing the value with the same string + // must be idempotent instead of concatenating it again (which would produce + // e.g. "call_abc123call_abc123"). + let mut message = ChatMessage::new(); + message.apply_model_response_chunk(tool_call_delta( + 0, + Some("call_abc123"), + Some("function"), + Some("get_weather"), + Some(""), + )); + message.apply_model_response_chunk(tool_call_delta( + 0, + Some("call_abc123"), + Some("function"), + None, + Some("{\"city\""), + )); + message.apply_model_response_chunk(tool_call_delta( + 0, + Some("call_abc123"), + Some("function"), + None, + Some(":\"SF\"}"), + )); + + let tool_calls = message.tool_calls.as_ref().unwrap(); + assert_eq!(tool_calls.len(), 1); + assert_eq!(tool_calls[0].id, "call_abc123"); + assert_eq!(tool_calls[0]._type, "function"); + assert_eq!(tool_calls[0].function.name, "get_weather"); + assert_eq!(tool_calls[0].function.arguments, "{\"city\":\"SF\"}"); +} + +#[test] +fn test_apply_tool_call_new_id_and_type_replace_the_previous_value() { + // `id` / `type` are complete values, not token streams, so a later non-empty + // value replaces the one accumulated so far (last value wins). + let mut message = ChatMessage::new(); + message.apply_model_response_chunk(tool_call_delta( + 0, + Some("call_old"), + Some("function"), + Some("get_weather"), + Some(""), + )); + message.apply_model_response_chunk(tool_call_delta( + 0, + Some("call_new"), + Some("function"), + None, + Some("{}"), + )); + + let tool_calls = message.tool_calls.as_ref().unwrap(); + assert_eq!(tool_calls.len(), 1); + assert_eq!(tool_calls[0].id, "call_new"); + assert_eq!(tool_calls[0]._type, "function"); + assert_eq!(tool_calls[0].function.name, "get_weather"); + assert_eq!(tool_calls[0].function.arguments, "{}"); +} + +#[test] +fn test_apply_tool_call_empty_id_and_type_do_not_clobber() { + // A provider may send an empty string instead of omitting `id`/`type` on the + // deltas that do not carry them; an empty value must not erase the real one. + let mut message = ChatMessage::new(); + message.apply_model_response_chunk(tool_call_delta( + 0, + Some("call_abc123"), + Some("function"), + Some("get_weather"), + Some("{\"a"), + )); + message.apply_model_response_chunk(tool_call_delta(0, Some(""), Some(""), None, Some(":1}"))); + + let tool_calls = message.tool_calls.as_ref().unwrap(); + assert_eq!(tool_calls.len(), 1); + assert_eq!(tool_calls[0].id, "call_abc123"); + assert_eq!(tool_calls[0]._type, "function"); + assert_eq!(tool_calls[0].function.name, "get_weather"); + assert_eq!(tool_calls[0].function.arguments, "{\"a:1}"); +} + +#[test] +fn test_apply_tool_call_repeated_id_and_type_per_index() { + // Parallel tool calls: the keep-vs-append decision must be made per index, so + // one tool call resending its id does not affect another one. + let mut message = ChatMessage::new(); + message.apply_model_response_chunk(ChatResponseChunkDelta { + role: None, + content: None, + reasoning_content: None, + tool_calls: Some(vec![ + ToolCallRequestChunkDelta { + index: 0, + id: Some("call_0".to_owned()), + _type: Some("function".to_owned()), + function: Some(FunctionCallRequestChunkDelta { + name: Some("first".to_owned()), + arguments: Some(String::new()), + }), + }, + ToolCallRequestChunkDelta { + index: 1, + id: Some("call_1".to_owned()), + _type: Some("function".to_owned()), + function: Some(FunctionCallRequestChunkDelta { + name: Some("second".to_owned()), + arguments: Some(String::new()), + }), + }, + ]), + }); + // Resend the full id/type for both tool calls, then stream the arguments. + message.apply_model_response_chunk(ChatResponseChunkDelta { + role: None, + content: None, + reasoning_content: None, + tool_calls: Some(vec![ + ToolCallRequestChunkDelta { + index: 0, + id: Some("call_0".to_owned()), + _type: Some("function".to_owned()), + function: Some(FunctionCallRequestChunkDelta { + name: None, + arguments: Some("{\"a\":1}".to_owned()), + }), + }, + ToolCallRequestChunkDelta { + index: 1, + id: Some("call_1".to_owned()), + _type: Some("function".to_owned()), + function: Some(FunctionCallRequestChunkDelta { + name: None, + arguments: Some("{\"b\":2}".to_owned()), + }), + }, + ]), + }); + + let tool_calls = message.tool_calls.as_ref().unwrap(); + assert_eq!(tool_calls.len(), 2); + assert_eq!(tool_calls[0].id, "call_0"); + assert_eq!(tool_calls[0]._type, "function"); + assert_eq!(tool_calls[0].function.name, "first"); + assert_eq!(tool_calls[0].function.arguments, "{\"a\":1}"); + assert_eq!(tool_calls[1].id, "call_1"); + assert_eq!(tool_calls[1]._type, "function"); + assert_eq!(tool_calls[1].function.name, "second"); + assert_eq!(tool_calls[1].function.arguments, "{\"b\":2}"); +} + #[test] fn test_chat_completion_params_builder() { let mut params_builder = ChatCompletionParamsBuilder::new();