A high-performance inference engine for AI models
Cli server tool calls (#686)
Aleksandr Golokozc38ed24b2a24
diff --git a/crates/cli/src/server/chat_completions.rs b/crates/cli/src/server/chat_completions.rsindex c707e5e67..aca296f2a 100644--- a/crates/cli/src/server/chat_completions.rs+++ b/crates/cli/src/server/chat_completions.rs@@ -28,13 +28,23 @@ use uzu::{},};-use crate::server::ServerState;+use crate::server::{+ ServerState,+ chat_tool_calls::{+ OaiTool, OaiToolCall, backfill_tool_result_names, choose_tools, insert_tools_message, reply_tool_calls,+ to_tool_call, tool_call_deltas, tool_call_result_block, withhold_stream_text,+ },+};#[derive(Serialize, Deserialize, Clone)]pub struct OaiMessage {pub role: String,#[serde(default)]- pub content: String,+ pub content: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub tool_calls: Option<Vec<OaiToolCall>>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub tool_call_id: Option<String>,}#[derive(Deserialize)]@@ -56,6 +66,11 @@ pub struct ChatCompletionRequest {#[serde(default)]pub response_format: Option<serde_json::Value>,#[serde(default)]+ pub tools: Option<Vec<OaiTool>>,+ // Raw value like response_format: a bad tool_choice is our 400, not Rocket's 422.+ #[serde(default)]+ pub tool_choice: Option<serde_json::Value>,+ #[serde(default)]#[allow(dead_code)]pub model: Option<String>,}@@ -99,12 +114,14 @@ pub struct ChatCompletionResponse {pub usage: ChatCompletionUsage,}-#[derive(Serialize)]+#[derive(Serialize, Default)]struct StreamDelta {#[serde(skip_serializing_if = "Option::is_none")]role: Option<String>,#[serde(skip_serializing_if = "Option::is_none")]content: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ tool_calls: Option<Vec<OaiToolCall>>,}#[derive(Serialize)]@@ -167,11 +184,29 @@ fn to_chat_messages(messages: &[OaiMessage]) -> Vec<ChatMessage> {.iter().map(|message| {let role = ChatRole::from_str(&message.role).unwrap_or(ChatRole::User {});- ChatMessage::for_role(role).with_text(message.content.clone())+ let mut chat_message = ChatMessage::for_role(role);+ if let Some(identifier) = &message.tool_call_id {+ let result = tool_call_result_block(identifier, message.content.clone().unwrap_or_default());+ chat_message = chat_message.with_block(result);+ } else if let Some(content) = &message.content {+ chat_message = chat_message.with_text(content.clone());+ }+ for tool_call in message.tool_calls.iter().flatten() {+ chat_message = chat_message.with_tool_call(to_tool_call(tool_call));+ }+ chat_message}).collect()}+pub(crate) fn build_messages(request: &ChatCompletionRequest) -> Result<Vec<ChatMessage>, String> {+ let tools = choose_tools(request.tools.as_deref(), request.tool_choice.as_ref())?;+ let mut messages = to_chat_messages(&request.messages);+ backfill_tool_result_names(&mut messages);+ insert_tools_message(&mut messages, &tools);+ Ok(messages)+}+#[derive(Debug, PartialEq, Eq)]enum ResponseFormatError {GrammarUnsupported,@@ -204,15 +239,19 @@ impl ResponseFormatError {}}-fn request_error_response(error: ResponseFormatError) -> ChatCompletionResult {+fn invalid_request_response(+ param: &str,+ code: &str,+ message: String,+) -> ChatCompletionResult {ChatCompletionResult::Error(status::Custom(Status::BadRequest,Json(OaiErrorResponse {error: OaiError {- message: error.message(),+ message,kind: "invalid_request_error".to_string(),- param: Some("response_format".to_string()),- code: Some(error.code().to_string()),+ param: Some(param.to_string()),+ code: Some(code.to_string()),},}),))@@ -310,7 +349,9 @@ fn error_response(index: 0,message: OaiMessage {role: "assistant".to_string(),- content: format!("Error: {message}"),+ content: Some(format!("Error: {message}")),+ tool_calls: None,+ tool_call_id: None,},finish_reason: "stop".to_string(),}],@@ -356,24 +397,34 @@ async fn run_blocking(match session.reply(messages, config).await {Ok(replies) => match replies.last() {- Some(reply) => ChatCompletionResponse {- id,- object: "chat.completion".to_string(),- created,- model,- choices: vec![ChatCompletionChoice {- index: 0,- message: OaiMessage {- role: "assistant".to_string(),- content: reply.message.text().unwrap_or_default(),- },- finish_reason: reply- .finish_reason- .as_ref()- .map(map_finish_reason)- .unwrap_or_else(|| "stop".to_string()),- }],- usage: usage_from_stats(&reply.stats),+ Some(reply) => {+ let tool_calls = reply_tool_calls(&reply.message);+ // OpenAI sets content to null (not "") on tool call replies.+ let content = reply.message.text().or_else(|| tool_calls.is_none().then(String::new));+ let mut finish_reason =+ reply.finish_reason.as_ref().map(map_finish_reason).unwrap_or_else(|| "stop".to_string());+ // A call the parser could not finalize yields ToolCalls with nothing to execute.+ // Clients would stall on an absent tool_calls array, so report stop.+ if tool_calls.is_none() && finish_reason == "tool_calls" {+ finish_reason = "stop".to_string();+ }+ ChatCompletionResponse {+ id,+ object: "chat.completion".to_string(),+ created,+ model,+ choices: vec![ChatCompletionChoice {+ index: 0,+ message: OaiMessage {+ role: "assistant".to_string(),+ content,+ tool_calls,+ tool_call_id: None,+ },+ finish_reason,+ }],+ usage: usage_from_stats(&reply.stats),+ }},None => error_response(id, model, created, "No response generated"),},@@ -397,8 +448,8 @@ async fn run_stream(&model,created,StreamDelta {- role: None,content: Some(format!("Error: {error}")),+ ..StreamDelta::default()},Some("stop".to_string()),None,@@ -413,14 +464,17 @@ async fn run_stream(created,StreamDelta {role: Some("assistant".to_string()),- content: None,+ ..StreamDelta::default()},None,None,)));+ let has_tools = messages.iter().any(|message| !message.tool_namespaces().is_empty());let stream = session.reply_with_stream(messages, config).await;let mut emitted = 0usize;+ let mut emitted_tool_calls = 0usize;+ let mut final_text = String::new();let mut finish_reason = "stop".to_string();let mut usage = ChatCompletionUsage::default();let mut errored = false;@@ -435,7 +489,7 @@ async fn run_stream(};let text = reply.message.text().unwrap_or_default();let start = (emitted..=text.len()).find(|&index| text.is_char_boundary(index)).unwrap_or(text.len());- if text.len() > start {+ if !withhold_stream_text(has_tools, &text) && text.len() > start {let delta = text[start..].to_string();emitted = text.len();let sent = sender.send(Event::data(chunk_json(@@ -443,8 +497,8 @@ async fn run_stream(&model,created,StreamDelta {- role: None,content: Some(delta),+ ..StreamDelta::default()},None,None,@@ -453,10 +507,32 @@ async fn run_stream(return;}}++ let tool_calls = reply.message.tool_calls();+ if tool_calls.len() > emitted_tool_calls {+ let delta = tool_call_deltas(&tool_calls, emitted_tool_calls);+ emitted_tool_calls = tool_calls.len();+ let sent = sender.send(Event::data(chunk_json(+ &id,+ &model,+ created,+ StreamDelta {+ tool_calls: Some(delta),+ ..StreamDelta::default()+ },+ None,+ None,+ )));+ if sent.is_err() {+ return;+ }+ }+if let Some(reason) = &reply.finish_reason {finish_reason = map_finish_reason(reason);}usage = usage_from_stats(&reply.stats);+ final_text = text;},ChatSessionStreamChunk::Error {error,@@ -467,8 +543,8 @@ async fn run_stream(&model,created,StreamDelta {- role: None,content: Some(format!("Error: {error}")),+ ..StreamDelta::default()},Some("stop".to_string()),None,@@ -479,14 +555,36 @@ async fn run_stream(}if !errored {+ // Flush withheld text that survived in the final message.+ // Text that was reclassified into tool calls is gone from it and stays suppressed.+ let start =+ (emitted..=final_text.len()).find(|&index| final_text.is_char_boundary(index)).unwrap_or(final_text.len());+ if final_text.len() > start {+ let sent = sender.send(Event::data(chunk_json(+ &id,+ &model,+ created,+ StreamDelta {+ content: Some(final_text[start..].to_string()),+ ..StreamDelta::default()+ },+ None,+ None,+ )));+ if sent.is_err() {+ return;+ }+ }+ // Same guard as the blocking path: candidates that never finalized produce a ToolCalls finish with+ // no emitted tool call deltas, which reads as stop.+ if emitted_tool_calls == 0 && finish_reason == "tool_calls" {+ finish_reason = "stop".to_string();+ }let _ = sender.send(Event::data(chunk_json(&id,&model,created,- StreamDelta {- role: None,- content: None,- },+ StreamDelta::default(),Some(finish_reason),Some(usage),)));@@ -508,9 +606,12 @@ pub async fn handle_chat_completions(let config = match build_reply_config(&request) {Ok(config) => config,- Err(error) => return request_error_response(error),+ Err(error) => return invalid_request_response("response_format", error.code(), error.message()),+ };+ let messages = match build_messages(&request) {+ Ok(messages) => messages,+ Err(detail) => return invalid_request_response("tool_choice", "invalid_tool_choice", detail),};- let messages = to_chat_messages(&request.messages);if is_stream {let session = Arc::clone(&state.session);diff --git a/crates/cli/src/server/chat_tool_calls.rs b/crates/cli/src/server/chat_tool_calls.rsnew file mode 100644index 000000000..4b6339353--- /dev/null+++ b/crates/cli/src/server/chat_tool_calls.rs@@ -0,0 +1,216 @@+use std::collections::HashMap;++use serde::{Deserialize, Serialize};+use uzu::types::{+ basic::{ToolCall, ToolDescription, ToolFunction, ToolNamespace, Value},+ session::chat::{ChatContentBlock, ChatMessage, ChatRole},+};++#[derive(Serialize, Deserialize, Clone)]+pub struct OaiToolCall {+ // Present only in streaming deltas, per the OpenAI wire format.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub index: Option<usize>,+ pub id: String,+ #[serde(rename = "type", default)]+ pub kind: String,+ pub function: OaiFunctionCall,+}++#[derive(Serialize, Deserialize, Clone)]+pub struct OaiFunctionCall {+ pub name: String,+ pub arguments: String,+}++#[derive(Deserialize)]+pub struct OaiTool {+ pub function: OaiToolFunction,+}++#[derive(Deserialize)]+pub struct OaiToolFunction {+ pub name: String,+ #[serde(default)]+ pub description: String,+ #[serde(default)]+ pub parameters: Option<Value>,+}++#[derive(Deserialize)]+#[serde(untagged)]+enum OaiToolChoice {+ Mode(String),+ Function {+ function: OaiToolChoiceFunction,+ },+}++#[derive(Deserialize)]+struct OaiToolChoiceFunction {+ name: String,+}++// Applies tool_choice to the declared tools: "none" hides all of them and a forced function+// exposes only the named one. Declarations are the only lever a local model has, so+// "required" cannot compel a call and keeps the full set like "auto".+pub fn choose_tools<'t>(+ tools: Option<&'t [OaiTool]>,+ tool_choice: Option<&serde_json::Value>,+) -> Result<Vec<&'t OaiTool>, String> {+ let tools: Vec<&OaiTool> = tools.unwrap_or_default().iter().collect();+ let Some(tool_choice) = tool_choice else {+ return Ok(tools);+ };+ let choice = serde_json::from_value::<OaiToolChoice>(tool_choice.clone())+ .map_err(|error| format!("tool_choice is not a recognized value: {error}"))?;+ match choice {+ OaiToolChoice::Mode(mode) => match mode.as_str() {+ "none" => Ok(vec![]),+ "auto" | "required" => Ok(tools),+ other => {+ Err(format!("tool_choice must be \"none\", \"auto\", \"required\" or a function object, got {other:?}"))+ },+ },+ OaiToolChoice::Function {+ function,+ } => {+ let selected: Vec<&OaiTool> =+ tools.into_iter().filter(|tool| tool.function.name == function.name).collect();+ if selected.is_empty() {+ return Err(format!("tool_choice names function {:?} but tools does not declare it", function.name));+ }+ Ok(selected)+ },+ }+}++pub fn to_tool_call(tool_call: &OaiToolCall) -> ToolCall {+ // An invalid Value fails serialization inside template rendering and errors the whole request,+ // so arguments that are not valid JSON are re-wrapped instead of passed through.+ let arguments = &tool_call.function.arguments;+ let json = match serde_json::from_str::<serde_json::Value>(arguments) {+ Ok(_) => arguments.clone(),+ Err(_) if arguments.trim().is_empty() => "{}".to_string(),+ Err(_) => serde_json::Value::String(arguments.clone()).to_string(),+ };+ ToolCall {+ identifier: Some(tool_call.id.clone()),+ name: tool_call.function.name.clone(),+ arguments: Value {+ json,+ },+ }+}++pub fn tool_call_result_block(+ identifier: &str,+ content: String,+) -> ChatContentBlock {+ let value = serde_json::from_str::<serde_json::Value>(&content).unwrap_or(serde_json::Value::String(content));+ ChatContentBlock::ToolCallResult {+ identifier: Some(identifier.to_string()),+ name: None,+ value: value.into(),+ }+}++fn tools_message(tools: &[&OaiTool]) -> ChatMessage {+ let descriptions = tools+ .iter()+ .map(|tool| ToolDescription::Function {+ tool_function: ToolFunction {+ name: tool.function.name.clone(),+ description: tool.function.description.clone(),+ parameters: tool.function.parameters.clone(),+ return_definition: None,+ },+ })+ .collect();+ ChatMessage::developer().with_tool_namespaces(vec![ToolNamespace {+ name: "functions".to_string(),+ description: None,+ tools: descriptions,+ }])+}++// OpenAI tool messages carry only tool_call_id, but some chat templates render tool+// results as {name, response} pairs, so the name is recovered from the matching call.+pub fn backfill_tool_result_names(messages: &mut [ChatMessage]) {+ let names: HashMap<String, String> = messages+ .iter()+ .flat_map(|message| message.tool_calls())+ .filter_map(|tool_call| Some((tool_call.identifier?, tool_call.name)))+ .collect();+ for message in messages.iter_mut() {+ for block in message.content.iter_mut() {+ if let ChatContentBlock::ToolCallResult {+ identifier: Some(identifier),+ name,+ ..+ } = block+ && name.is_none()+ {+ *name = names.get(identifier.as_str()).cloned();+ }+ }+ }+}++pub fn insert_tools_message(+ messages: &mut Vec<ChatMessage>,+ tools: &[&OaiTool],+) {+ if tools.is_empty() {+ return;+ }+ let position = messages.iter().position(|message| message.role != (ChatRole::System {})).unwrap_or(messages.len());+ messages.insert(position, tools_message(tools));+}++pub fn oai_tool_call(+ index: Option<usize>,+ tool_call: &ToolCall,+) -> OaiToolCall {+ OaiToolCall {+ index,+ id: tool_call.identifier.clone().unwrap_or_default(),+ kind: "function".to_string(),+ function: OaiFunctionCall {+ name: tool_call.name.clone(),+ arguments: tool_call.arguments.json.clone(),+ },+ }+}++pub fn reply_tool_calls(message: &ChatMessage) -> Option<Vec<OaiToolCall>> {+ let tool_calls = message.tool_calls();+ (!tool_calls.is_empty()).then(|| tool_calls.iter().map(|tool_call| oai_tool_call(None, tool_call)).collect())+}++// Bare-JSON formats (e.g. llama-3) stream a tool call as ordinary text and only rewrite+// it into a ToolCall block when the turn finishes, so JSON-looking text must be withheld+// from delta.content until then; whatever survives in the final message is flushed at the end.+pub fn withhold_stream_text(+ has_tools: bool,+ text: &str,+) -> bool {+ let trimmed = text.trim_start();+ has_tools && (trimmed.is_empty() || trimmed.starts_with('{'))+}++pub fn tool_call_deltas(+ tool_calls: &[ToolCall],+ emitted: usize,+) -> Vec<OaiToolCall> {+ tool_calls+ .iter()+ .enumerate()+ .skip(emitted)+ .map(|(index, tool_call)| oai_tool_call(Some(index), tool_call))+ .collect()+}++#[cfg(test)]+#[path = "../../unit/server/chat_tool_calls_test.rs"]+mod tests;diff --git a/crates/cli/src/server/mod.rs b/crates/cli/src/server/mod.rsindex 3b2e32f04..69b688e3c 100644--- a/crates/cli/src/server/mod.rs+++ b/crates/cli/src/server/mod.rs@@ -1,4 +1,5 @@pub mod chat_completions;+pub mod chat_tool_calls;pub mod models;pub mod runner;pub mod state;diff --git a/crates/cli/unit/server/chat_completions_test.rs b/crates/cli/unit/server/chat_completions_test.rsindex 6b142e521..34c061db7 100644--- a/crates/cli/unit/server/chat_completions_test.rs+++ b/crates/cli/unit/server/chat_completions_test.rs@@ -78,7 +78,8 @@ fn response_format_json_schema_rejects_invalid_schema() {#[test]fn response_format_validation_errors_are_request_errors() {- match request_error_response(ResponseFormatError::GrammarUnsupported) {+ let error = ResponseFormatError::GrammarUnsupported;+ match invalid_request_response("response_format", error.code(), error.message()) {ChatCompletionResult::Error(_) => {},ChatCompletionResult::Json(_) | ChatCompletionResult::Stream(_) => {panic!("response_format validation errors should be request errors")@@ -99,7 +100,8 @@ fn malformed_response_format_passes_json_extraction() {#[rocket::get("/err")]fn err_route() -> ChatCompletionResult {- request_error_response(ResponseFormatError::InvalidResponseFormat("bad".to_string()))+ let error = ResponseFormatError::InvalidResponseFormat("bad".to_string());+ invalid_request_response("response_format", error.code(), error.message())}#[test]diff --git a/crates/cli/unit/server/chat_tool_calls_test.rs b/crates/cli/unit/server/chat_tool_calls_test.rsnew file mode 100644index 000000000..5d6fa128b--- /dev/null+++ b/crates/cli/unit/server/chat_tool_calls_test.rs@@ -0,0 +1,142 @@+use super::*;+use crate::server::chat_completions::{ChatCompletionRequest, build_messages};++fn request(json: &str) -> ChatCompletionRequest {+ serde_json::from_str(json).expect("valid request json")+}++fn messages(json: &str) -> Vec<ChatMessage> {+ build_messages(&request(json)).expect("valid request")+}++#[test]+fn tools_become_developer_message_after_system() {+ let messages = messages(+ r#"{+ "messages":[{"role":"system","content":"be nice"},{"role":"user","content":"hi"}],+ "tools":[{"type":"function","function":{"name":"get_time","description":"Get time","parameters":{"type":"object","properties":{}}}}]+ }"#,+ );++ assert_eq!(messages.len(), 3);+ assert_eq!(messages[1].role, ChatRole::Developer {});+ let namespaces = messages[1].tool_namespaces();+ assert_eq!(namespaces.len(), 1);+ assert_eq!(namespaces[0].name, "functions");+ let ToolDescription::Function {+ tool_function,+ } = &namespaces[0].tools[0];+ assert_eq!(tool_function.name, "get_time");+}++#[test]+fn tool_call_round_trip_maps_to_chat_blocks() {+ let messages = messages(+ r#"{+ "messages":[+ {"role":"user","content":"what time is it?"},+ {"role":"assistant","content":null,"tool_calls":[{"id":"call_1","type":"function","function":{"name":"get_time","arguments":"{}"}}]},+ {"role":"tool","tool_call_id":"call_1","content":"{\"time\":\"17:03\"}"}+ ]+ }"#,+ );++ assert_eq!(messages.len(), 3);+ let tool_calls = messages[1].tool_calls();+ assert_eq!(tool_calls.len(), 1);+ assert_eq!(tool_calls[0].identifier.as_deref(), Some("call_1"));+ assert_eq!(tool_calls[0].name, "get_time");++ assert_eq!(messages[2].role, ChatRole::Tool {});+ let results = messages[2].tool_call_results();+ assert_eq!(results.len(), 1);+ assert_eq!(results[0].0.as_deref(), Some("call_1"));+ assert_eq!(results[0].1.as_deref(), Some("get_time"), "result name should be backfilled from the matching call");+}++#[test]+fn invalid_tool_call_arguments_stay_serializable() {+ let call = |arguments: &str| {+ to_tool_call(&OaiToolCall {+ index: None,+ id: "call_1".to_string(),+ kind: "function".to_string(),+ function: OaiFunctionCall {+ name: "get_time".to_string(),+ arguments: arguments.to_string(),+ },+ })+ };++ assert_eq!(call(r#"{"a":1}"#).arguments.json, r#"{"a":1}"#);+ assert_eq!(call("").arguments.json, "{}");+ assert_eq!(call(r#"{"a":"#).arguments.json, r#""{\"a\":""#);+ for arguments in ["", r#"{"a":"#] {+ serde_json::to_value(&call(arguments).arguments).expect("arguments should stay serializable");+ }+}++#[test]+fn tool_choice_controls_exposed_tools() {+ const TOOLS: &str = r#""tools":[+ {"type":"function","function":{"name":"get_time","description":"Get time"}},+ {"type":"function","function":{"name":"get_weather","description":"Get weather"}}+ ]"#;+ let with_choice =+ |choice: &str| format!(r#"{{"messages":[{{"role":"user","content":"hi"}}],{TOOLS},"tool_choice":{choice}}}"#);+ let exposed = |choice: &str| -> Vec<String> {+ messages(&with_choice(choice))+ .iter()+ .flat_map(|message| message.tool_namespaces())+ .flat_map(|namespace| namespace.tools)+ .map(+ |ToolDescription::Function {+ tool_function,+ }| tool_function.name,+ )+ .collect()+ };++ assert_eq!(exposed(r#""auto""#), ["get_time", "get_weather"]);+ assert_eq!(exposed(r#""required""#), ["get_time", "get_weather"]);+ assert_eq!(exposed(r#""none""#), Vec::<String>::new());+ assert_eq!(exposed(r#"{"type":"function","function":{"name":"get_weather"}}"#), ["get_weather"]);++ let unknown_function = with_choice(r#"{"type":"function","function":{"name":"missing"}}"#);+ assert!(build_messages(&request(&unknown_function)).is_err(), "undeclared forced function should be rejected");+ let bogus_mode = with_choice(r#""sometimes""#);+ assert!(build_messages(&request(&bogus_mode)).is_err(), "unrecognized tool_choice should be rejected");+}++#[test]+fn json_looking_stream_text_is_withheld_while_tools_are_declared() {+ // Undecided (empty / leading whitespace) or JSON-looking text may still be+ // reclassified into a tool call, so it must not stream.+ assert!(withhold_stream_text(true, ""));+ assert!(withhold_stream_text(true, " "));+ assert!(withhold_stream_text(true, r#" {"name": "get_time", "parameters"#));++ // Prose can never be rewritten; without tools no rewrite happens at all.+ assert!(!withhold_stream_text(true, "The time is"));+ assert!(!withhold_stream_text(false, r#"{"name": "get_time"}"#));+}++#[test]+fn reply_tool_calls_serialize_in_openai_format() {+ let tool_call = ToolCall {+ identifier: Some("call_1".to_string()),+ name: "get_time".to_string(),+ arguments: Value {+ json: "{}".to_string(),+ },+ };++ let response = serde_json::to_value(oai_tool_call(None, &tool_call)).expect("serializable tool call");+ assert_eq!(+ response,+ serde_json::json!({"id":"call_1","type":"function","function":{"name":"get_time","arguments":"{}"}})+ );++ let delta = serde_json::to_value(oai_tool_call(Some(0), &tool_call)).expect("serializable tool call delta");+ assert_eq!(delta["index"], 0);+}