mirror of
https://wget.la/https://github.com/leookun/cursor-byok
synced 2026-12-01 01:05:10 +08:00
feat: enhance context token estimation and compaction logic
- Added `estimate_context_tokens` function to calculate provider-visible context size based on prompt specifications and projected messages. - Updated `CheckpointBuilder` to record estimated context tokens during message processing. - Refactored compaction logic to utilize the new token estimation, ensuring proper context management during model runs. - Introduced tests to validate context estimation and compaction behavior under various scenarios.
This commit is contained in:
1 parent
ee2592c469
commit
29fde7d7c7
9 files changed
+723
-188
No files matched your search
@@ -6,8 +6,6 @@ mod usage {
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::ProviderType;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct Usage {
|
||||
pub input_tokens: Option<u64>,
|
||||
@@ -18,21 +16,6 @@ mod usage {
|
||||
pub reasoning_tokens: Option<u64>,
|
||||
}
|
||||
|
||||
impl Usage {
|
||||
/// Returns the provider-visible input context without counting cached tokens twice.
|
||||
pub(crate) fn context_input_tokens(self, provider: ProviderType) -> Option<u64> {
|
||||
let input = self.input_tokens?;
|
||||
match provider {
|
||||
ProviderType::OpenAiChat | ProviderType::OpenAiResponses | ProviderType::Plugin => {
|
||||
Some(input)
|
||||
}
|
||||
ProviderType::Anthropic => input
|
||||
.checked_add(self.cache_read_tokens.unwrap_or_default())?
|
||||
.checked_add(self.cache_write_tokens.unwrap_or_default()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AddAssign for Usage {
|
||||
fn add_assign(&mut self, rhs: Self) {
|
||||
self.input_tokens = sum(self.input_tokens, rhs.input_tokens);
|
||||
@@ -53,7 +36,7 @@ pub use usage::*;
|
||||
mod llm_call {
|
||||
use serde::Serialize;
|
||||
|
||||
use super::{ProviderType, Usage};
|
||||
use super::ProviderType;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct NewLlmCall {
|
||||
@@ -75,14 +58,6 @@ mod llm_call {
|
||||
pub detailed: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct LlmCallUsageAnchor {
|
||||
pub request_type: ProviderType,
|
||||
pub usage: Usage,
|
||||
pub message_count: usize,
|
||||
pub tool_count: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct LlmCallSummary {
|
||||
pub call_id: String,
|
||||
|
||||
@@ -1,4 +1,100 @@
|
||||
//! Estimates and records model token usage.
|
||||
//! Estimates provider-visible context size and formats configured token counts.
|
||||
|
||||
use super::{ContentPart, ProjectedContent, ProjectedMessage, PromptSpec};
|
||||
|
||||
const TOKENS_PER_MESSAGE_OVERHEAD: u64 = 8;
|
||||
const TOKENS_PER_TOOL_CALL_OVERHEAD: u64 = 6;
|
||||
const TOKENS_PER_IMAGE: u64 = 1_024;
|
||||
|
||||
pub(crate) fn estimate_context_tokens(prompt: &PromptSpec, messages: &[ProjectedMessage]) -> u64 {
|
||||
let instructions = estimate_text_tokens(&prompt.instructions);
|
||||
let tools = prompt.tools.iter().fold(0_u64, |total, tool| {
|
||||
total.saturating_add(estimate_json_tokens(tool))
|
||||
});
|
||||
let messages = messages.iter().fold(0_u64, |total, message| {
|
||||
total.saturating_add(estimate_message_tokens(message))
|
||||
});
|
||||
instructions.saturating_add(tools).saturating_add(messages)
|
||||
}
|
||||
|
||||
fn estimate_message_tokens(message: &ProjectedMessage) -> u64 {
|
||||
let content = match &message.content {
|
||||
ProjectedContent::Parts(parts) => estimate_parts_tokens(parts),
|
||||
ProjectedContent::Assistant {
|
||||
text,
|
||||
thinking,
|
||||
replay_state,
|
||||
calls,
|
||||
} => {
|
||||
let calls = calls.iter().fold(0_u64, |total, call| {
|
||||
total
|
||||
.saturating_add(TOKENS_PER_TOOL_CALL_OVERHEAD)
|
||||
.saturating_add(estimate_text_tokens(&call.call_id))
|
||||
.saturating_add(estimate_text_tokens(&call.name))
|
||||
.saturating_add(estimate_json_tokens(&call.arguments))
|
||||
});
|
||||
estimate_text_tokens(text)
|
||||
.saturating_add(estimate_text_tokens(thinking))
|
||||
.saturating_add(
|
||||
replay_state
|
||||
.as_ref()
|
||||
.map(estimate_json_tokens)
|
||||
.unwrap_or_default(),
|
||||
)
|
||||
.saturating_add(calls)
|
||||
}
|
||||
ProjectedContent::ToolResult(result) => {
|
||||
let content = if result.provider_parts.is_empty() {
|
||||
estimate_text_tokens(&result.content).saturating_add(
|
||||
result
|
||||
.image
|
||||
.as_ref()
|
||||
.map(|image| {
|
||||
TOKENS_PER_IMAGE.saturating_add(estimate_text_tokens(&image.mime_type))
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
)
|
||||
} else {
|
||||
estimate_parts_tokens(&result.provider_parts)
|
||||
};
|
||||
estimate_text_tokens(&result.call_id)
|
||||
.saturating_add(estimate_text_tokens(&result.name))
|
||||
.saturating_add(content)
|
||||
}
|
||||
};
|
||||
TOKENS_PER_MESSAGE_OVERHEAD.saturating_add(content)
|
||||
}
|
||||
|
||||
fn estimate_parts_tokens(parts: &[ContentPart]) -> u64 {
|
||||
parts.iter().fold(0_u64, |total, part| {
|
||||
let tokens = match part {
|
||||
ContentPart::Text { text } => estimate_text_tokens(text),
|
||||
ContentPart::Image { mime_type, .. } => {
|
||||
TOKENS_PER_IMAGE.saturating_add(estimate_text_tokens(mime_type))
|
||||
}
|
||||
};
|
||||
total.saturating_add(tokens)
|
||||
})
|
||||
}
|
||||
|
||||
fn estimate_json_tokens(value: &impl serde::Serialize) -> u64 {
|
||||
serde_json::to_string(value)
|
||||
.map(|value| estimate_text_tokens(&value))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn estimate_text_tokens(text: &str) -> u64 {
|
||||
let text = text.trim();
|
||||
if text.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
let characters = text.chars().count() as u64;
|
||||
characters
|
||||
.div_ceil(4)
|
||||
.saturating_add(text.bytes().filter(|byte| *byte == b'\n').count() as u64)
|
||||
.max(1)
|
||||
}
|
||||
|
||||
pub(crate) fn parse_token_count(value: &str) -> Option<u64> {
|
||||
let value = value.trim().to_ascii_lowercase();
|
||||
let (number, multiplier) = match value.chars().last()? {
|
||||
@@ -18,3 +114,104 @@ pub(crate) fn format_token_count(tokens: u64) -> String {
|
||||
tokens.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::model::{Role, ToolCallContent, ToolDefinition, ToolResultContent};
|
||||
|
||||
fn prompt() -> PromptSpec {
|
||||
PromptSpec {
|
||||
instructions: "system instructions".into(),
|
||||
tools: vec![ToolDefinition {
|
||||
name: "Read".into(),
|
||||
description: "Read a file".into(),
|
||||
parameters: serde_json::json!({"type": "object", "properties": {"path": {"type": "string"}}}),
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_estimate_grows_with_provider_visible_text_and_tools() {
|
||||
let short = vec![ProjectedMessage {
|
||||
message_id: "short".into(),
|
||||
role: Role::User,
|
||||
content: ProjectedContent::Parts(vec![ContentPart::Text {
|
||||
text: "hello".into(),
|
||||
}]),
|
||||
}];
|
||||
let long = vec![ProjectedMessage {
|
||||
message_id: "long".into(),
|
||||
role: Role::User,
|
||||
content: ProjectedContent::Parts(vec![ContentPart::Text {
|
||||
text: "x".repeat(40_000),
|
||||
}]),
|
||||
}];
|
||||
let without_tools = PromptSpec {
|
||||
instructions: prompt().instructions,
|
||||
tools: Vec::new(),
|
||||
};
|
||||
|
||||
assert!(
|
||||
estimate_context_tokens(&prompt(), &short)
|
||||
> estimate_context_tokens(&without_tools, &short)
|
||||
);
|
||||
assert!(
|
||||
estimate_context_tokens(&prompt(), &long) > estimate_context_tokens(&prompt(), &short)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_estimate_counts_tool_calls_results_and_images() {
|
||||
let assistant = ProjectedMessage {
|
||||
message_id: "assistant".into(),
|
||||
role: Role::Assistant,
|
||||
content: ProjectedContent::Assistant {
|
||||
text: String::new(),
|
||||
thinking: "reasoning".into(),
|
||||
replay_state: None,
|
||||
calls: vec![ToolCallContent {
|
||||
index: 0,
|
||||
call_id: "call-1".into(),
|
||||
name: "Read".into(),
|
||||
arguments: serde_json::json!({"path": "/tmp/file"}),
|
||||
}],
|
||||
},
|
||||
};
|
||||
let text_result = ProjectedMessage {
|
||||
message_id: "result-text".into(),
|
||||
role: Role::Tool,
|
||||
content: ProjectedContent::ToolResult(ToolResultContent {
|
||||
call_id: "call-1".into(),
|
||||
name: "Read".into(),
|
||||
content: "file contents".into(),
|
||||
is_error: false,
|
||||
image: None,
|
||||
provider_parts: Vec::new(),
|
||||
}),
|
||||
};
|
||||
let image_result = ProjectedMessage {
|
||||
message_id: "result-image".into(),
|
||||
role: Role::Tool,
|
||||
content: ProjectedContent::ToolResult(ToolResultContent {
|
||||
call_id: "call-1".into(),
|
||||
name: "Read".into(),
|
||||
content: "file contents".into(),
|
||||
is_error: false,
|
||||
image: None,
|
||||
provider_parts: vec![ContentPart::Image {
|
||||
mime_type: "image/png".into(),
|
||||
data: vec![0; 32],
|
||||
}],
|
||||
}),
|
||||
};
|
||||
|
||||
let base = estimate_context_tokens(&prompt(), &[]);
|
||||
let with_call = estimate_context_tokens(&prompt(), std::slice::from_ref(&assistant));
|
||||
let with_text = estimate_context_tokens(&prompt(), &[assistant.clone(), text_result]);
|
||||
let with_image = estimate_context_tokens(&prompt(), &[assistant, image_result]);
|
||||
assert!(with_call > base);
|
||||
assert!(with_text > with_call);
|
||||
assert!(with_image > with_text);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user