lc_core/token_counter/
tracker.rs1use std::sync::Arc;
4
5use crate::language_models::LLMResult;
6use crate::{BaseChatModel, RunnableConfig};
7use lc_schema::Message;
8use tokio::sync::Mutex;
9
10use super::counter::{TokenCounter, TokenUsage};
11use super::tiktoken::TiktokenCounter;
12
13pub struct TokenTrackingLLM<L: BaseChatModel> {
18 llm: L,
19 counter: Arc<dyn TokenCounter>,
20 usage: Arc<Mutex<TokenUsage>>,
21}
22
23impl<L: BaseChatModel> TokenTrackingLLM<L> {
24 pub fn new(llm: L, counter: Arc<dyn TokenCounter>) -> Self {
25 Self {
26 llm,
27 counter,
28 usage: Arc::new(Mutex::new(TokenUsage::new())),
29 }
30 }
31
32 pub fn for_openai(llm: L) -> Result<Self, String> {
34 let counter = TiktokenCounter::new()?;
35 Ok(Self::new(llm, Arc::new(counter)))
36 }
37
38 pub async fn chat(
40 &self,
41 messages: Vec<Message>,
42 config: Option<RunnableConfig>,
43 ) -> Result<LLMResult, L::Error> {
44 let estimated_prompt = self.counter.count_messages(&messages);
45 let result = self.llm.chat(messages, config).await?;
46
47 let (prompt, completion) = result
49 .token_usage
50 .as_ref()
51 .map(|u| (u.prompt_tokens as u32, u.completion_tokens as u32))
52 .unwrap_or((estimated_prompt, self.counter.count_tokens(&result.content)));
53
54 self.usage.lock().await.add(prompt, completion);
55 Ok(result)
56 }
57
58 pub async fn get_usage(&self) -> TokenUsage {
60 self.usage.lock().await.clone()
61 }
62
63 pub async fn reset(&self) {
65 self.usage.lock().await.reset();
66 }
67
68 pub async fn estimate_cost(&self, pricing: &ModelPricing) -> f64 {
70 let usage = self.get_usage().await;
71 pricing.calculate(usage.prompt_tokens, usage.completion_tokens)
72 }
73}
74
75pub struct ModelPricing {
77 pub prompt_price_per_1k: f64,
78 pub completion_price_per_1k: f64,
79}
80
81impl ModelPricing {
82 pub fn new(prompt: f64, completion: f64) -> Self {
83 Self {
84 prompt_price_per_1k: prompt,
85 completion_price_per_1k: completion,
86 }
87 }
88
89 pub fn gpt4o_mini() -> Self {
91 Self::new(0.15, 0.60)
92 }
93
94 pub fn gpt4o() -> Self {
96 Self::new(2.50, 10.00)
97 }
98
99 pub fn calculate(&self, prompt: u32, completion: u32) -> f64 {
101 (prompt as f64 / 1000.0) * self.prompt_price_per_1k
102 + (completion as f64 / 1000.0) * self.completion_price_per_1k
103 }
104}
105
106#[cfg(test)]
107mod tests {
108 use super::*;
109
110 #[test]
111 fn test_model_pricing_gpt4o_mini() {
112 let p = ModelPricing::gpt4o_mini();
113 let cost = p.calculate(1000, 1000);
115 assert!((cost - 0.75).abs() < 0.001);
116 }
117
118 #[test]
119 fn test_model_pricing_zero() {
120 let p = ModelPricing::gpt4o_mini();
121 assert_eq!(p.calculate(0, 0), 0.0);
122 }
123
124 #[test]
125 fn test_model_pricing_custom() {
126 let p = ModelPricing::new(1.0, 2.0);
127 let cost = p.calculate(500, 250);
129 assert!((cost - 1.0).abs() < 0.001);
130 }
131
132 }