|
| 1 | +# SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai> |
| 2 | +# |
| 3 | +# SPDX-License-Identifier: Apache-2.0 |
| 4 | + |
| 5 | +import json |
| 6 | + |
| 7 | +from haystack.dataclasses import ChatMessage, FileContent, ImageContent, TextContent |
| 8 | +from haystack.dataclasses.chat_message import ChatMessageContentT, ToolCallResultContentT |
| 9 | + |
| 10 | + |
| 11 | +def _non_text_placeholder(content: ChatMessageContentT) -> str: |
| 12 | + """A short stand-in, such as `<image>`, for message content that has no text form.""" |
| 13 | + if isinstance(content, ImageContent): |
| 14 | + return "<image>" |
| 15 | + if isinstance(content, FileContent): |
| 16 | + return f"<file: {content.filename or 'unnamed'}>" |
| 17 | + return f"<{type(content).__name__}>" |
| 18 | + |
| 19 | + |
| 20 | +def _tool_result_text(result: ToolCallResultContentT) -> str: |
| 21 | + """A tool result as a single string, with placeholders standing in for any non-text parts.""" |
| 22 | + if isinstance(result, str): |
| 23 | + return result |
| 24 | + return "".join(block.text if isinstance(block, TextContent) else _non_text_placeholder(block) for block in result) |
| 25 | + |
| 26 | + |
| 27 | +def _render_message(message: ChatMessage) -> str: |
| 28 | + """ |
| 29 | + One message as one or more lines of plain text. |
| 30 | +
|
| 31 | + Reasoning content is deliberately left out: providers discard it between turns, so it is not part of the context |
| 32 | + being measured. |
| 33 | + """ |
| 34 | + role = message.role.value |
| 35 | + # A tool-result msg only carries tool_call_results, so it is rendered on its own and labelled with the tool that |
| 36 | + # produced it. |
| 37 | + if results := message.tool_call_results: |
| 38 | + return "\n".join( |
| 39 | + f"[tool:{result.origin.tool_name}{' (error)' if result.error else ''}] {_tool_result_text(result.result)}" |
| 40 | + for result in results |
| 41 | + ) |
| 42 | + |
| 43 | + lines: list[str] = [] |
| 44 | + if texts := message.texts: |
| 45 | + lines.append(f"[{role}] " + "\n".join(texts)) |
| 46 | + for call in message.tool_calls: |
| 47 | + arguments = json.dumps(call.arguments, default=str, sort_keys=True) |
| 48 | + lines.append(f"[{role} -> tool_call] {call.tool_name}({arguments})") |
| 49 | + # Images and files cost tokens too, so they need a stand-in rather than being skipped. |
| 50 | + non_text: list[ChatMessageContentT] = [*message.images, *message.files] |
| 51 | + for content in non_text: |
| 52 | + lines.append(f"[{role}] {_non_text_placeholder(content)}") |
| 53 | + return "\n".join(lines) if lines else f"[{role}] <no content>" |
| 54 | + |
| 55 | + |
| 56 | +def _rendered_conversation(messages: list[ChatMessage]) -> str: |
| 57 | + """The whole conversation as one plain-text block, which is what a counter measures.""" |
| 58 | + return "\n".join(_render_message(message) for message in messages) |
| 59 | + |
| 60 | + |
| 61 | +def _non_text_tokens(messages: list[ChatMessage], tokens_per_image: int, tokens_per_file: int) -> int: |
| 62 | + """ |
| 63 | + A flat estimate for the images and files in a conversation, which have no text to measure. |
| 64 | +
|
| 65 | + :param messages: The conversation to measure. |
| 66 | + :param tokens_per_image: Tokens to charge per image. |
| 67 | + :param tokens_per_file: Tokens to charge per file. |
| 68 | + :returns: The estimated token count for the non-text content. |
| 69 | + """ |
| 70 | + images = 0 |
| 71 | + files = 0 |
| 72 | + for message in messages: |
| 73 | + images += len(message.images) |
| 74 | + files += len(message.files) |
| 75 | + # Images and files returned by a tool are nested inside the tool result |
| 76 | + for result in message.tool_call_results: |
| 77 | + if isinstance(result.result, str): |
| 78 | + continue |
| 79 | + images += sum(isinstance(block, ImageContent) for block in result.result) |
| 80 | + files += sum(isinstance(block, FileContent) for block in result.result) |
| 81 | + return images * tokens_per_image + files * tokens_per_file |
0 commit comments