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