A high-performance inference engine for AI models
Better tool calling rendering in cli (#679)
uuuvnb99a24c1282d
diff --git a/crates/cli/src/interactive/components/history_cell.rs b/crates/cli/src/interactive/components/history_cell.rsindex 34bb9073f..2eb9cb34d 100644--- a/crates/cli/src/interactive/components/history_cell.rs+++ b/crates/cli/src/interactive/components/history_cell.rs@@ -1,8 +1,6 @@use iocraft::prelude::*;use shoji::types::session::{- chat::{ChatReply, ChatReplyStats},- classification::ClassificationOutput,- text_to_speech::TextToSpeechStats,+ chat::ChatReplyStats, classification::ClassificationOutput, text_to_speech::TextToSpeechStats,};use crate::interactive::{@@ -10,6 +8,16 @@ use crate::interactive::{helpers::{SYMBOL_COMMAND, SYMBOL_INPUT, SYMBOL_INPUT_RESULT, SYMBOL_LONG_DASH},};+#[derive(Clone)]+pub enum TranscriptItem {+ Thinking(String),+ ToolCall {+ name: String,+ called: bool,+ },+ Text(String),+}+#[derive(Clone)]pub enum HistoryCellType {Command {@@ -21,8 +29,9 @@ pub enum HistoryCellType {Request {text: String,},- ChatReply {- reply: ChatReply,+ ChatTranscript {+ items: Vec<TranscriptItem>,+ stats: Option<ChatReplyStats>,},ClassificationOutput {output: ClassificationOutput,@@ -84,9 +93,10 @@ pub fn HistoryCell(}}.into(),- Some(HistoryCellType::ChatReply {- reply,- }) => chat_reply_component(reply, theme.subtitle_color, theme.overlay_color(), theme.padding()),+ Some(HistoryCellType::ChatTranscript {+ items,+ stats,+ }) => chat_transcript_component(items, stats, theme.subtitle_color, theme.overlay_color(), theme.padding()),Some(HistoryCellType::ClassificationOutput {output,}) => classification_output_component(output, theme.subtitle_color, theme.padding()),@@ -98,17 +108,13 @@ pub fn HistoryCell(view}-fn chat_reply_component(- reply: ChatReply,+fn chat_transcript_component(+ items: Vec<TranscriptItem>,+ stats: Option<ChatReplyStats>,subtitle_color: Color,overlay_color: Color,padding: u16,) -> AnyElement<'static> {- let text = reply.message.text();- let reasoning =- reply.message.reasoning().map(|content| content.trim().to_string()).filter(|content| !content.is_empty());- let stats = reply.stats.clone();-element! {View(width: 100pct,@@ -119,18 +125,32 @@ fn chat_reply_component(padding_left: padding,padding_right: padding,) {- #(reasoning.map(|content| element! {- View(- width: 100pct,- background_color: Some(overlay_color),- ) {- Text(content: content, color: subtitle_color)+ #(items.into_iter().map(|item| match item {+ TranscriptItem::Thinking(content) => element! {+ View(+ width: 100pct,+ background_color: Some(overlay_color),+ ) {+ Text(content: content, color: subtitle_color)+ }+ }+ .into(),+ TranscriptItem::ToolCall {+ name,+ called,+ } => element! {+ Text(+ content: format!("* {} {}", if called { "called" } else { "calling" }, name),+ color: subtitle_color,+ )+ }+ .into(),+ TranscriptItem::Text(content) => element! {+ Text(content: content)}- }))- #(text.map(|content| element! {- Text(content: content)- }))- #(chat_reply_stats_component(&stats, subtitle_color))+ .into(),+ }).collect::<Vec<AnyElement<'static>>>())+ #(stats.as_ref().map(|stats| chat_reply_stats_component(stats, subtitle_color)))}}.into()diff --git a/crates/cli/src/interactive/components/mod.rs b/crates/cli/src/interactive/components/mod.rsindex de5d2a049..9efc7f36f 100644--- a/crates/cli/src/interactive/components/mod.rs+++ b/crates/cli/src/interactive/components/mod.rs@@ -16,7 +16,7 @@ mod theme;pub use application::{Application, ApplicationState, ModelState};pub use command_input::CommandInput;pub use gradient::Gradient;-pub use history_cell::{HistoryCell, HistoryCellType};+pub use history_cell::{HistoryCell, HistoryCellType, TranscriptItem};pub use loading::Loading;pub use logo::Logo;pub use model_capabilities::{ModelCapabilities, ModelSamplingDefaults, ThinkingSupport};diff --git a/crates/cli/src/interactive/sessions/chat.rs b/crates/cli/src/interactive/sessions/chat.rsindex 8633ebbfe..ab20f2ee7 100644--- a/crates/cli/src/interactive/sessions/chat.rs+++ b/crates/cli/src/interactive/sessions/chat.rs@@ -7,13 +7,13 @@ use nagare::{tool::uzu_tool_function,};use shoji::types::{- basic::CancelToken,+ basic::{CancelToken, ToolCall},model::Model,- session::chat::{ChatConfig, ChatMessage, ChatReply, ChatReplyConfig},+ session::chat::{ChatConfig, ChatMessage, ChatReplyConfig, ChatReplyStats, ChatRole},};use crate::interactive::{- components::{ApplicationState, HistoryCellType},+ components::{ApplicationState, HistoryCellType, TranscriptItem},helpers::HINT_SESSION_INTERRUPT,sessions::SessionState,};@@ -28,7 +28,8 @@ enum ChatSessionStatus {#[derive(Clone)]pub struct ChatSessionState {session: Option<ChatSession>,- pending_reply: Option<ChatReply>,+ pending_items: Vec<TranscriptItem>,+ pending_stats: Option<ChatReplyStats>,cancel_token: Option<CancelToken>,status: ChatSessionStatus,}@@ -37,7 +38,8 @@ impl ChatSessionState {pub fn loading() -> Self {Self {session: None,- pending_reply: None,+ pending_items: Vec::new(),+ pending_stats: None,cancel_token: None,status: ChatSessionStatus::Loading,}@@ -46,7 +48,8 @@ impl ChatSessionState {pub fn idle(session: ChatSession) -> Self {Self {session: Some(session),- pending_reply: None,+ pending_items: Vec::new(),+ pending_stats: None,cancel_token: None,status: ChatSessionStatus::Idle,}@@ -84,8 +87,12 @@ impl SessionState for ChatSessionState {}fn pending_history_cell(&self) -> Option<HistoryCellType> {- self.pending_reply.clone().map(|reply| HistoryCellType::ChatReply {- reply,+ if self.pending_items.is_empty() && self.pending_stats.is_none() {+ return None;+ }+ Some(HistoryCellType::ChatTranscript {+ items: self.pending_items.clone(),+ stats: self.pending_stats.clone(),})}}@@ -164,14 +171,16 @@ pub async fn run_session({let mut state = state.write();if let Some(chat_state) = chat_state_mut(&mut state) {- chat_state.pending_reply = None;+ chat_state.pending_items = Vec::new();+ chat_state.pending_stats = None;chat_state.cancel_token = None;chat_state.status = ChatSessionStatus::Generating;}}+ let history_offset = session.messages().await.len();let stream = session.reply_with_stream(messages, reply_config).await;- let mut latest_reply: Option<ChatReply> = None;+ let mut latest_stats: Option<ChatReplyStats> = None;{let mut state = state.write();if let Some(chat_state) = chat_state_mut(&mut state) {@@ -184,12 +193,14 @@ pub async fn run_session(ChatSessionStreamChunk::Replies {replies,} => {- if let Some(reply) = replies.last().cloned() {- latest_reply = Some(reply.clone());- let mut state = state.write();- if let Some(chat_state) = chat_state_mut(&mut state) {- chat_state.pending_reply = Some(reply);- }+ if let Some(reply) = replies.last() {+ latest_stats = Some(reply.stats.clone());+ }+ let items = build_transcript(&session.messages().await, history_offset);+ let mut state = state.write();+ if let Some(chat_state) = chat_state_mut(&mut state) {+ chat_state.pending_items = items;+ chat_state.pending_stats = latest_stats.clone();}},ChatSessionStreamChunk::Error {@@ -203,23 +214,66 @@ pub async fn run_session(}}+ let final_items = build_transcript(&session.messages().await, history_offset);let mut state = state.write();- let final_reply = if let Some(chat_state) = chat_state_mut(&mut state) {- let final_reply = latest_reply.or_else(|| chat_state.pending_reply.take());- chat_state.pending_reply = None;+ if let Some(chat_state) = chat_state_mut(&mut state) {+ chat_state.pending_items = Vec::new();+ chat_state.pending_stats = None;chat_state.cancel_token = None;chat_state.status = ChatSessionStatus::Idle;- final_reply- } else {- latest_reply- };- if let Some(reply) = final_reply {- state.history.push(HistoryCellType::ChatReply {- reply,+ }+ if !final_items.is_empty() || latest_stats.is_some() {+ state.history.push(HistoryCellType::ChatTranscript {+ items: final_items,+ stats: latest_stats,});}}+/// A tool call is `calling` until its result message shows up in the history,+/// then it becomes `called`.+fn build_transcript(+ messages: &[ChatMessage],+ history_offset: usize,+) -> Vec<TranscriptItem> {+ let messages = &messages[history_offset.min(messages.len())..];+ let mut items = Vec::new();+ for (index, message) in messages.iter().enumerate() {+ if message.role != (ChatRole::Assistant {}) {+ continue;+ }+ if let Some(reasoning) =+ message.reasoning().map(|content| content.trim().to_string()).filter(|content| !content.is_empty())+ {+ items.push(TranscriptItem::Thinking(reasoning));+ }+ if let Some(text) = message.text().filter(|content| !content.is_empty()) {+ items.push(TranscriptItem::Text(text));+ }+ for tool_call in message.tool_calls() {+ items.push(TranscriptItem::ToolCall {+ name: tool_call.name.clone(),+ called: tool_call_called(messages, index, &tool_call),+ });+ }+ }+ items+}++fn tool_call_called(+ messages: &[ChatMessage],+ index: usize,+ tool_call: &ToolCall,+) -> bool {+ messages[index + 1..].iter().any(|message| {+ message.role == (ChatRole::Tool {})+ && message.tool_call_results().iter().any(|(identifier, _, _)| match (&tool_call.identifier, identifier) {+ (Some(call_identifier), Some(result_identifier)) => call_identifier == result_identifier,+ _ => true,+ })+ })+}+fn chat_state(state: &ApplicationState) -> Option<&ChatSessionState> {state.model_state