From 69965466e6510db730f0eaf2384addecdcc66a84 Mon Sep 17 00:00:00 2001 From: sigoden Date: Mon, 9 Sep 2024 18:39:14 +0800 Subject: feat: proxy chat-completions api with tools support (#850) --- src/client/openai.rs | 50 ++++++++++++++++++++++++++++---------------------- 1 file changed, 28 insertions(+), 22 deletions(-) (limited to 'src/client/openai.rs') diff --git a/src/client/openai.rs b/src/client/openai.rs index 902a215..4876ed3 100644 --- a/src/client/openai.rs +++ b/src/client/openai.rs @@ -108,9 +108,12 @@ pub async fn openai_chat_completions_streaming( let handle = |message: SseMmessage| -> Result { if message.data == "[DONE]" { if !function_name.is_empty() { + let arguments: Value = function_arguments.parse().with_context(|| { + format!("Tool call '{function_name}' is invalid: arguments must be in valid JSON format") + })?; handler.tool_call(ToolCall::new( function_name.clone(), - json!(function_arguments), + arguments, normalize_function_id(&function_id), ))?; } @@ -128,9 +131,12 @@ pub async fn openai_chat_completions_streaming( let index = index.unwrap_or_default(); if index != function_index { if !function_name.is_empty() { + let arguments: Value = function_arguments.parse().with_context(|| { + format!("Tool call '{function_name}' is invalid: arguments must be in valid JSON format") + })?; handler.tool_call(ToolCall::new( function_name.clone(), - json!(function_arguments), + arguments, normalize_function_id(&function_id), ))?; } @@ -207,7 +213,7 @@ pub fn openai_build_chat_completions_body(data: ChatCompletionsData, model: &Mod "type": "function", "function": { "name": tool_result.call.name, - "arguments": tool_result.call.arguments, + "arguments": tool_result.call.arguments.to_string(), }, }) }).collect(); @@ -237,7 +243,7 @@ pub fn openai_build_chat_completions_body(data: ChatCompletionsData, model: &Mod "type": "function", "function": { "name": tool_result.call.name, - "arguments": tool_result.call.arguments, + "arguments": tool_result.call.arguments.to_string(), }, } ] @@ -302,24 +308,24 @@ pub fn openai_extract_chat_completions(data: &Value) -> Result