Skip to content

Commit 856ff47

Browse files
feat: add token usage in CLI (tailcallhq#167)
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
1 parent bbe7cf0 commit 856ff47

12 files changed

Lines changed: 294 additions & 163 deletions

File tree

‎Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎crates/forge_app/src/service/chat.rs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,12 @@ impl Live {
123123
.await
124124
.unwrap();
125125
}
126+
127+
if let Some(usage) = &message.usage {
128+
tx.send(Ok(ChatResponse::Usage(usage.clone())))
129+
.await
130+
.unwrap();
131+
}
126132
}
127133

128134
request = request.add_message(ContextMessage::assistant(

‎crates/forge_domain/src/chat_response.rs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
use serde::Serialize;
22

3-
use crate::{Context, ConversationId, Errata, FinishReason, ToolCallFull, ToolName, ToolResult};
3+
use crate::{
4+
Context, ConversationId, Errata, FinishReason, ToolCallFull, ToolName, ToolResult, Usage,
5+
};
46

57
/// Events that are emitted by the agent for external consumption. This includes
68
/// events for all internal state changes.
@@ -22,4 +24,5 @@ pub enum ChatResponse {
2224
CompleteTitle(String),
2325
Error(Errata),
2426
FinishReason(FinishReason),
27+
Usage(Usage),
2528
}

‎crates/forge_domain/src/message.rs‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,13 @@ use strum_macros::EnumString;
55

66
use super::ToolCall;
77

8+
#[derive(Default, Clone, Debug, Serialize, PartialEq, Eq)]
9+
pub struct Usage {
10+
pub prompt_tokens: u64,
11+
pub completion_tokens: u64,
12+
pub total_tokens: u64,
13+
}
14+
815
/// Represents a message that was received from the LLM provider
916
/// NOTE: Tool call messages are part of the larger Response object and not part
1017
/// of the message.
@@ -14,6 +21,7 @@ pub struct ChatCompletionMessage {
1421
pub content: Option<Content>,
1522
pub tool_call: Vec<ToolCall>,
1623
pub finish_reason: Option<FinishReason>,
24+
pub usage: Option<Usage>,
1725
}
1826

1927
/// Represents partial or full content of a message

‎crates/forge_main/Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ strum = "0.26.3"
1818
strum_macros = "0.26.4"
1919
anyhow = "1.0.95"
2020
chrono = "0.4"
21+
derive_setters = "0.1"
2122
lazy_static = "1.4.0"
2223
serde_json = "1.0"
2324
thiserror = "2.0"

‎crates/forge_main/src/info.rs‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
use std::io;
22

33
use colored::Colorize;
4-
use forge_domain::Environment;
4+
use forge_domain::{Environment, Usage};
55

66
use crate::CONSOLE;
77

8-
pub fn display_info(env: &Environment) -> io::Result<()> {
8+
pub fn display_info(env: &Environment, usage: &Usage) -> io::Result<()> {
99
CONSOLE.newline()?;
1010
CONSOLE.writeln(format!("{} {}", "OS:".bold().bright_yellow(), env.os))?;
1111
CONSOLE.writeln(format!(
@@ -38,5 +38,21 @@ pub fn display_info(env: &Environment) -> io::Result<()> {
3838
env.small_model_id
3939
))?;
4040
CONSOLE.newline()?;
41+
CONSOLE.writeln(format!(
42+
"{} {}",
43+
"Prompt:".bold().bright_yellow(),
44+
usage.prompt_tokens
45+
))?;
46+
CONSOLE.writeln(format!(
47+
"{} {}",
48+
"Completion:".bold().bright_yellow(),
49+
usage.completion_tokens
50+
))?;
51+
CONSOLE.writeln(format!(
52+
"{} {}",
53+
"Total:".bold().bright_yellow(),
54+
usage.total_tokens
55+
))?;
56+
CONSOLE.newline()?;
4157
Ok(())
4258
}
Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use std::error::Error as StdError;
22
use std::path::PathBuf;
33

44
use async_trait::async_trait;
5-
use forge_domain::{Command, UserInput};
5+
use forge_domain::{Command, Usage, UserInput};
66
use inquire::Autocomplete;
77
use tokio::fs;
88

@@ -102,7 +102,8 @@ impl UserInput for Console {
102102
match Command::parse(&text) {
103103
Ok(input) => return Ok(input),
104104
Err(e) => {
105-
CONSOLE.writeln(StatusDisplay::failed(e.to_string()).format())?;
105+
CONSOLE
106+
.writeln(StatusDisplay::failed(e.to_string(), Usage::default()).format())?;
106107
}
107108
}
108109
}

‎crates/forge_main/src/lib.rs‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
pub mod banner;
2-
pub mod command;
32
pub mod console;
43
pub mod info;
4+
pub mod input;
55
mod normalize;
66
pub mod status;
7+
pub mod ui;
78

8-
pub use command::Console;
99
pub use console::CONSOLE;
1010
pub use info::display_info;
11+
pub use input::Console;
1112
pub use status::StatusDisplay;
13+
pub use ui::UI;

‎crates/forge_main/src/main.rs‎

Lines changed: 5 additions & 146 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,6 @@
11
use anyhow::Result;
22
use clap::Parser;
3-
use colored::Colorize;
4-
use forge_app::Routes;
5-
use forge_domain::{ChatRequest, ChatResponse, Command, ModelId, UserInput};
6-
use forge_main::{display_info, Console, StatusDisplay, CONSOLE};
7-
use tokio_stream::StreamExt;
8-
9-
fn context_reset_message(_: &Command) -> String {
10-
"All context was cleared, and we're starting fresh. Please re-add files and details so we can get started.".to_string()
11-
.yellow()
12-
.bold()
13-
.to_string()
14-
}
3+
use forge_main::{banner, UI};
154

165
/// Command line arguments for the application
176
#[derive(Parser)]
@@ -28,141 +17,11 @@ async fn main() -> Result<()> {
2817
let cli = Cli::parse();
2918

3019
// Display the banner in dimmed colors
31-
forge_main::banner::display()?;
32-
33-
let mut current_conversation_id = None;
34-
let mut current_title = None;
35-
let mut current_content = None;
36-
37-
let api = Routes::init()
38-
.await
39-
.map_err(|e| anyhow::anyhow!("Failed to initialize API: {}", e))?;
40-
41-
// Create a Console instance
42-
let console = Console;
43-
44-
// Get initial input from file or prompt
45-
let mut input = match &cli.exec {
46-
Some(ref path) => console.upload(path).await?,
47-
None => console.prompt(None, None).await?,
48-
};
49-
let model = ModelId::from_env(&api.environment().await?);
50-
loop {
51-
match input {
52-
Command::End => break,
53-
Command::New => {
54-
CONSOLE.writeln(context_reset_message(&input))?;
55-
current_conversation_id = None;
56-
current_title = None;
57-
input = console.prompt(None, None).await?;
58-
continue;
59-
}
60-
Command::Reload => {
61-
CONSOLE.writeln(context_reset_message(&input))?;
62-
current_conversation_id = None;
63-
current_title = None;
64-
input = match cli.exec {
65-
Some(ref path) => console.upload(path).await?,
66-
None => console.prompt(None, current_content.as_deref()).await?,
67-
};
68-
continue;
69-
}
70-
Command::Info => {
71-
display_info(&api.environment().await?)?;
72-
input = console.prompt(current_title.as_deref(), None).await?;
73-
continue;
74-
}
75-
Command::Message(ref content) => {
76-
current_content = Some(content.clone());
77-
let chat = ChatRequest {
78-
content: content.clone(),
79-
model: model.clone(),
80-
conversation_id: current_conversation_id,
81-
};
82-
83-
match api.chat(chat).await {
84-
Ok(mut stream) => {
85-
while let Some(message) = stream.next().await {
86-
match message {
87-
Ok(message) => match message {
88-
ChatResponse::Text(text) => {
89-
CONSOLE.write(&text)?;
90-
}
91-
ChatResponse::ToolCallDetected(_) => {}
92-
ChatResponse::ToolCallArgPart(arg) => {
93-
if cli.verbose {
94-
CONSOLE.write(&arg)?;
95-
}
96-
}
97-
ChatResponse::ToolCallStart(tool_call_full) => {
98-
let tool_name = tool_call_full.name.as_str();
99-
CONSOLE.newline()?;
100-
CONSOLE
101-
.writeln(StatusDisplay::execute(tool_name).format())?;
102-
103-
// Convert to JSON and apply dimmed style
104-
let json =
105-
serde_json::to_string_pretty(&tool_call_full.arguments)
106-
.unwrap_or_else(|_| {
107-
"Failed to serialize arguments".to_string()
108-
});
109-
110-
CONSOLE.writeln(format!("{}", json.dimmed()))?;
111-
}
112-
ChatResponse::ToolCallEnd(tool_result) => {
113-
let tool_name = tool_result.name.as_str();
114-
// Always show result content for errors, or in verbose mode
115-
if tool_result.is_error || cli.verbose {
116-
CONSOLE.writeln(format!(
117-
"{}",
118-
tool_result.to_string().dimmed()
119-
))?;
120-
}
121-
let status = if tool_result.is_error {
122-
StatusDisplay::failed(tool_name)
123-
} else {
124-
StatusDisplay::success(tool_name)
125-
};
126-
CONSOLE.write(status.format())?;
127-
}
128-
ChatResponse::ConversationStarted(conversation_id) => {
129-
current_conversation_id = Some(conversation_id);
130-
}
131-
ChatResponse::ModifyContext(_) => {}
132-
ChatResponse::Complete => {}
133-
ChatResponse::Error(err) => {
134-
CONSOLE.writeln(
135-
StatusDisplay::failed(err.to_string()).format(),
136-
)?;
137-
}
138-
ChatResponse::PartialTitle(_) => {}
139-
ChatResponse::CompleteTitle(title) => {
140-
current_title = Some(StatusDisplay::title(title).format());
141-
}
142-
ChatResponse::FinishReason(_) => {}
143-
},
144-
Err(err) => {
145-
CONSOLE
146-
.writeln(StatusDisplay::failed(err.to_string()).format())?;
147-
}
148-
}
149-
}
150-
}
151-
Err(err) => {
152-
CONSOLE.writeln(
153-
StatusDisplay::failed_with(
154-
err.to_string(),
155-
"Failed to establish chat stream",
156-
)
157-
.format(),
158-
)?;
159-
}
160-
}
20+
banner::display()?;
16121

162-
input = console.prompt(current_title.as_deref(), None).await?;
163-
}
164-
}
165-
}
22+
// Initialize and run the UI
23+
let mut ui = UI::new(cli.verbose, cli.exec).await?;
24+
ui.run().await?;
16625

16726
Ok(())
16827
}

‎crates/forge_main/src/status.rs‎

Lines changed: 31 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use colored::Colorize;
2+
use forge_domain::Usage;
23

34
#[derive(Clone)]
45
enum Kind {
@@ -33,51 +34,61 @@ pub struct StatusDisplay {
3334
kind: Kind,
3435
message: String,
3536
error_details: Option<String>,
37+
usage: Usage, // (prompt, completion, total)
3638
}
3739

3840
impl StatusDisplay {
3941
/// Create a status for executing a tool
40-
pub fn execute(message: impl Into<String>) -> Self {
42+
pub fn execute(message: impl Into<String>, usage: Usage) -> Self {
4143
Self {
4244
kind: Kind::Execute,
4345
message: message.into(),
4446
error_details: None,
47+
usage,
4548
}
4649
}
4750

4851
/// Create a success status
49-
pub fn success(message: impl Into<String>) -> Self {
52+
pub fn success(message: impl Into<String>, usage: Usage) -> Self {
5053
Self {
5154
kind: Kind::Success,
5255
message: message.into(),
5356
error_details: None,
57+
usage,
5458
}
5559
}
5660

5761
/// Create a failure status
58-
pub fn failed(message: impl Into<String>) -> Self {
62+
pub fn failed(message: impl Into<String>, usage: Usage) -> Self {
5963
Self {
6064
kind: Kind::Failed,
6165
message: message.into(),
6266
error_details: None,
67+
usage,
6368
}
6469
}
6570

6671
/// Create a failure status with additional details
67-
pub fn failed_with(message: impl Into<String>, details: impl Into<String>) -> Self {
72+
pub fn failed_with(
73+
message: impl Into<String>,
74+
details: impl Into<String>,
75+
usage: Usage,
76+
) -> Self {
6877
Self {
6978
kind: Kind::Failed,
7079
message: message.into(),
7180
error_details: Some(details.into()),
81+
usage,
7282
}
7383
}
7484

75-
/// Create a title status
76-
pub fn title(message: impl Into<String>) -> Self {
85+
/// Create a task status
86+
pub fn task(message: impl Into<String>, usage: Usage) -> Self {
7787
Self {
7888
kind: Kind::Task,
7989
message: message.into(),
8090
error_details: None,
91+
usage,
8192
}
8293
}
8394

@@ -113,7 +124,20 @@ impl StatusDisplay {
113124
};
114125

115126
let timestamp = chrono::Local::now().format("%H:%M:%S%.3f").to_string();
116-
format!("{} {} {} {}", timestamp.dimmed(), icon, label, message)
127+
let mut result = format!("{} {} {} {}", timestamp.dimmed(), icon, label, message);
128+
129+
if self.usage.total_tokens > 0 {
130+
result.push_str(
131+
&format!(
132+
" [tokens {}/{}/{}]",
133+
self.usage.prompt_tokens, self.usage.completion_tokens, self.usage.total_tokens
134+
)
135+
.dimmed()
136+
.to_string(),
137+
);
138+
}
139+
140+
result
117141
}
118142

119143
fn icon(&self) -> &'static str {

0 commit comments

Comments
 (0)