Skip to content

Commit 5311e0c

Browse files
committed
fix: Make context token counter more reliable
- Only consider API requests with valid token information - Skip messages with invalid/missing token data - Prevent counter from resetting on action approval messages - Ensure both tokensIn and tokensOut are valid numbers This makes the context token counter more stable and accurate by only updating on valid API responses with complete token data.
1 parent 97fe13d commit 5311e0c

File tree

1 file changed

+12
-4
lines changed

1 file changed

+12
-4
lines changed

src/shared/getApiMetrics.ts

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,18 @@ export function getApiMetrics(messages: ClineMessage[]): ApiMetrics {
3636
contextTokens: 0,
3737
}
3838

39-
// Find the last api_req_started message to get the context size
40-
const lastApiReq = [...messages]
41-
.reverse()
42-
.find((message) => message.type === "say" && message.say === "api_req_started" && message.text)
39+
// Find the last api_req_started message that has valid token information
40+
const lastApiReq = [...messages].reverse().find((message) => {
41+
if (message.type === "say" && message.say === "api_req_started" && message.text) {
42+
try {
43+
const parsedData = JSON.parse(message.text)
44+
return typeof parsedData.tokensIn === "number" && typeof parsedData.tokensOut === "number"
45+
} catch {
46+
return false
47+
}
48+
}
49+
return false
50+
})
4351

4452
messages.forEach((message) => {
4553
if (message.type === "say" && message.say === "api_req_started" && message.text) {

0 commit comments

Comments
 (0)