-
Notifications
You must be signed in to change notification settings - Fork 39
Fix stagehand.metrics #176
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
miguelg719
wants to merge
2
commits into
main
Choose a base branch
from
miguel/stg-663-fix-stagehandmetrics-in-python
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
--- | ||
"stagehand": patch | ||
--- | ||
|
||
Fix stagehand.metrics on env:BROWSERBASE |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -9,7 +9,19 @@ description = "Python SDK for Stagehand" | |
readme = "README.md" | ||
classifiers = [ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent",] | ||
requires-python = ">=3.9" | ||
dependencies = [ "httpx>=0.24.0", "python-dotenv>=1.0.0", "pydantic>=1.10.0", "playwright>=1.42.1", "requests>=2.31.0", "browserbase>=1.4.0", "rich>=13.7.0", "openai>=1.83.0", "anthropic>=0.51.0", "litellm>=1.72.0",] | ||
dependencies = [ | ||
"httpx>=0.24.0", | ||
"python-dotenv>=1.0.0", | ||
"pydantic>=1.10.0", | ||
"playwright>=1.42.1", | ||
"requests>=2.31.0", | ||
"browserbase>=1.4.0", | ||
"rich>=13.7.0", | ||
"openai>=1.83.0", | ||
"anthropic>=0.51.0", | ||
"litellm>=1.72.0", | ||
"nest-asyncio>=1.6.0", | ||
] | ||
[[project.authors]] | ||
name = "Browserbase, Inc." | ||
email = "[email protected]" | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -5,7 +5,7 @@ | |
|
||
from .utils import convert_dict_keys_to_camel_case | ||
|
||
__all__ = ["_create_session", "_execute"] | ||
__all__ = ["_create_session", "_execute", "_get_replay_metrics"] | ||
|
||
|
||
async def _create_session(self): | ||
|
@@ -177,3 +177,91 @@ async def _execute(self, method: str, payload: dict[str, Any]) -> Any: | |
except Exception as e: | ||
self.logger.error(f"[EXCEPTION] {str(e)}") | ||
raise | ||
|
||
|
||
async def _get_replay_metrics(self): | ||
""" | ||
Fetch replay metrics from the API endpoint /sessions/:id/replay and parse them | ||
into StagehandMetrics format. | ||
""" | ||
from .metrics import StagehandMetrics | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. move import |
||
|
||
if not self.session_id: | ||
raise ValueError("session_id is required to fetch metrics.") | ||
|
||
headers = { | ||
"x-bb-api-key": self.browserbase_api_key, | ||
"x-bb-project-id": self.browserbase_project_id, | ||
"Content-Type": "application/json", | ||
} | ||
|
||
try: | ||
response = await self._client.get( | ||
f"{self.api_url}/sessions/{self.session_id}/replay", | ||
headers=headers, | ||
) | ||
|
||
if response.status_code != 200: | ||
error_text = ( | ||
await response.aread() if hasattr(response, "aread") else response.text | ||
) | ||
self.logger.error( | ||
f"[HTTP ERROR] Failed to fetch metrics. Status {response.status_code}: {error_text}" | ||
) | ||
raise RuntimeError( | ||
f"Failed to fetch metrics with status {response.status_code}: {error_text}" | ||
) | ||
|
||
data = response.json() | ||
|
||
if not data.get("success"): | ||
raise RuntimeError( | ||
f"Failed to fetch metrics: {data.get('error', 'Unknown error')}" | ||
) | ||
|
||
# Parse the API data into StagehandMetrics format | ||
api_data = data.get("data", {}) | ||
metrics = StagehandMetrics() | ||
|
||
# Parse pages and their actions | ||
pages = api_data.get("pages", []) | ||
for page in pages: | ||
actions = page.get("actions", []) | ||
for action in actions: | ||
# Get method name and token usage | ||
method = action.get("method", "").lower() | ||
token_usage = action.get("tokenUsage", {}) | ||
|
||
if token_usage: | ||
input_tokens = token_usage.get("inputTokens", 0) | ||
output_tokens = token_usage.get("outputTokens", 0) | ||
time_ms = token_usage.get("timeMs", 0) | ||
|
||
# Map method to metrics fields | ||
if method == "act": | ||
metrics.act_prompt_tokens += input_tokens | ||
metrics.act_completion_tokens += output_tokens | ||
metrics.act_inference_time_ms += time_ms | ||
elif method == "extract": | ||
metrics.extract_prompt_tokens += input_tokens | ||
metrics.extract_completion_tokens += output_tokens | ||
metrics.extract_inference_time_ms += time_ms | ||
elif method == "observe": | ||
metrics.observe_prompt_tokens += input_tokens | ||
metrics.observe_completion_tokens += output_tokens | ||
metrics.observe_inference_time_ms += time_ms | ||
elif method == "agent": | ||
metrics.agent_prompt_tokens += input_tokens | ||
metrics.agent_completion_tokens += output_tokens | ||
metrics.agent_inference_time_ms += time_ms | ||
|
||
# Always update totals for any method with token usage | ||
metrics.total_prompt_tokens += input_tokens | ||
metrics.total_completion_tokens += output_tokens | ||
metrics.total_inference_time_ms += time_ms | ||
|
||
return metrics | ||
|
||
except Exception as e: | ||
self.logger.error(f"[EXCEPTION] Error fetching replay metrics: {str(e)}") | ||
raise |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
remove