Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

updated pricing for cached tokens support

Gregor Žunič2ee526d9033b
diff --git a/browser_use/agent/message_manager/service.py b/browser_use/agent/message_manager/service.py
index 576546428..3d4ccd9a8 100644
--- a/browser_use/agent/message_manager/service.py
+++ b/browser_use/agent/message_manager/service.py
@@ -134,7 +134,8 @@ class MessageManager:
self._add_message_with_type(self.system_prompt, message_type='init')
placeholder_message = UserMessage(
- content='<example_1>\nHere is an example output of thinking and tool call. You can use it as a reference but do not copy it exactly.'
+ content='<example_1>\nHere is an example output of thinking and tool call. You can use it as a reference but do not copy it exactly.',
+ cache=True,
)
# placeholder_message = HumanMessage(content='Example output:')
self._add_message_with_type(placeholder_message, message_type='init')
@@ -176,11 +177,12 @@ Since this appears to be a multi-step task involving visiting multiple repositor
After writing todo.md, I can also initialize a github.md file to accumulate the information I've collected.
The file system actions do not change the browser state, so I can also click on the bytedance/UI-TARS-desktop (index [4]) to start collecting information."""
- example_tool_call_1 = AssistantMessage(content=json.dumps(example_content))
+ example_tool_call_1 = AssistantMessage(content=json.dumps(example_content), cache=True)
self._add_message_with_type(example_tool_call_1, message_type='init')
self._add_message_with_type(
UserMessage(
content='Data written to todo.md.\nData written to github.md.\nClicked element with index 4.\n</example_1>',
+ cache=True,
),
message_type='init',
)
diff --git a/browser_use/agent/prompts.py b/browser_use/agent/prompts.py
index f794964f6..b5fae75c4 100644
--- a/browser_use/agent/prompts.py
+++ b/browser_use/agent/prompts.py
@@ -32,7 +32,7 @@ class SystemPrompt:
if extend_system_message:
prompt += f'\n{extend_system_message}'
- self.system_message = SystemMessage(content=prompt)
+ self.system_message = SystemMessage(content=prompt, cache=True)
def _load_prompt_template(self) -> None:
"""Load the prompt template from the markdown file."""
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 7940ec25a..6ccc54f03 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -181,6 +181,7 @@ class Agent(Generic[Context]):
file_system_path: str | None = None,
task_id: str | None = None,
cloud_sync: CloudSync | None = None,
+ calculate_cost: bool = False,
):
if page_extraction_llm is None:
page_extraction_llm = llm
@@ -221,10 +222,11 @@ class Agent(Generic[Context]):
is_planner_reasoning=is_planner_reasoning,
extend_planner_system_message=extend_planner_system_message,
use_thinking=use_thinking,
+ calculate_cost=calculate_cost,
)
# Token cost service
- self.token_cost_service = TokenCost()
+ self.token_cost_service = TokenCost(include_cost=calculate_cost)
self.token_cost_service.register_llm(llm)
self.token_cost_service.register_llm(page_extraction_llm)
if self.settings.planner_llm:
@@ -1037,7 +1039,7 @@ class Agent(Generic[Context]):
def _log_agent_event(self, max_steps: int, agent_run_error: str | None = None) -> None:
"""Sent the agent event for this run to telemetry"""
- total_input_tokens = self.token_cost_service.get_usage_summary(calculate_cost=False).total_prompt_tokens
+ token_summary = self.token_cost_service.get_usage_tokens_for_model(self.llm.model)
# Prepare action_history data correctly
action_history_data = []
@@ -1073,7 +1075,7 @@ class Agent(Generic[Context]):
action_history=action_history_data,
urls_visited=self.state.history.urls(),
steps=self.state.n_steps,
- total_input_tokens=total_input_tokens,
+ total_input_tokens=token_summary.prompt_tokens,
total_duration_seconds=self.state.history.total_duration_seconds(),
success=self.state.history.is_successful(),
final_result_response=final_result_str,
diff --git a/browser_use/agent/views.py b/browser_use/agent/views.py
index effdd5494..0299f565c 100644
--- a/browser_use/agent/views.py
+++ b/browser_use/agent/views.py
@@ -57,6 +57,7 @@ class AgentSettings(BaseModel):
planner_interval: int = 1 # Run planner every N steps
is_planner_reasoning: bool = False # type: ignore
extend_planner_system_message: str | None = None
+ calculate_cost: bool = False
class AgentState(BaseModel):
diff --git a/browser_use/llm/anthropic/chat.py b/browser_use/llm/anthropic/chat.py
index 08976417b..de61f5bea 100644
--- a/browser_use/llm/anthropic/chat.py
+++ b/browser_use/llm/anthropic/chat.py
@@ -5,13 +5,14 @@ from typing import Any, TypeVar, overload
import httpx
from anthropic import (
+ NOT_GIVEN,
APIConnectionError,
APIStatusError,
AsyncAnthropic,
NotGiven,
RateLimitError,
)
-from anthropic.types import Message, ToolParam
+from anthropic.types import CacheControlEphemeralParam, Message, ToolParam
from anthropic.types.model_param import ModelParam
from anthropic.types.text_block import TextBlock
from anthropic.types.tool_choice_tool_param import ToolChoiceToolParam
@@ -102,9 +103,15 @@ class ChatAnthropic(BaseChatModel):
def _get_usage(self, response: Message) -> ChatInvokeUsage | None:
usage = ChatInvokeUsage(
- prompt_tokens=response.usage.input_tokens,
+ prompt_tokens=response.usage.input_tokens
+ + (
+ response.usage.cache_read_input_tokens or 0
+ ), # Total tokens in Anthropic are a bit fucked, you have to add cached tokens to the prompt tokens
completion_tokens=response.usage.output_tokens,
total_tokens=response.usage.input_tokens + response.usage.output_tokens,
+ prompt_cached_tokens=response.usage.cache_read_input_tokens,
+ prompt_cache_creation_tokens=response.usage.cache_creation_input_tokens,
+ prompt_image_tokens=None,
)
return usage
@@ -123,7 +130,10 @@ class ChatAnthropic(BaseChatModel):
if output_format is None:
# Normal completion without structured output
response = await self.get_client().messages.create(
- model=self.model, messages=anthropic_messages, **self._get_client_params_for_invoke()
+ model=self.model,
+ messages=anthropic_messages,
+ system=system_prompt or NOT_GIVEN,
+ **self._get_client_params_for_invoke(),
)
usage = self._get_usage(response)
@@ -152,7 +162,10 @@ class ChatAnthropic(BaseChatModel):
del schema['title']
tool = ToolParam(
- name=tool_name, description=f'Extract information in the format of {tool_name}', input_schema=schema
+ name=tool_name,
+ description=f'Extract information in the format of {tool_name}',
+ input_schema=schema,
+ cache_control=CacheControlEphemeralParam(type='ephemeral'),
)
# Force the model to use this tool
@@ -162,6 +175,7 @@ class ChatAnthropic(BaseChatModel):
model=self.model,
messages=anthropic_messages,
tools=[tool],
+ system=system_prompt or NOT_GIVEN,
tool_choice=tool_choice,
**self._get_client_params_for_invoke(),
)
diff --git a/browser_use/llm/anthropic/serializer.py b/browser_use/llm/anthropic/serializer.py
index 166be26ee..d9a09b823 100644
--- a/browser_use/llm/anthropic/serializer.py
+++ b/browser_use/llm/anthropic/serializer.py
@@ -1,7 +1,9 @@
+import json
from typing import overload
from anthropic.types import (
Base64ImageSourceParam,
+ CacheControlEphemeralParam,
ImageBlockParam,
MessageParam,
TextBlockParam,
@@ -19,6 +21,8 @@ from browser_use.llm.messages import (
UserMessage,
)
+NonSystemMessage = UserMessage | AssistantMessage
+
class AnthropicMessageSerializer:
"""Serializer for converting between custom message types and Anthropic message param types."""
@@ -47,9 +51,18 @@ class AnthropicMessageSerializer:
return media_type, data # type: ignore
@staticmethod
- def _serialize_content_part_text(part: ContentPartTextParam) -> TextBlockParam:
+ def _serialize_cache_control(use_cache: bool) -> CacheControlEphemeralParam | None:
+ """Serialize cache control."""
+ if use_cache:
+ return CacheControlEphemeralParam(type='ephemeral')
+ return None
+
+ @staticmethod
+ def _serialize_content_part_text(part: ContentPartTextParam, use_cache: bool) -> TextBlockParam:
"""Convert a text content part to Anthropic's TextBlockParam."""
- return TextBlockParam(text=part.text, type='text')
+ return TextBlockParam(
+ text=part.text, type='text', cache_control=AnthropicMessageSerializer._serialize_cache_control(use_cache)
+ )
@staticmethod
def _serialize_content_part_image(part: ContentPartImageParam) -> ImageBlockParam:
@@ -72,42 +85,52 @@ class AnthropicMessageSerializer:
return ImageBlockParam(source=URLImageSourceParam(url=url, type='url'), type='image')
@staticmethod
- def _serialize_content_to_str(content: str | list[ContentPartTextParam]) -> str | list[TextBlockParam]:
+ def _serialize_content_to_str(
+ content: str | list[ContentPartTextParam], use_cache: bool = False
+ ) -> list[TextBlockParam] | str:
"""Serialize content to a string."""
+ cache_control = AnthropicMessageSerializer._serialize_cache_control(use_cache)
+
if isinstance(content, str):
- return content
+ if cache_control:
+ return [TextBlockParam(text=content, type='text', cache_control=cache_control)]
+ else:
+ return content
serialized_blocks: list[TextBlockParam] = []
for part in content:
if part.type == 'text':
- serialized_blocks.append(AnthropicMessageSerializer._serialize_content_part_text(part))
+ serialized_blocks.append(AnthropicMessageSerializer._serialize_content_part_text(part, use_cache))
return serialized_blocks
@staticmethod
def _serialize_content(
content: str | list[ContentPartTextParam | ContentPartImageParam],
+ use_cache: bool = False,
) -> str | list[TextBlockParam | ImageBlockParam]:
"""Serialize content to Anthropic format."""
if isinstance(content, str):
- return content
+ if use_cache:
+ return [TextBlockParam(text=content, type='text', cache_control=CacheControlEphemeralParam(type='ephemeral'))]
+ else:
+ return content
serialized_blocks: list[TextBlockParam | ImageBlockParam] = []
for part in content:
if part.type == 'text':
- serialized_blocks.append(AnthropicMessageSerializer._serialize_content_part_text(part))
+ serialized_blocks.append(AnthropicMessageSerializer._serialize_content_part_text(part, use_cache))
elif part.type == 'image_url':
serialized_blocks.append(AnthropicMessageSerializer._serialize_content_part_image(part))
return serialized_blocks
@staticmethod
- def _serialize_tool_calls_to_content(tool_calls) -> list[ToolUseBlockParam]:
+ def _serialize_tool_calls_to_content(tool_calls, use_cache: bool = False) -> list[ToolUseBlockParam]:
"""Convert tool calls to Anthropic's ToolUseBlockParam format."""
blocks: list[ToolUseBlockParam] = []
for tool_call in tool_calls:
# Parse the arguments JSON string to object
- import json
try:
input_obj = json.loads(tool_call.function.arguments)
@@ -115,7 +138,15 @@ class AnthropicMessageSerializer:
# If arguments aren't valid JSON, use as string
input_obj = {'arguments': tool_call.function.arguments}
- blocks.append(ToolUseBlockParam(id=tool_call.id, input=input_obj, name=tool_call.function.name, type='tool_use'))
+ blocks.append(
+ ToolUseBlockParam(
+ id=tool_call.id,
+ input=input_obj,
+ name=tool_call.function.name,
+ type='tool_use',
+ cache_control=AnthropicMessageSerializer._serialize_cache_control(use_cache),
+ )
+ )
return blocks
# region - Serialize overloads
@@ -140,7 +171,7 @@ class AnthropicMessageSerializer:
If a SystemMessage is passed here, it will be converted to a user message.
"""
if isinstance(message, UserMessage):
- content = AnthropicMessageSerializer._serialize_content(message.content)
+ content = AnthropicMessageSerializer._serialize_content(message.content, use_cache=message.cache)
return MessageParam(role='user', content=content)
elif isinstance(message, SystemMessage):
@@ -155,12 +186,18 @@ class AnthropicMessageSerializer:
# Add content blocks if present
if message.content is not None:
if isinstance(message.content, str):
- blocks.append(TextBlockParam(text=message.content, type='text'))
+ blocks.append(
+ TextBlockParam(
+ text=message.content,
+ type='text',
+ cache_control=AnthropicMessageSerializer._serialize_cache_control(message.cache),
+ )
+ )
else:
# Process content parts (text and refusal)
for part in message.content:
if part.type == 'text':
- blocks.append(AnthropicMessageSerializer._serialize_content_part_text(part))
+ blocks.append(AnthropicMessageSerializer._serialize_content_part_text(part, use_cache=message.cache))
# # Note: Anthropic doesn't have a specific refusal block type,
# # so we convert refusals to text blocks
# elif part.type == 'refusal':
@@ -168,24 +205,77 @@ class AnthropicMessageSerializer:
# Add tool use blocks if present
if message.tool_calls:
- tool_blocks = AnthropicMessageSerializer._serialize_tool_calls_to_content(message.tool_calls)
+ tool_blocks = AnthropicMessageSerializer._serialize_tool_calls_to_content(
+ message.tool_calls, use_cache=message.cache
+ )
blocks.extend(tool_blocks)
# If no content or tool calls, add empty text block
# (Anthropic requires at least one content block)
if not blocks:
- blocks.append(TextBlockParam(text='', type='text'))
+ blocks.append(
+ TextBlockParam(
+ text='', type='text', cache_control=AnthropicMessageSerializer._serialize_cache_control(message.cache)
+ )
+ )
+
+ # If caching is enabled or we have multiple blocks, return blocks as-is
+ # Otherwise, simplify single text blocks to plain string
+ if message.cache or len(blocks) > 1:
+ content = blocks
+ else:
+ # Only simplify when no caching and single block
+ single_block = blocks[0]
+ if single_block['type'] == 'text' and not single_block.get('cache_control'):
+ content = single_block['text']
+ else:
+ content = blocks
return MessageParam(
role='assistant',
- content=blocks if len(blocks) > 1 else blocks[0].get('text', ''), # type: ignore
+ content=content,
)
else:
raise ValueError(f'Unknown message type: {type(message)}')
@staticmethod
- def serialize_messages(messages: list[BaseMessage]) -> tuple[list[MessageParam], str | list[TextBlockParam] | None]:
+ def _clean_cache_messages(messages: list[NonSystemMessage]) -> list[NonSystemMessage]:
+ """Clean cache settings so only the last cache=True message remains cached.
+
+ Because of how Claude caching works, only the last cache message matters.
+ This method automatically removes cache=True from all messages except the last one.
+
+ Args:
+ messages: List of non-system messages to clean
+
+ Returns:
+ List of messages with cleaned cache settings
+ """
+ if not messages:
+ return messages
+
+ # Create a copy to avoid modifying the original
+ cleaned_messages = [msg.model_copy(deep=True) for msg in messages]
+
+ # Find the last message with cache=True
+ last_cache_index = -1
+ for i in range(len(cleaned_messages) - 1, -1, -1):
+ if cleaned_messages[i].cache:
+ last_cache_index = i
+ break
+
+ # If we found a cached message, disable cache for all others
+ if last_cache_index != -1:
+ for i, msg in enumerate(cleaned_messages):
+ if i != last_cache_index and msg.cache:
+ # Set cache to False for all messages except the last cached one
+ msg.cache = False
+
+ return cleaned_messages
+
+ @staticmethod
+ def serialize_messages(messages: list[BaseMessage]) -> tuple[list[MessageParam], list[TextBlockParam] | str | None]:
"""Serialize a list of messages, extracting any system message.
Returns:
@@ -194,15 +284,29 @@ class AnthropicMessageSerializer:
"""
messages = [m.model_copy(deep=True) for m in messages]
- serialized_messages: list[MessageParam] = []
- system_message: str | list[TextBlockParam] | None = None
+ # Separate system messages from normal messages
+ normal_messages: list[NonSystemMessage] = []
+ system_message: SystemMessage | None = None
for message in messages:
- result = AnthropicMessageSerializer.serialize(message)
- if isinstance(result, SystemMessage):
- # Keep the SystemMessage as-is
- system_message = AnthropicMessageSerializer._serialize_content_to_str(result.content)
+ if isinstance(message, SystemMessage):
+ system_message = message
else:
- serialized_messages.append(result)
+ normal_messages.append(message)
+
+ # Clean cache messages so only the last cache=True message remains cached
+ normal_messages = AnthropicMessageSerializer._clean_cache_messages(normal_messages)
+
+ # Serialize normal messages
+ serialized_messages: list[MessageParam] = []
+ for message in normal_messages:
+ serialized_messages.append(AnthropicMessageSerializer.serialize(message))
+
+ # Serialize system message
+ serialized_system_message: list[TextBlockParam] | str | None = None
+ if system_message:
+ serialized_system_message = AnthropicMessageSerializer._serialize_content_to_str(
+ system_message.content, use_cache=system_message.cache
+ )
- return serialized_messages, system_message
+ return serialized_messages, serialized_system_message
diff --git a/browser_use/llm/google/chat.py b/browser_use/llm/google/chat.py
index 086e835b9..42a1dad92 100644
--- a/browser_use/llm/google/chat.py
+++ b/browser_use/llm/google/chat.py
@@ -95,7 +95,9 @@ class ChatGoogle(BaseChatModel):
prompt_tokens=response.usage_metadata.prompt_token_count or 0,
completion_tokens=response.usage_metadata.candidates_token_count or 0,
total_tokens=response.usage_metadata.total_token_count or 0,
- image_tokens=image_tokens,
+ prompt_cached_tokens=response.usage_metadata.cached_content_token_count,
+ prompt_cache_creation_tokens=None,
+ prompt_image_tokens=image_tokens,
)
return usage
diff --git a/browser_use/llm/groq/chat.py b/browser_use/llm/groq/chat.py
index 99d73b77c..a6cf00f65 100644
--- a/browser_use/llm/groq/chat.py
+++ b/browser_use/llm/groq/chat.py
@@ -71,6 +71,9 @@ class ChatGroq(BaseChatModel):
prompt_tokens=response.usage.prompt_tokens,
completion_tokens=response.usage.completion_tokens,
total_tokens=response.usage.total_tokens,
+ prompt_cached_tokens=None, # Groq doesn't support cached tokens
+ prompt_cache_creation_tokens=None,
+ prompt_image_tokens=None,
)
if response.usage is not None
else None
diff --git a/browser_use/llm/messages.py b/browser_use/llm/messages.py
index d2ca77c58..75a5d8f6e 100644
--- a/browser_use/llm/messages.py
+++ b/browser_use/llm/messages.py
@@ -122,9 +122,17 @@ class ToolCall(BaseModel):
# region - Message types
+class _MessageBase(BaseModel):
+ """Base class for all message types"""
+ role: Literal['user', 'system', 'assistant']
-class UserMessage(BaseModel):
+ cache: bool = False
+ """Whether to cache this message. This is only applicable when using Anthropic models.
+ """
+
+
+class UserMessage(_MessageBase):
role: Literal['user'] = 'user'
"""The role of the messages author, in this case `user`."""
@@ -157,7 +165,7 @@ class UserMessage(BaseModel):
return f'UserMessage(content={repr(self.text)})'
-class SystemMessage(BaseModel):
+class SystemMessage(_MessageBase):
role: Literal['system'] = 'system'
"""The role of the messages author, in this case `system`."""
@@ -185,7 +193,7 @@ class SystemMessage(BaseModel):
return f'SystemMessage(content={repr(self.text)})'
-class AssistantMessage(BaseModel):
+class AssistantMessage(_MessageBase):
role: Literal['assistant'] = 'assistant'
"""The role of the messages author, in this case `assistant`."""
diff --git a/browser_use/llm/openai/chat.py b/browser_use/llm/openai/chat.py
index 329e65c9d..6de5f977b 100644
--- a/browser_use/llm/openai/chat.py
+++ b/browser_use/llm/openai/chat.py
@@ -93,6 +93,12 @@ class ChatOpenAI(BaseChatModel):
usage = (
ChatInvokeUsage(
prompt_tokens=response.usage.prompt_tokens,
+ prompt_cached_tokens=response.usage.prompt_tokens_details.cached_tokens
+ if response.usage.prompt_tokens_details is not None
+ else None,
+ prompt_cache_creation_tokens=None,
+ prompt_image_tokens=None,
+ # Completion
completion_tokens=response.usage.completion_tokens,
total_tokens=response.usage.total_tokens,
)
diff --git a/browser_use/llm/tests/test_anthropic_cache.py b/browser_use/llm/tests/test_anthropic_cache.py
new file mode 100644
index 000000000..e6989f045
--- /dev/null
+++ b/browser_use/llm/tests/test_anthropic_cache.py
@@ -0,0 +1,290 @@
+import logging
+from typing import cast
+
+from browser_use.agent.service import Agent
+from browser_use.llm.anthropic.chat import ChatAnthropic
+from browser_use.llm.anthropic.serializer import AnthropicMessageSerializer, NonSystemMessage
+from browser_use.llm.messages import (
+ AssistantMessage,
+ BaseMessage,
+ ContentPartImageParam,
+ ContentPartTextParam,
+ Function,
+ ImageURL,
+ SystemMessage,
+ ToolCall,
+ UserMessage,
+)
+
+logger = logging.getLogger(__name__)
+
+
+class TestAnthropicCache:
+ """Comprehensive test for Anthropic cache serialization."""
+
+ def test_cache_basic_functionality(self):
+ """Test basic cache functionality for all message types."""
+ # Test cache with different message types
+ messages: list[BaseMessage] = [
+ SystemMessage(content='System message!', cache=True),
+ UserMessage(content='User message!', cache=True),
+ AssistantMessage(content='Assistant message!', cache=False),
+ ]
+
+ anthropic_messages, system_message = AnthropicMessageSerializer.serialize_messages(messages)
+
+ assert len(anthropic_messages) == 2
+ assert isinstance(system_message, list)
+ assert isinstance(anthropic_messages[0]['content'], list)
+ assert isinstance(anthropic_messages[1]['content'], str)
+
+ # Test cache with assistant message
+ agent_messages: list[BaseMessage] = [
+ SystemMessage(content='System message!'),
+ UserMessage(content='User message!'),
+ AssistantMessage(content='Assistant message!', cache=True),
+ ]
+
+ anthropic_messages, system_message = AnthropicMessageSerializer.serialize_messages(agent_messages)
+
+ assert isinstance(system_message, str)
+ assert isinstance(anthropic_messages[0]['content'], str)
+ assert isinstance(anthropic_messages[1]['content'], list)
+
+ def test_cache_with_tool_calls(self):
+ """Test cache functionality with tool calls."""
+ tool_call = ToolCall(id='test_id', function=Function(name='test_function', arguments='{"arg": "value"}'))
+
+ # Assistant with tool calls and cache
+ assistant_with_tools = AssistantMessage(content='Assistant with tools', tool_calls=[tool_call], cache=True)
+ messages, _ = AnthropicMessageSerializer.serialize_messages([assistant_with_tools])
+
+ assert len(messages) == 1
+ assert isinstance(messages[0]['content'], list)
+ # Should have both text and tool_use blocks
+ assert len(messages[0]['content']) >= 2
+
+ def test_cache_with_images(self):
+ """Test cache functionality with image content."""
+ user_with_image = UserMessage(
+ content=[
+ ContentPartTextParam(text='Here is an image:', type='text'),
+ ContentPartImageParam(image_url=ImageURL(url='https://example.com/image.jpg'), type='image_url'),
+ ],
+ cache=True,
+ )
+
+ messages, _ = AnthropicMessageSerializer.serialize_messages([user_with_image])
+
+ assert len(messages) == 1
+ assert isinstance(messages[0]['content'], list)
+ assert len(messages[0]['content']) == 2
+
+ def test_cache_with_base64_images(self):
+ """Test cache functionality with base64 images."""
+ base64_url = 'data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=='
+
+ user_with_base64 = UserMessage(
+ content=[
+ ContentPartTextParam(text='Base64 image:', type='text'),
+ ContentPartImageParam(image_url=ImageURL(url=base64_url), type='image_url'),
+ ],
+ cache=True,
+ )
+
+ messages, _ = AnthropicMessageSerializer.serialize_messages([user_with_base64])
+
+ assert len(messages) == 1
+ assert isinstance(messages[0]['content'], list)
+
+ def test_cache_content_types(self):
+ """Test different content types with cache."""
+ # String content with cache should become list
+ user_string_cached = UserMessage(content='String message', cache=True)
+ messages, _ = AnthropicMessageSerializer.serialize_messages([user_string_cached])
+ assert isinstance(messages[0]['content'], list)
+
+ # String content without cache should remain string
+ user_string_no_cache = UserMessage(content='String message', cache=False)
+ messages, _ = AnthropicMessageSerializer.serialize_messages([user_string_no_cache])
+ assert isinstance(messages[0]['content'], str)
+
+ # List content maintains list format regardless of cache
+ user_list_cached = UserMessage(content=[ContentPartTextParam(text='List message', type='text')], cache=True)
+ messages, _ = AnthropicMessageSerializer.serialize_messages([user_list_cached])
+ assert isinstance(messages[0]['content'], list)
+
+ user_list_no_cache = UserMessage(content=[ContentPartTextParam(text='List message', type='text')], cache=False)
+ messages, _ = AnthropicMessageSerializer.serialize_messages([user_list_no_cache])
+ assert isinstance(messages[0]['content'], list)
+
+ def test_assistant_cache_empty_content(self):
+ """Test AssistantMessage with empty content and cache."""
+ # With cache
+ assistant_empty_cached = AssistantMessage(content=None, cache=True)
+ messages, _ = AnthropicMessageSerializer.serialize_messages([assistant_empty_cached])
+
+ assert len(messages) == 1
+ assert isinstance(messages[0]['content'], list)
+
+ # Without cache
+ assistant_empty_no_cache = AssistantMessage(content=None, cache=False)
+ messages, _ = AnthropicMessageSerializer.serialize_messages([assistant_empty_no_cache])
+
+ assert len(messages) == 1
+ assert isinstance(messages[0]['content'], str)
+
+ def test_mixed_cache_scenarios(self):
+ """Test various combinations of cached and non-cached messages."""
+ messages_list: list[BaseMessage] = [
+ SystemMessage(content='System with cache', cache=True),
+ UserMessage(content='User with cache', cache=True),
+ AssistantMessage(content='Assistant without cache', cache=False),
+ UserMessage(content='User without cache', cache=False),
+ AssistantMessage(content='Assistant with cache', cache=True),
+ ]
+
+ serialized_messages, system_message = AnthropicMessageSerializer.serialize_messages(messages_list)
+
+ # Check system message is cached (becomes list)
+ assert isinstance(system_message, list)
+
+ # Check serialized messages
+ assert len(serialized_messages) == 4
+
+ # User with cache should be list
+ assert isinstance(serialized_messages[0]['content'], list)
+
+ # Assistant without cache should be string
+ assert isinstance(serialized_messages[1]['content'], str)
+
+ # User without cache should be string
+ assert isinstance(serialized_messages[2]['content'], str)
+
+ # Assistant with cache should be list
+ assert isinstance(serialized_messages[3]['content'], list)
+
+ def test_system_message_cache_behavior(self):
+ """Test SystemMessage specific cache behavior."""
+ # With cache
+ system_cached = SystemMessage(content='System message with cache', cache=True)
+ result = AnthropicMessageSerializer.serialize(system_cached)
+ assert isinstance(result, SystemMessage)
+
+ # Test serialization to string format
+ serialized_content = AnthropicMessageSerializer._serialize_content_to_str(result.content, use_cache=True)
+ assert isinstance(serialized_content, list)
+
+ # Without cache
+ system_no_cache = SystemMessage(content='System message without cache', cache=False)
+ result = AnthropicMessageSerializer.serialize(system_no_cache)
+ assert isinstance(result, SystemMessage)
+
+ serialized_content = AnthropicMessageSerializer._serialize_content_to_str(result.content, use_cache=False)
+ assert isinstance(serialized_content, str)
+
+ def test_agent_messages_integration(self):
+ """Test integration with actual agent messages."""
+ agent = Agent(task='Hello, world!', llm=ChatAnthropic(''))
+
+ messages = agent.message_manager.get_messages()
+ anthropic_messages, system_message = AnthropicMessageSerializer.serialize_messages(messages)
+
+ # System message should be properly handled
+ assert system_message is not None
+
+ def test_cache_cleaning_last_message_only(self):
+ """Test that only the last cache=True message remains cached."""
+ # Create multiple messages with cache=True
+ messages_list: list[BaseMessage] = [
+ UserMessage(content='First user message', cache=True),
+ AssistantMessage(content='First assistant message', cache=True),
+ UserMessage(content='Second user message', cache=True),
+ AssistantMessage(content='Second assistant message', cache=False),
+ UserMessage(content='Third user message', cache=True), # This should be the only one cached
+ ]
+
+ # Test the cleaning method directly (only accepts non-system messages)
+ normal_messages = cast(list[NonSystemMessage], [msg for msg in messages_list if not isinstance(msg, SystemMessage)])
+ cleaned_messages = AnthropicMessageSerializer._clean_cache_messages(normal_messages)
+
+ # Verify only the last cache=True message remains cached
+ assert not cleaned_messages[0].cache # First user message should be uncached
+ assert not cleaned_messages[1].cache # First assistant message should be uncached
+ assert not cleaned_messages[2].cache # Second user message should be uncached
+ assert not cleaned_messages[3].cache # Second assistant message was already uncached
+ assert cleaned_messages[4].cache # Third user message should remain cached
+
+ # Test through serialize_messages
+ serialized_messages, system_message = AnthropicMessageSerializer.serialize_messages(messages_list)
+
+ # Count how many messages have list content (indicating caching)
+ cached_content_count = sum(1 for msg in serialized_messages if isinstance(msg['content'], list))
+
+ # Only one message should have cached content
+ assert cached_content_count == 1
+
+ # The last message should be the cached one
+ assert isinstance(serialized_messages[-1]['content'], list)
+
+ def test_cache_cleaning_with_system_message(self):
+ """Test that system messages are not affected by cache cleaning logic."""
+ messages_list: list[BaseMessage] = [
+ SystemMessage(content='System message', cache=True), # System messages are handled separately
+ UserMessage(content='First user message', cache=True),
+ AssistantMessage(content='Assistant message', cache=True), # This should be the only normal message cached
+ ]
+
+ # Test through serialize_messages to see the full integration
+ serialized_messages, system_message = AnthropicMessageSerializer.serialize_messages(messages_list)
+
+ # System message should be cached
+ assert isinstance(system_message, list)
+
+ # Only one normal message should have cached content (the last one)
+ cached_content_count = sum(1 for msg in serialized_messages if isinstance(msg['content'], list))
+ assert cached_content_count == 1
+
+ # The last message should be the cached one
+ assert isinstance(serialized_messages[-1]['content'], list)
+
+ def test_cache_cleaning_no_cached_messages(self):
+ """Test that messages without cache=True are not affected."""
+ normal_messages_list = [
+ UserMessage(content='User message 1', cache=False),
+ AssistantMessage(content='Assistant message 1', cache=False),
+ UserMessage(content='User message 2', cache=False),
+ ]
+
+ cleaned_messages = AnthropicMessageSerializer._clean_cache_messages(normal_messages_list)
+
+ # All messages should remain uncached
+ for msg in cleaned_messages:
+ assert not msg.cache
+
+ def test_max_4_cache_blocks(self):
+ """Test that the max number of cache blocks is 4."""
+ agent = Agent(task='Hello, world!', llm=ChatAnthropic(''))
+ messages = agent.message_manager.get_messages()
+ anthropic_messages, system_message = AnthropicMessageSerializer.serialize_messages(messages)
+
+ logger.info(anthropic_messages)
+ logger.info(system_message)
+
+
+if __name__ == '__main__':
+ test_instance = TestAnthropicCache()
+ test_instance.test_cache_basic_functionality()
+ test_instance.test_cache_with_tool_calls()
+ test_instance.test_cache_with_images()
+ test_instance.test_cache_with_base64_images()
+ test_instance.test_cache_content_types()
+ test_instance.test_assistant_cache_empty_content()
+ test_instance.test_mixed_cache_scenarios()
+ test_instance.test_system_message_cache_behavior()
+ test_instance.test_agent_messages_integration()
+ test_instance.test_cache_cleaning_last_message_only()
+ test_instance.test_cache_cleaning_with_system_message()
+ test_instance.test_cache_cleaning_no_cached_messages()
+ test_instance.test_max_4_cache_blocks()
+ print('All cache tests passed!')
diff --git a/browser_use/llm/views.py b/browser_use/llm/views.py
index 136d1e1b4..4707db104 100644
--- a/browser_use/llm/views.py
+++ b/browser_use/llm/views.py
@@ -11,7 +11,16 @@ class ChatInvokeUsage(BaseModel):
"""
prompt_tokens: int
- """The number of tokens in the prompt."""
+ """The number of tokens in the prompt (this includes the cached tokens as well. When calculating the cost, subtract the cached tokens from the prompt tokens)"""
+
+ prompt_cached_tokens: int | None
+ """The number of cached tokens."""
+
+ prompt_cache_creation_tokens: int | None
+ """Anthropic only: The number of tokens used to create the cache."""
+
+ prompt_image_tokens: int | None
+ """Google only: The number of tokens in the image (prompt tokens is the text tokens + image tokens in that case)"""
completion_tokens: int
"""The number of tokens in the completion."""
@@ -19,9 +28,6 @@ class ChatInvokeUsage(BaseModel):
total_tokens: int
"""The total number of tokens in the response."""
- image_tokens: int | None = None
- """The number of tokens in the image. Google only (prompt tokens is the text tokens + image tokens in that case)"""
-
class ChatInvokeCompletion(BaseModel, Generic[T]):
"""
diff --git a/browser_use/tokens/service.py b/browser_use/tokens/service.py
index 594e84d82..e281c059e 100644
--- a/browser_use/tokens/service.py
+++ b/browser_use/tokens/service.py
@@ -18,7 +18,15 @@ from dotenv import load_dotenv
from browser_use.llm.base import BaseChatModel
from browser_use.llm.views import ChatInvokeUsage
-from browser_use.tokens.views import CachedPricingData, ModelPricing, ModelUsageStats, TokenUsageEntry, UsageSummary
+from browser_use.tokens.views import (
+ CachedPricingData,
+ ModelPricing,
+ ModelUsageStats,
+ ModelUsageTokens,
+ TokenCostCalculated,
+ TokenUsageEntry,
+ UsageSummary,
+)
load_dotenv()
@@ -170,31 +178,44 @@ class TokenCost:
max_tokens=data.get('max_tokens'),
max_input_tokens=data.get('max_input_tokens'),
max_output_tokens=data.get('max_output_tokens'),
+ cache_read_input_token_cost=data.get('cache_read_input_token_cost'),
+ cache_creation_input_token_cost=data.get('cache_creation_input_token_cost'),
)
- def calculate_cost(self, model: str, prompt_tokens: int, completion_tokens: int) -> tuple[float, float]:
- """Calculate cost for given token counts. Returns 0 if pricing data is not available or cost tracking is disabled."""
- if not self.include_cost or not self._pricing_data or model not in self._pricing_data:
- return 0.0, 0.0
-
- data = self._pricing_data[model]
- input_cost_per_token = data.get('input_cost_per_token', 0.0)
- output_cost_per_token = data.get('output_cost_per_token', 0.0)
+ async def calculate_cost(self, model: str, usage: ChatInvokeUsage) -> TokenCostCalculated | None:
+ if not self.include_cost:
+ return None
- input_cost = prompt_tokens * input_cost_per_token
- output_cost = completion_tokens * output_cost_per_token
+ data = await self.get_model_pricing(model)
+ if data is None:
+ return None
- return input_cost, output_cost
+ uncached_prompt_tokens = usage.prompt_tokens - (usage.prompt_cached_tokens or 0)
+
+ return TokenCostCalculated(
+ new_prompt_tokens=usage.prompt_tokens,
+ new_prompt_cost=uncached_prompt_tokens * (data.input_cost_per_token or 0),
+ # Cached tokens
+ prompt_read_cached_tokens=usage.prompt_cached_tokens,
+ prompt_read_cached_cost=usage.prompt_cached_tokens * data.cache_read_input_token_cost
+ if usage.prompt_cached_tokens and data.cache_read_input_token_cost
+ else None,
+ # Cache creation tokens
+ prompt_cached_creation_tokens=usage.prompt_cache_creation_tokens,
+ prompt_cache_creation_cost=usage.prompt_cache_creation_tokens * data.cache_creation_input_token_cost
+ if data.cache_creation_input_token_cost and usage.prompt_cache_creation_tokens
+ else None,
+ # Completion tokens
+ completion_tokens=usage.completion_tokens,
+ completion_cost=usage.completion_tokens * float(data.output_cost_per_token or 0),
+ )
def add_usage(self, model: str, usage: ChatInvokeUsage) -> TokenUsageEntry:
"""Add token usage entry to history (without calculating cost)"""
entry = TokenUsageEntry(
model=model,
timestamp=datetime.now(),
- prompt_tokens=usage.prompt_tokens,
- completion_tokens=usage.completion_tokens,
- total_tokens=usage.total_tokens,
- image_tokens=usage.image_tokens,
+ usage=usage,
)
self.usage_history.append(entry)
@@ -217,28 +238,63 @@ class TokenCost:
C_CYAN = '\033[96m'
C_YELLOW = '\033[93m'
C_GREEN = '\033[92m'
+ C_BLUE = '\033[94m'
C_RESET = '\033[0m'
- # Format tokens with k notation
- prompt_tokens_fmt = self._format_tokens(usage.prompt_tokens)
- completion_tokens_fmt = self._format_tokens(usage.completion_tokens)
+ # Always get cost breakdown for token details (even if not showing costs)
+ cost = await self.calculate_cost(model, usage.usage)
- # Format tokens with or without cost based on whether cost tracking is enabled
- if self.include_cost:
- input_cost, output_cost = self.calculate_cost(model, usage.prompt_tokens, usage.completion_tokens)
- cost = input_cost + output_cost
+ # Build input tokens breakdown
+ input_part = self._build_input_tokens_display(usage.usage, cost)
- if cost > 0:
- input_part = f'{C_YELLOW}{prompt_tokens_fmt} (${input_cost:.4f}){C_RESET}'
- output_part = f'{C_GREEN}{completion_tokens_fmt} (${output_cost:.4f}){C_RESET}'
- else:
- input_part = f'{C_YELLOW}{prompt_tokens_fmt}{C_RESET}'
- output_part = f'{C_GREEN}{completion_tokens_fmt}{C_RESET}'
+ # Build output tokens display
+ completion_tokens_fmt = self._format_tokens(usage.usage.completion_tokens)
+ if self.include_cost and cost and cost.completion_cost > 0:
+ output_part = f'📤 {C_GREEN}{completion_tokens_fmt} (${cost.completion_cost:.4f}){C_RESET}'
else:
- input_part = f'{C_YELLOW}{prompt_tokens_fmt}{C_RESET}'
- output_part = f'{C_GREEN}{completion_tokens_fmt}{C_RESET}'
+ output_part = f'📤 {C_GREEN}{completion_tokens_fmt}{C_RESET}'
+
+ cost_logger.info(f'🧠 {C_CYAN}{model}{C_RESET} | {input_part} | {output_part}')
+
+ def _build_input_tokens_display(self, usage: ChatInvokeUsage, cost: TokenCostCalculated | None) -> str:
+ """Build a clear display of input tokens breakdown with emojis and optional costs"""
+ C_YELLOW = '\033[93m'
+ C_BLUE = '\033[94m'
+ C_RESET = '\033[0m'
- cost_logger.info(f'🧠 llm : {C_CYAN}{model}{C_RESET} | ⬅️ tokens: {input_part} | ➡️ tokens: {output_part}')
+ parts = []
+
+ if cost:
+ # Calculate actual new tokens (non-cached)
+ new_tokens = usage.prompt_tokens - (usage.prompt_cached_tokens or 0)
+
+ if new_tokens > 0:
+ new_tokens_fmt = self._format_tokens(new_tokens)
+ if self.include_cost and cost.new_prompt_cost > 0:
+ parts.append(f'🆕 {C_YELLOW}{new_tokens_fmt} (${cost.new_prompt_cost:.4f}){C_RESET}')
+ else:
+ parts.append(f'🆕 {C_YELLOW}{new_tokens_fmt}{C_RESET}')
+
+ if usage.prompt_cached_tokens:
+ cached_tokens_fmt = self._format_tokens(usage.prompt_cached_tokens)
+ if self.include_cost and cost.prompt_read_cached_cost:
+ parts.append(f'💾 {C_BLUE}{cached_tokens_fmt} (${cost.prompt_read_cached_cost:.4f}){C_RESET}')
+ else:
+ parts.append(f'💾 {C_BLUE}{cached_tokens_fmt}{C_RESET}')
+
+ if usage.prompt_cache_creation_tokens:
+ creation_tokens_fmt = self._format_tokens(usage.prompt_cache_creation_tokens)
+ if self.include_cost and cost.prompt_cache_creation_cost:
+ parts.append(f'🔧 {C_BLUE}{creation_tokens_fmt} (${cost.prompt_cache_creation_cost:.4f}){C_RESET}')
+ else:
+ parts.append(f'🔧 {C_BLUE}{creation_tokens_fmt}{C_RESET}')
+
+ if not parts:
+ # Fallback to simple display
+ total_tokens_fmt = self._format_tokens(usage.prompt_tokens)
+ parts.append(f'📥 {C_YELLOW}{total_tokens_fmt}{C_RESET}')
+
+ return ' + '.join(parts)
def register_llm(self, llm: BaseChatModel) -> BaseChatModel:
"""
@@ -285,9 +341,19 @@ class TokenCost:
return llm
- def get_usage_summary(
- self, model: str | None = None, since: datetime | None = None, calculate_cost: bool = True
- ) -> UsageSummary:
+ def get_usage_tokens_for_model(self, model: str) -> ModelUsageTokens:
+ """Get usage tokens for a specific model"""
+ filtered_usage = [u for u in self.usage_history if u.model == model]
+
+ return ModelUsageTokens(
+ model=model,
+ prompt_tokens=sum(u.usage.prompt_tokens for u in filtered_usage),
+ prompt_cached_tokens=sum(u.usage.prompt_cached_tokens or 0 for u in filtered_usage),
+ completion_tokens=sum(u.usage.completion_tokens for u in filtered_usage),
+ total_tokens=sum(u.usage.prompt_tokens + u.usage.completion_tokens for u in filtered_usage),
+ )
+
+ async def get_usage_summary(self, model: str | None = None, since: datetime | None = None) -> UsageSummary:
"""Get summary of token usage and costs (costs calculated on-the-fly)"""
filtered_usage = self.usage_history
@@ -301,6 +367,8 @@ class TokenCost:
return UsageSummary(
total_prompt_tokens=0,
total_prompt_cost=0.0,
+ total_prompt_cached_tokens=0,
+ total_prompt_cached_cost=0.0,
total_completion_tokens=0,
total_completion_cost=0.0,
total_tokens=0,
@@ -309,31 +377,35 @@ class TokenCost:
)
# Calculate totals
- total_prompt = sum(u.prompt_tokens for u in filtered_usage)
- total_completion = sum(u.completion_tokens for u in filtered_usage)
- total_tokens = sum(u.total_tokens for u in filtered_usage)
+ total_prompt = sum(u.usage.prompt_tokens for u in filtered_usage)
+ total_completion = sum(u.usage.completion_tokens for u in filtered_usage)
+ total_tokens = total_prompt + total_completion
+ total_prompt_cached = sum(u.usage.prompt_cached_tokens or 0 for u in filtered_usage)
models = list({u.model for u in filtered_usage})
- # Calculate per-model stats with on-the-fly cost calculation
+ # Calculate per-model stats with record-by-record cost calculation
model_stats: dict[str, ModelUsageStats] = {}
total_prompt_cost = 0.0
total_completion_cost = 0.0
+ total_prompt_cached_cost = 0.0
for entry in filtered_usage:
if entry.model not in model_stats:
model_stats[entry.model] = ModelUsageStats(model=entry.model)
stats = model_stats[entry.model]
- stats.prompt_tokens += entry.prompt_tokens
- stats.completion_tokens += entry.completion_tokens
- stats.total_tokens += entry.total_tokens
+ stats.prompt_tokens += entry.usage.prompt_tokens
+ stats.completion_tokens += entry.usage.completion_tokens
+ stats.total_tokens += entry.usage.prompt_tokens + entry.usage.completion_tokens
stats.invocations += 1
- if calculate_cost:
- # Calculate cost on-the-fly
- input_cost, output_cost = self.calculate_cost(entry.model, entry.prompt_tokens, entry.completion_tokens)
- total_prompt_cost += input_cost
- total_completion_cost += output_cost
+ if self.include_cost:
+ # Calculate cost record by record using the updated calculate_cost function
+ cost = await self.calculate_cost(entry.model, entry.usage)
+ if cost:
+ total_prompt_cost += cost.prompt_cost
+ total_completion_cost += cost.completion_cost
+ total_prompt_cached_cost += cost.prompt_read_cached_cost or 0
# Calculate averages
for stats in model_stats.values():
@@ -343,10 +415,12 @@ class TokenCost:
return UsageSummary(
total_prompt_tokens=total_prompt,
total_prompt_cost=total_prompt_cost,
+ total_prompt_cached_tokens=total_prompt_cached,
+ total_prompt_cached_cost=total_prompt_cached_cost,
total_completion_tokens=total_completion,
total_completion_cost=total_completion_cost,
total_tokens=total_tokens,
- total_cost=total_prompt_cost + total_completion_cost,
+ total_cost=total_prompt_cost + total_completion_cost + total_prompt_cached_cost,
entry_count=len(filtered_usage),
models=models,
by_model=model_stats,
@@ -367,7 +441,7 @@ class TokenCost:
if not self.usage_history:
return
- summary = self.get_usage_summary(calculate_cost=self.include_cost)
+ summary = await self.get_usage_summary()
if summary.entry_count == 0:
return
@@ -422,9 +496,10 @@ class TokenCost:
# Calculate costs for this model
for entry in self.usage_history:
if entry.model == model:
- input_cost, output_cost = self.calculate_cost(entry.model, entry.prompt_tokens, entry.completion_tokens)
- model_prompt_cost += input_cost
- model_completion_cost += output_cost
+ cost = await self.calculate_cost(entry.model, entry.usage)
+ if cost:
+ model_prompt_cost += cost.prompt_cost
+ model_completion_cost += cost.completion_cost
total_model_cost = model_prompt_cost + model_completion_cost
@@ -447,9 +522,9 @@ class TokenCost:
f'📞 {stats.invocations} calls | 📈 {avg_tokens_fmt}/call'
)
- def get_cost_by_model(self) -> dict[str, ModelUsageStats]:
+ async def get_cost_by_model(self) -> dict[str, ModelUsageStats]:
"""Get cost breakdown by model"""
- summary = self.get_usage_summary(calculate_cost=self.include_cost)
+ summary = await self.get_usage_summary()
return summary.by_model
def clear_history(self) -> None:
diff --git a/browser_use/tokens/tests/test_cost.py b/browser_use/tokens/tests/test_cost.py
index d88fd789a..2fec84688 100644
--- a/browser_use/tokens/tests/test_cost.py
+++ b/browser_use/tokens/tests/test_cost.py
@@ -70,7 +70,7 @@ Only output the country name, no numbers, no punctuation, just the name."""
print('\n💰 Cost Summary')
print('=' * 80)
- summary = tc.get_usage_summary()
+ summary = await tc.get_usage_summary()
print(f'Total calls: {summary.entry_count}')
print(f'Total tokens: {summary.total_tokens:,}')
print(f'Total cost: ${summary.total_cost:.6f}')
diff --git a/browser_use/tokens/views.py b/browser_use/tokens/views.py
index 16bf8569c..b044a7dad 100644
--- a/browser_use/tokens/views.py
+++ b/browser_use/tokens/views.py
@@ -3,6 +3,8 @@ from typing import Any, TypeVar
from pydantic import BaseModel, Field
+from browser_use.llm.views import ChatInvokeUsage
+
T = TypeVar('T', bound=BaseModel)
@@ -11,21 +13,52 @@ class TokenUsageEntry(BaseModel):
model: str
timestamp: datetime
- prompt_tokens: int
+ usage: ChatInvokeUsage
+
+
+class TokenCostCalculated(BaseModel):
+ """Token cost"""
+
+ new_prompt_tokens: int
+ new_prompt_cost: float
+
+ prompt_read_cached_tokens: int | None
+ prompt_read_cached_cost: float | None
+
+ prompt_cached_creation_tokens: int | None
+ prompt_cache_creation_cost: float | None
+ """Anthropic only: The cost of creating the cache."""
+
completion_tokens: int
- total_tokens: int
- image_tokens: int | None = None
+ completion_cost: float
+
+ @property
+ def prompt_cost(self) -> float:
+ return self.new_prompt_cost + (self.prompt_read_cached_cost or 0) + (self.prompt_cache_creation_cost or 0)
+
+ @property
+ def total_cost(self) -> float:
+ return (
+ self.new_prompt_cost
+ + (self.prompt_read_cached_cost or 0)
+ + (self.prompt_cache_creation_cost or 0)
+ + self.completion_cost
+ )
class ModelPricing(BaseModel):
"""Pricing information for a model"""
model: str
- input_cost_per_token: float | None = None
- output_cost_per_token: float | None = None
- max_tokens: int | None = None
- max_input_tokens: int | None = None
- max_output_tokens: int | None = None
+ input_cost_per_token: float | None
+ output_cost_per_token: float | None
+
+ cache_read_input_token_cost: float | None
+ cache_creation_input_token_cost: float | None
+
+ max_tokens: int | None
+ max_input_tokens: int | None
+ max_output_tokens: int | None
class CachedPricingData(BaseModel):
@@ -47,11 +80,25 @@ class ModelUsageStats(BaseModel):
average_tokens_per_invocation: float = 0.0
+class ModelUsageTokens(BaseModel):
+ """Usage tokens for a single model"""
+
+ model: str
+ prompt_tokens: int
+ prompt_cached_tokens: int
+ completion_tokens: int
+ total_tokens: int
+
+
class UsageSummary(BaseModel):
"""Summary of token usage and costs"""
total_prompt_tokens: int
total_prompt_cost: float
+
+ total_prompt_cached_tokens: int
+ total_prompt_cached_cost: float
+
total_completion_tokens: int
total_completion_cost: float
total_tokens: int
diff --git a/examples/models/claude-3.7-sonnet.py b/examples/models/claude-4-sonnet.py
similarity index 83%
rename from examples/models/claude-3.7-sonnet.py
rename to examples/models/claude-4-sonnet.py
index 7170b7abc..defa8914d 100644
--- a/examples/models/claude-3.7-sonnet.py
+++ b/examples/models/claude-4-sonnet.py
@@ -10,13 +10,15 @@ import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from dotenv import load_dotenv
+from lmnr import Laminar
load_dotenv()
+Laminar.initialize()
from browser_use import Agent
from browser_use.llm import ChatAnthropic
-llm = ChatAnthropic(model='claude-3-7-sonnet-20250219', temperature=0.0)
+llm = ChatAnthropic(model='claude-4-sonnet-20250514', temperature=0.0)
agent = Agent(
task='Go to amazon.com, search for laptop, sort by best rating, and give me the price of the first result',
diff --git a/examples/models/gemini.py b/examples/models/gemini.py
index aa8941b50..fbb660246 100644
--- a/examples/models/gemini.py
+++ b/examples/models/gemini.py
@@ -5,9 +5,12 @@ import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from dotenv import load_dotenv
+from lmnr import Laminar
load_dotenv()
+Laminar.initialize()
+
from browser_use import Agent
from browser_use.browser import BrowserProfile, BrowserSession
diff --git a/examples/models/gpt-4.1.py b/examples/models/gpt-4.1.py
index 9c4106abc..b5ffc9bb6 100644
--- a/examples/models/gpt-4.1.py
+++ b/examples/models/gpt-4.1.py
@@ -11,12 +11,16 @@ import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from dotenv import load_dotenv
-
-load_dotenv()
+from lmnr import Laminar
from browser_use import Agent
from browser_use.llm import ChatOpenAI
+load_dotenv()
+
+
+Laminar.initialize()
+
# All the models are type safe from OpenAI in case you need a list of supported models
llm = ChatOpenAI(model='gpt-4.1')
agent = Agent(
diff --git a/pyproject.toml b/pyproject.toml
index 94c8e5707..640b4c3b9 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -182,5 +182,6 @@ dev-dependencies = [
"ty>=0.0.1a1",
"pytest-xdist>=3.7.0",
"pillow>=11.2.1",
+ "lmnr>=0.6.13",
# "pytest-playwright-asyncio>=0.7.0", # not actually needed I think
]