-
Notifications
You must be signed in to change notification settings - Fork 2.5k
feat: implement async token counter with network resilience and performance optimizations #3111
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
648b2b9
feat: implement async token counter with caching for optimal performance
95e5e8c
perf: optimize async token counter with high-impact performance impro…
b624590
fix: resolve clippy warnings and finalize async token counter
45ee822
feat: add robust network failure handling to async token counter
568882d
fmt, fix tests
salman1993 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| /// Demo showing the async token counter improvement | ||
| /// | ||
| /// This example demonstrates the key improvement: no blocking runtime creation | ||
| /// | ||
| /// BEFORE (blocking): | ||
| /// ```rust | ||
| /// let content = tokio::runtime::Runtime::new()?.block_on(async { | ||
| /// let response = reqwest::get(&file_url).await?; | ||
| /// // ... download logic | ||
| /// })?; | ||
| /// ``` | ||
| /// | ||
| /// AFTER (async): | ||
| /// ```rust | ||
| /// let client = reqwest::Client::new(); | ||
| /// let response = client.get(&file_url).send().await?; | ||
| /// let bytes = response.bytes().await?; | ||
| /// tokio::fs::write(&file_path, bytes).await?; | ||
| /// ``` | ||
| use goose::token_counter::{create_async_token_counter, TokenCounter}; | ||
| use std::time::Instant; | ||
|
|
||
| #[tokio::main] | ||
| async fn main() -> Result<(), Box<dyn std::error::Error>> { | ||
| println!("🚀 Async Token Counter Demo"); | ||
| println!("==========================="); | ||
|
|
||
| // Test text samples | ||
| let samples = vec![ | ||
| "Hello, world!", | ||
| "This is a longer text sample for tokenization testing.", | ||
| "The quick brown fox jumps over the lazy dog.", | ||
| "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", | ||
| "async/await patterns eliminate blocking operations", | ||
| ]; | ||
|
|
||
| println!("\n📊 Performance Comparison"); | ||
| println!("-------------------------"); | ||
|
|
||
| // Test original TokenCounter | ||
| let start = Instant::now(); | ||
| let sync_counter = TokenCounter::new("Xenova--gpt-4o"); | ||
| let sync_init_time = start.elapsed(); | ||
|
|
||
| let start = Instant::now(); | ||
| let mut sync_total = 0; | ||
| for sample in &samples { | ||
| sync_total += sync_counter.count_tokens(sample); | ||
| } | ||
| let sync_count_time = start.elapsed(); | ||
|
|
||
| println!("🔴 Synchronous TokenCounter:"); | ||
| println!(" Init time: {:?}", sync_init_time); | ||
| println!(" Count time: {:?}", sync_count_time); | ||
| println!(" Total tokens: {}", sync_total); | ||
|
|
||
| // Test AsyncTokenCounter | ||
| let start = Instant::now(); | ||
| let async_counter = create_async_token_counter("Xenova--gpt-4o").await?; | ||
| let async_init_time = start.elapsed(); | ||
|
|
||
| let start = Instant::now(); | ||
| let mut async_total = 0; | ||
| for sample in &samples { | ||
| async_total += async_counter.count_tokens(sample); | ||
| } | ||
| let async_count_time = start.elapsed(); | ||
|
|
||
| println!("\n🟢 Async TokenCounter:"); | ||
| println!(" Init time: {:?}", async_init_time); | ||
| println!(" Count time: {:?}", async_count_time); | ||
| println!(" Total tokens: {}", async_total); | ||
| println!(" Cache size: {}", async_counter.cache_size()); | ||
|
|
||
| // Test caching benefit | ||
| let start = Instant::now(); | ||
| let mut cached_total = 0; | ||
| for sample in &samples { | ||
| cached_total += async_counter.count_tokens(sample); // Should hit cache | ||
| } | ||
| let cached_time = start.elapsed(); | ||
|
|
||
| println!("\n⚡ Cached TokenCounter (2nd run):"); | ||
| println!(" Count time: {:?}", cached_time); | ||
| println!(" Total tokens: {}", cached_total); | ||
| println!(" Cache size: {}", async_counter.cache_size()); | ||
|
|
||
| // Verify same results | ||
| assert_eq!(sync_total, async_total); | ||
| assert_eq!(async_total, cached_total); | ||
|
|
||
| println!("\n✅ Key Improvements:"); | ||
| println!(" • No blocking runtime creation (eliminates deadlock risk)"); | ||
| println!(" • Global tokenizer caching with DashMap (lock-free concurrent access)"); | ||
| println!(" • Fast AHash for better cache performance"); | ||
| println!(" • Cache size management (prevents unbounded growth)"); | ||
| println!( | ||
| " • Token result caching ({}x faster on repeated text)", | ||
| async_count_time.as_nanos() / cached_time.as_nanos().max(1) | ||
| ); | ||
| println!(" • Proper async patterns throughout"); | ||
| println!(" • Robust network failure handling with exponential backoff"); | ||
| println!(" • Download validation and corruption detection"); | ||
| println!(" • Progress reporting for large tokenizer downloads"); | ||
| println!(" • Smart retry logic (3 attempts, server errors only)"); | ||
|
|
||
| Ok(()) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,7 +2,11 @@ use std::sync::Arc; | |
|
|
||
| use mcp_core::Tool; | ||
|
|
||
| use crate::{message::Message, providers::base::Provider, token_counter::TokenCounter}; | ||
| use crate::{ | ||
| message::Message, | ||
| providers::base::Provider, | ||
| token_counter::{AsyncTokenCounter, TokenCounter}, | ||
| }; | ||
|
|
||
| const ESTIMATE_FACTOR: f32 = 0.7; | ||
| const SYSTEM_PROMPT_TOKEN_OVERHEAD: usize = 3_000; | ||
|
|
@@ -28,6 +32,19 @@ pub fn get_messages_token_counts(token_counter: &TokenCounter, messages: &[Messa | |
| .collect() | ||
| } | ||
|
|
||
| /// Async version of get_messages_token_counts for better performance | ||
| pub fn get_messages_token_counts_async( | ||
| token_counter: &AsyncTokenCounter, | ||
| messages: &[Message], | ||
| ) -> Vec<usize> { | ||
| // Calculate current token count of each message, use count_chat_tokens to ensure we | ||
| // capture the full content of the message, include ToolRequests and ToolResponses | ||
| messages | ||
| .iter() | ||
| .map(|msg| token_counter.count_chat_tokens("", std::slice::from_ref(msg), &[])) | ||
| .collect() | ||
| } | ||
|
|
||
| // These are not being used now but could be useful in the future | ||
|
|
||
| #[allow(dead_code)] | ||
|
|
@@ -55,3 +72,23 @@ pub fn get_token_counts( | |
| messages: messages_token_count, | ||
| } | ||
| } | ||
|
|
||
| /// Async version of get_token_counts for better performance | ||
| #[allow(dead_code)] | ||
| pub fn get_token_counts_async( | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ^ same comment - async in fn name might be a typo |
||
| token_counter: &AsyncTokenCounter, | ||
| messages: &mut [Message], | ||
| system_prompt: &str, | ||
| tools: &mut Vec<Tool>, | ||
| ) -> ChatTokenCounts { | ||
| // Take into account the system prompt (includes goosehints), and our tools input | ||
| let system_prompt_token_count = token_counter.count_tokens(system_prompt); | ||
| let tools_token_count = token_counter.count_tokens_for_tools(tools.as_slice()); | ||
| let messages_token_count = get_messages_token_counts_async(token_counter, messages); | ||
|
|
||
| ChatTokenCounts { | ||
| system: system_prompt_token_count, | ||
| tools: tools_token_count, | ||
| messages: messages_token_count, | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
async in fn name might be a typo