* Serializes a tool_result block to text for token counting. * Handles both string content and array content.
(block: Anthropic.Messages.ToolResultBlockParam)
| 27 | * Handles both string content and array content. |
| 28 | */ |
| 29 | function serializeToolResult(block: Anthropic.Messages.ToolResultBlockParam): string { |
| 30 | const parts = [`Tool Result (${block.tool_use_id})`] |
| 31 | |
| 32 | if (block.is_error) { |
| 33 | parts.push(`[Error]`) |
| 34 | } |
| 35 | |
| 36 | const content = block.content |
| 37 | if (typeof content === "string") { |
| 38 | parts.push(content) |
| 39 | } else if (Array.isArray(content)) { |
| 40 | // Handle array of content blocks recursively |
| 41 | for (const item of content) { |
| 42 | if (item.type === "text") { |
| 43 | parts.push(item.text || "") |
| 44 | } else if (item.type === "image") { |
| 45 | parts.push("[Image content]") |
| 46 | } else { |
| 47 | parts.push(`[Unsupported content block: ${String((item as { type?: unknown }).type)}]`) |
| 48 | } |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | return parts.join("\n") |
| 53 | } |
| 54 | |
| 55 | export async function tiktoken(content: Anthropic.Messages.ContentBlockParam[]): Promise<number> { |
| 56 | if (content.length === 0) { |