Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/agent-runtime/src/run-agent-step.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ import {
buildUserMessageContent,
expireMessages,
} from './util/messages'
import { countTokensJson } from './util/token-counter'
import { countTokensJson, safeJsonStringify } from './util/token-counter'

import type { AgentTemplate } from '@codebuff/common/types/agent-template'
import type { TrackEventFn } from '@codebuff/common/types/contracts/analytics'
Expand Down Expand Up @@ -860,7 +860,7 @@ export async function loopAgentSteps(
// Convert tools to a serializable format for context-pruner token counting
const toolDefinitions = mapValues(tools, (tool) => ({
description: tool.description,
inputSchema: tool.inputSchema as {},
inputSchema: JSON.parse(safeJsonStringify(tool.inputSchema)),
}))

const additionalToolDefinitionsWithCache = async () => {
Expand Down
26 changes: 25 additions & 1 deletion packages/agent-runtime/src/util/token-counter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,34 @@ export function countTokens(text: string): number {
}
}

export function safeJsonStringify(obj: any): string {
const seen = new WeakSet()
return JSON.stringify(obj, (key, value) => {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) {
return '[Circular]'
}
seen.add(value)
}
if (typeof value === 'function') {
return value.toString()
}
return value
})
}

export function countTokensJson(text: string | object): number {
return countTokens(JSON.stringify(text))
if (typeof text === 'string') {
return countTokens(text)
}
try {
return countTokens(JSON.stringify(text))
} catch (e) {
return countTokens(safeJsonStringify(text))
}
}


export function countTokensForFiles(
files: Record<string, string | null>,
): Record<string, number> {
Expand Down