-
Notifications
You must be signed in to change notification settings - Fork 4
feat: use tokie for accurate token counting #31
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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -163,13 +163,19 @@ impl EmbeddingProvider for GeminiProvider { | |
| let latency_ms = start.elapsed().as_secs_f64() * 1000.0; | ||
| let dimensions = embedding_vectors.first().map(|e| e.len()).unwrap_or(0); | ||
|
|
||
| // Gemini doesn't return token count, estimate based on input | ||
| // Rough estimate: 1 token per 5 characters | ||
| let estimated_tokens: u64 = request | ||
| .inputs | ||
| .iter() | ||
| .map(|s| (s.len() as u64 / 5).max(1)) | ||
| .sum(); | ||
| let inputs_for_counting = request.inputs.clone(); | ||
| let model_for_counting = request.model.clone(); | ||
| let estimated_tokens = tokio::task::spawn_blocking(move || { | ||
| crate::tokenizer::count_tokens_for_model( | ||
| "gemini", | ||
| &model_for_counting, | ||
| &inputs_for_counting, | ||
| ) | ||
| }) | ||
| .await | ||
| .unwrap_or_else(|_| { | ||
| crate::tokenizer::fallback_count(&request.inputs) | ||
| }); | ||
|
Comment on lines
+175
to
+178
|
||
|
|
||
| let cost = calculate_cost(&request.model, estimated_tokens); | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,80 @@ | ||||||||||||||||||||||||||||||||||||||||||||||||||
| use std::collections::HashMap; | ||||||||||||||||||||||||||||||||||||||||||||||||||
| use std::sync::{Arc, Mutex}; | ||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||
| use once_cell::sync::Lazy; | ||||||||||||||||||||||||||||||||||||||||||||||||||
| use tokie::Tokenizer; | ||||||||||||||||||||||||||||||||||||||||||||||||||
| use tracing::warn; | ||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||
| use crate::catalog::get_model; | ||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||
| static TOKENIZER_CACHE: Lazy<Mutex<HashMap<String, Arc<Tokenizer>>>> = | ||||||||||||||||||||||||||||||||||||||||||||||||||
| Lazy::new(|| Mutex::new(HashMap::new())); | ||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||
| pub fn count_tokens_for_model(provider: &str, model: &str, texts: &[String]) -> u64 { | ||||||||||||||||||||||||||||||||||||||||||||||||||
| let tokenizer_info = match get_model(provider, model) { | ||||||||||||||||||||||||||||||||||||||||||||||||||
| Some(info) => match info.tokenizer { | ||||||||||||||||||||||||||||||||||||||||||||||||||
| Some(t) => t, | ||||||||||||||||||||||||||||||||||||||||||||||||||
| None => return fallback_count(texts), | ||||||||||||||||||||||||||||||||||||||||||||||||||
| }, | ||||||||||||||||||||||||||||||||||||||||||||||||||
| None => return fallback_count(texts), | ||||||||||||||||||||||||||||||||||||||||||||||||||
| }; | ||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||
| let repo_name = match tokenizer_info.engine.as_str() { | ||||||||||||||||||||||||||||||||||||||||||||||||||
| "huggingface" => tokenizer_info.name.clone(), | ||||||||||||||||||||||||||||||||||||||||||||||||||
| "tiktoken" => match tiktoken_to_repo(&tokenizer_info.name) { | ||||||||||||||||||||||||||||||||||||||||||||||||||
| Some(repo) => repo.to_string(), | ||||||||||||||||||||||||||||||||||||||||||||||||||
| None => return fallback_count(texts), | ||||||||||||||||||||||||||||||||||||||||||||||||||
| }, | ||||||||||||||||||||||||||||||||||||||||||||||||||
| _ => return fallback_count(texts), | ||||||||||||||||||||||||||||||||||||||||||||||||||
| }; | ||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||
| match get_or_load_tokenizer(&repo_name) { | ||||||||||||||||||||||||||||||||||||||||||||||||||
| Some(tokenizer) => { | ||||||||||||||||||||||||||||||||||||||||||||||||||
| let refs: Vec<&str> = texts.iter().map(|s| s.as_str()).collect(); | ||||||||||||||||||||||||||||||||||||||||||||||||||
| tokenizer.count_tokens_batch(&refs).iter().sum::<usize>() as u64 | ||||||||||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||||||||||
| None => fallback_count(texts), | ||||||||||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||
| fn get_or_load_tokenizer(name: &str) -> Option<Arc<Tokenizer>> { | ||||||||||||||||||||||||||||||||||||||||||||||||||
| let mut cache = TOKENIZER_CACHE.lock().ok()?; | ||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||
| if let Some(tok) = cache.get(name) { | ||||||||||||||||||||||||||||||||||||||||||||||||||
| return Some(Arc::clone(tok)); | ||||||||||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||
| match Tokenizer::from_pretrained(name) { | ||||||||||||||||||||||||||||||||||||||||||||||||||
| Ok(tok) => { | ||||||||||||||||||||||||||||||||||||||||||||||||||
| let tok = Arc::new(tok); | ||||||||||||||||||||||||||||||||||||||||||||||||||
|
Comment on lines
+41
to
+49
|
||||||||||||||||||||||||||||||||||||||||||||||||||
| let mut cache = TOKENIZER_CACHE.lock().ok()?; | |
| if let Some(tok) = cache.get(name) { | |
| return Some(Arc::clone(tok)); | |
| } | |
| match Tokenizer::from_pretrained(name) { | |
| Ok(tok) => { | |
| let tok = Arc::new(tok); | |
| { | |
| let cache = TOKENIZER_CACHE.lock().ok()?; | |
| if let Some(tok) = cache.get(name) { | |
| return Some(Arc::clone(tok)); | |
| } | |
| } | |
| match Tokenizer::from_pretrained(name) { | |
| Ok(tok) => { | |
| let tok = Arc::new(tok); | |
| let mut cache = TOKENIZER_CACHE.lock().ok()?; | |
| if let Some(existing) = cache.get(name) { | |
| return Some(Arc::clone(existing)); | |
| } |
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.
In the
spawn_blocking(...).awaiterror path, the fallback callscrate::tokenizer::fallback_count(&request.inputs)on the async runtime thread. Sincefallback_countmay attempt to load a tokenizer (and uses a blockingstd::sync::Mutex), this can block the runtime thread. Consider making the error-path fallback a purelen/5estimate, or runningfallback_countinsidespawn_blockingtoo.