|
1 | 1 | """Abstract base class for Agent model providers.""" |
2 | 2 |
|
3 | 3 | import abc |
| 4 | +import json |
4 | 5 | import logging |
5 | 6 | from collections.abc import AsyncGenerator, AsyncIterable |
6 | 7 | from dataclasses import dataclass |
7 | 8 | from typing import TYPE_CHECKING, Any, Literal, TypeVar |
8 | 9 |
|
| 10 | +import tiktoken |
9 | 11 | from pydantic import BaseModel |
10 | 12 |
|
11 | 13 | from ..hooks.events import AfterInvocationEvent |
12 | 14 | from ..plugins.plugin import Plugin |
13 | | -from ..types.content import Messages, SystemContentBlock |
| 15 | +from ..types.content import ContentBlock, Messages, SystemContentBlock |
14 | 16 | from ..types.streaming import StreamEvent |
15 | 17 | from ..types.tools import ToolChoice, ToolSpec |
16 | 18 |
|
|
21 | 23 |
|
22 | 24 | T = TypeVar("T", bound=BaseModel) |
23 | 25 |
|
| 26 | +_DEFAULT_ENCODING = "cl100k_base" |
| 27 | +_cached_encoding: tiktoken.Encoding | None = None |
| 28 | + |
| 29 | + |
| 30 | +def _get_encoding() -> tiktoken.Encoding: |
| 31 | + """Get the default tiktoken encoding, caching to avoid repeated lookups.""" |
| 32 | + global _cached_encoding |
| 33 | + if _cached_encoding is None: |
| 34 | + _cached_encoding = tiktoken.get_encoding(_DEFAULT_ENCODING) |
| 35 | + return _cached_encoding |
| 36 | + |
| 37 | + |
| 38 | +def _count_content_block_tokens(block: ContentBlock, encoding: tiktoken.Encoding) -> int: |
| 39 | + """Count tokens for a single content block.""" |
| 40 | + total = 0 |
| 41 | + |
| 42 | + if "text" in block: |
| 43 | + total += len(encoding.encode(block["text"])) |
| 44 | + |
| 45 | + if "toolUse" in block: |
| 46 | + try: |
| 47 | + total += len(encoding.encode(json.dumps(block["toolUse"]))) |
| 48 | + except (TypeError, ValueError): |
| 49 | + pass |
| 50 | + |
| 51 | + if "toolResult" in block: |
| 52 | + try: |
| 53 | + total += len(encoding.encode(json.dumps(block["toolResult"]))) |
| 54 | + except (TypeError, ValueError): |
| 55 | + pass |
| 56 | + |
| 57 | + if "reasoningContent" in block: |
| 58 | + reasoning = block["reasoningContent"] |
| 59 | + if "reasoningText" in reasoning: |
| 60 | + reasoning_text = reasoning["reasoningText"] |
| 61 | + if "text" in reasoning_text: |
| 62 | + total += len(encoding.encode(reasoning_text["text"])) |
| 63 | + |
| 64 | + if "guardContent" in block: |
| 65 | + guard = block["guardContent"] |
| 66 | + if "text" in guard: |
| 67 | + total += len(encoding.encode(guard["text"]["text"])) |
| 68 | + |
| 69 | + if "citationsContent" in block: |
| 70 | + citations = block["citationsContent"] |
| 71 | + for item in citations.get("content", []): |
| 72 | + if "text" in item: |
| 73 | + total += len(encoding.encode(item["text"])) |
| 74 | + |
| 75 | + return total |
| 76 | + |
| 77 | + |
| 78 | +def _estimate_tokens_with_tiktoken( |
| 79 | + messages: Messages, |
| 80 | + tool_specs: list[ToolSpec] | None = None, |
| 81 | + system_prompt: str | None = None, |
| 82 | +) -> int: |
| 83 | + """Estimate tokens by serializing messages/tools to text and counting with tiktoken. |
| 84 | +
|
| 85 | + This is a best-effort fallback for providers that don't expose native counting. |
| 86 | + Accuracy varies by model but is sufficient for threshold-based decisions. |
| 87 | + """ |
| 88 | + encoding = _get_encoding() |
| 89 | + total = 0 |
| 90 | + |
| 91 | + if system_prompt: |
| 92 | + total += len(encoding.encode(system_prompt)) |
| 93 | + |
| 94 | + for message in messages: |
| 95 | + for block in message["content"]: |
| 96 | + total += _count_content_block_tokens(block, encoding) |
| 97 | + |
| 98 | + if tool_specs: |
| 99 | + for spec in tool_specs: |
| 100 | + try: |
| 101 | + total += len(encoding.encode(json.dumps(spec))) |
| 102 | + except (TypeError, ValueError): |
| 103 | + pass |
| 104 | + |
| 105 | + return total |
| 106 | + |
24 | 107 |
|
25 | 108 | @dataclass |
26 | 109 | class CacheConfig: |
@@ -130,6 +213,32 @@ def stream( |
130 | 213 | """ |
131 | 214 | pass |
132 | 215 |
|
| 216 | + def _estimate_tokens( |
| 217 | + self, |
| 218 | + messages: Messages, |
| 219 | + tool_specs: list[ToolSpec] | None = None, |
| 220 | + system_prompt: str | None = None, |
| 221 | + ) -> int: |
| 222 | + """Estimate token count for the given input before sending to the model. |
| 223 | +
|
| 224 | + Used for proactive context management (e.g., triggering compression at a |
| 225 | + threshold). This is a naive approximation using tiktoken's cl100k_base encoding. |
| 226 | + Accuracy varies by model provider but is typically within 5-10% for most providers. |
| 227 | + Not intended for billing or precise quota calculations. |
| 228 | +
|
| 229 | + Subclasses may override this method to provide model-specific token counting |
| 230 | + using native APIs for improved accuracy. |
| 231 | +
|
| 232 | + Args: |
| 233 | + messages: List of message objects to estimate tokens for. |
| 234 | + tool_specs: List of tool specifications to include in the estimate. |
| 235 | + system_prompt: System prompt to include in the estimate. |
| 236 | +
|
| 237 | + Returns: |
| 238 | + Estimated total input tokens. |
| 239 | + """ |
| 240 | + return _estimate_tokens_with_tiktoken(messages, tool_specs, system_prompt) |
| 241 | + |
133 | 242 |
|
134 | 243 | class _ModelPlugin(Plugin): |
135 | 244 | """Plugin that manages model-related lifecycle hooks.""" |
|
0 commit comments