Elffuss BraidHub

kikocis/continue public

88b8936f200c · 4.3 KiBRawPermalink
1import { ModelConfig } from "@continuedev/config-yaml";
2import { encode } from "gpt-tokenizer";
3import { ChatCompletionMessageParam } from "openai/resources.mjs";
4
5import { logger } from "./logger.js";
6
7// Global auto-compact threshold (80% of context limit)
8// This is intentionally not configurable to ensure consistent behavior
9// across all usage scenarios. Change this value only for testing purposes.
10export const AUTO_COMPACT_THRESHOLD = 0.8;
11
12const DEFAULT_CONTEXT_LENGTH_FOR_COMPACTION = 200_000;
13/**
14 * Get the context length limit for a model
15 * @param modelName The model name
16 * @returns The context length limit in tokens
17 */
18export function getModelContextLimit(model: ModelConfig): number {
19 return (
20 model.defaultCompletionOptions?.contextLength ??
21 DEFAULT_CONTEXT_LENGTH_FOR_COMPACTION
22 );
23}
24
25/**
26 * Estimate the token count for a single message
27 * @param message The message to count tokens for
28 * @returns The estimated token count
29 */
30export function countMessageTokens(
31 message: ChatCompletionMessageParam,
32): number {
33 try {
34 let tokenCount = 0;
35
36 // Count tokens in content
37 if (typeof message.content === "string") {
38 tokenCount += encode(message.content).length;
39 } else if (Array.isArray(message.content)) {
40 // Handle array content (e.g., multimodal messages)
41 for (const part of message.content) {
42 if (part.type === "text" && part.text) {
43 tokenCount += encode(part.text).length;
44 }
45 // Images and other content types have their own token costs
46 // but we'll use a rough estimate for now
47 if (part.type === "image_url") {
48 tokenCount += 85; // Rough estimate for image tokens
49 }
50 }
51 }
52
53 // Add tokens for role (roughly 1-2 tokens)
54 tokenCount += 2;
55
56 // Add tokens for tool calls if present
57 if ("tool_calls" in message && message.tool_calls) {
58 for (const toolCall of message.tool_calls) {
59 // Function name and structure overhead
60 tokenCount += encode(toolCall.function.name).length + 10;
61 // Arguments
62 tokenCount += encode(toolCall.function.arguments).length;
63 }
64 }
65
66 // Add tokens for tool call results
67 if (message.role === "tool" && "content" in message) {
68 tokenCount += 5; // Tool message structure overhead
69 }
70
71 return tokenCount;
72 } catch (error) {
73 logger.error("Error counting tokens for message", error);
74 // Return a rough estimate based on character count
75 const content =
76 typeof message.content === "string"
77 ? message.content
78 : JSON.stringify(message.content);
79 return Math.ceil(content.length / 4); // Rough estimate: 4 chars per token
80 }
81}
82
83/**
84 * Estimate the total token count for a chat history
85 * @param chatHistory The chat history to count tokens for
86 * @returns The estimated total token count
87 */
88export function countChatHistoryTokens(
89 chatHistory: ChatCompletionMessageParam[],
90): number {
91 let totalTokens = 0;
92
93 for (const message of chatHistory) {
94 totalTokens += countMessageTokens(message);
95 }
96
97 // Add some overhead for message structure (roughly 3 tokens per message)
98 totalTokens += chatHistory.length * 3;
99
100 return totalTokens;
101}
102
103/**
104 * Calculate the percentage of context used
105 * @param tokenCount Current token count
106 * @param modelName The model name
107 * @returns The percentage of context used (0-100)
108 */
109export function calculateContextUsagePercentage(
110 tokenCount: number,
111 model: ModelConfig,
112): number {
113 const limit = getModelContextLimit(model);
114 return Math.min(100, Math.round((tokenCount / limit) * 100));
115}
116
117/**
118 * Check if the chat history exceeds the auto-compact threshold
119 * @param chatHistory The chat history to check
120 * @param modelName The model name
121 * @returns Whether auto-compacting should be triggered
122 */
123export function shouldAutoCompact(
124 chatHistory: ChatCompletionMessageParam[],
125 model: ModelConfig,
126): boolean {
127 const tokenCount = countChatHistoryTokens(chatHistory);
128 const limit = getModelContextLimit(model);
129 const usage = tokenCount / limit;
130
131 logger.debug("Context usage check", {
132 tokenCount,
133 limit,
134 usage: `${Math.round(usage * 100)}%`,
135 threshold: `${Math.round(AUTO_COMPACT_THRESHOLD * 100)}%`,
136 shouldCompact: usage >= AUTO_COMPACT_THRESHOLD,
137 });
138
139 return usage >= AUTO_COMPACT_THRESHOLD;
140}