-
Notifications
You must be signed in to change notification settings - Fork 5
Anthropic CUA Template update (Playwright -> Computer Controls) #72
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
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
fba8a7c
first pass at using kernel computer controls instead of playwright
tnsardesai 1c9f88a
Anthropic CUA - Update Python Template + fix remaining TS aspects
dprevoznik 3df2243
feat(templates): update Anthropic Computer Use templates with 1024x76…
dprevoznik 6801fa2
Update templates.go
dprevoznik 45af9fb
Update qa.md with new queries for anthropic templates
dprevoznik af0c233
fix(anthropic-cua): address PR review feedback for robustness and con…
dprevoznik 7df0d8a
fix(anthropic-cua): use 120px scroll multiplier to match Anthropic xd…
dprevoznik ac3baaa
fix(ts-anthropic-cua): add try/finally to ensure browser session cleanup
dprevoznik 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
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
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 |
|---|---|---|
| @@ -1,7 +1,47 @@ | ||
| # Kernel Python Sample App - Anthropic Computer Use | ||
|
|
||
| This is a simple Kernel application that implements a prompt loop using Anthropic Computer Use. | ||
| This is a Kernel application that implements a prompt loop using Anthropic Computer Use with Kernel's Computer Controls API. | ||
|
|
||
| It generally follows the [Anthropic Reference Implementation](https://github.com/anthropics/anthropic-quickstarts/tree/main/computer-use-demo) but replaces `xodotool` and `gnome-screenshot` with Playwright. | ||
| It generally follows the [Anthropic Reference Implementation](https://github.com/anthropics/anthropic-quickstarts/tree/main/computer-use-demo) but uses Kernel's Computer Controls API instead of `xdotool` and `gnome-screenshot`. | ||
|
|
||
| See the [docs](https://www.kernel.sh/docs/quickstart) for information. | ||
| ## Setup | ||
|
|
||
| 1. Get your API keys: | ||
| - **Kernel**: [dashboard.onkernel.com](https://dashboard.onkernel.com) | ||
| - **Anthropic**: [console.anthropic.com](https://console.anthropic.com) | ||
|
|
||
| 2. Deploy the app: | ||
| ```bash | ||
| kernel login | ||
| cp .env.example .env # Add your ANTHROPIC_API_KEY | ||
| kernel deploy main.py --env-file .env | ||
| ``` | ||
|
|
||
| ## Usage | ||
|
|
||
| ```bash | ||
| kernel invoke python-anthropic-cua cua-task --payload '{"query": "Navigate to https://example.com and describe the page"}' | ||
| ``` | ||
|
|
||
| ## Recording Replays | ||
|
|
||
| > **Note:** Replay recording is only available to Kernel users on paid plans. | ||
|
|
||
| Add `"record_replay": true` to your payload to capture a video of the browser session: | ||
|
|
||
| ```bash | ||
| kernel invoke python-anthropic-cua cua-task --payload '{"query": "Navigate to https://example.com", "record_replay": true}' | ||
| ``` | ||
|
|
||
| When enabled, the response will include a `replay_url` field with a link to view the recorded session. | ||
|
|
||
| ## Known Limitations | ||
|
|
||
| ### Cursor Position | ||
|
|
||
| The `cursor_position` action is not supported with Kernel's Computer Controls API. If the model attempts to use this action, an error will be returned. This is a known limitation that does not significantly impact most computer use workflows, as the model typically tracks cursor position through screenshots. | ||
|
|
||
| ## Resources | ||
|
|
||
| - [Anthropic Computer Use Documentation](https://docs.anthropic.com/en/docs/build-with-claude/computer-use) | ||
| - [Kernel Documentation](https://www.kernel.sh/docs/quickstart) |
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
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 |
|---|---|---|
| @@ -1,97 +1,92 @@ | ||
| import os | ||
| from typing import Dict, TypedDict | ||
| from typing import Dict, Optional, TypedDict | ||
|
|
||
| import kernel | ||
| from kernel import Kernel | ||
| from loop import sampling_loop | ||
| from playwright.async_api import async_playwright | ||
| from session import KernelBrowserSession | ||
|
|
||
|
|
||
| class QueryInput(TypedDict): | ||
| query: str | ||
| record_replay: Optional[bool] | ||
|
|
||
|
|
||
| class QueryOutput(TypedDict): | ||
| result: str | ||
| replay_url: Optional[str] | ||
|
|
||
|
|
||
| api_key = os.getenv("ANTHROPIC_API_KEY") | ||
| if not api_key: | ||
| raise ValueError("ANTHROPIC_API_KEY is not set") | ||
|
|
||
| client = Kernel() | ||
| app = kernel.App("python-anthropic-cua") | ||
|
|
||
|
|
||
| @app.action("cua-task") | ||
| async def cua_task( | ||
| ctx: kernel.KernelContext, | ||
| payload: QueryInput, | ||
| ) -> QueryOutput: | ||
| # A function that processes a user query using a browser-based sampling loop | ||
|
|
||
| # Args: | ||
| # ctx: Kernel context containing invocation information | ||
| # payload: An object containing a query string to process | ||
|
|
||
| # Returns: | ||
| # A dictionary containing the result of the sampling loop as a string | ||
| """ | ||
| Process a user query using Anthropic Computer Use with Kernel's browser automation. | ||
|
|
||
| Args: | ||
| ctx: Kernel context containing invocation information | ||
| payload: An object containing: | ||
| - query: The task/query string to process | ||
| - record_replay: Optional boolean to enable video replay recording | ||
|
|
||
| Returns: | ||
| A dictionary containing: | ||
| - result: The result of the sampling loop as a string | ||
| - replay_url: URL to view the replay (if recording was enabled) | ||
| """ | ||
| if not payload or not payload.get("query"): | ||
| raise ValueError("Query is required") | ||
|
|
||
| kernel_browser = client.browsers.create( | ||
| invocation_id=ctx.invocation_id, stealth=True | ||
| ) | ||
| print("Kernel browser live view url: ", kernel_browser.browser_live_view_url) | ||
|
|
||
| try: | ||
| async with async_playwright() as playwright: | ||
| browser = await playwright.chromium.connect_over_cdp( | ||
| kernel_browser.cdp_ws_url | ||
| ) | ||
| context = ( | ||
| browser.contexts[0] if browser.contexts else await browser.new_context() | ||
| record_replay = payload.get("record_replay", False) | ||
|
|
||
| async with KernelBrowserSession( | ||
| stealth=True, | ||
| record_replay=record_replay, | ||
| ) as session: | ||
| print("Kernel browser live view url:", session.live_view_url) | ||
|
|
||
| final_messages = await sampling_loop( | ||
| model="claude-sonnet-4-5-20250929", | ||
| messages=[ | ||
| { | ||
| "role": "user", | ||
| "content": payload["query"], | ||
| } | ||
| ], | ||
| api_key=str(api_key), | ||
| thinking_budget=1024, | ||
| kernel=session.kernel, | ||
| session_id=session.session_id, | ||
| ) | ||
|
|
||
| if not final_messages: | ||
| raise ValueError("No messages were generated during the sampling loop") | ||
|
|
||
| last_message = final_messages[-1] | ||
| if not last_message: | ||
| raise ValueError( | ||
| "Failed to get the last message from the sampling loop" | ||
| ) | ||
| page = context.pages[0] if context.pages else await context.new_page() | ||
|
|
||
| # Run the sampling loop | ||
| final_messages = await sampling_loop( | ||
| model="claude-sonnet-4-20250514", | ||
| messages=[ | ||
| { | ||
| "role": "user", | ||
| "content": payload["query"], | ||
| } | ||
| ], | ||
| api_key=str(api_key), | ||
| thinking_budget=1024, | ||
| playwright_page=page, | ||
|
|
||
| result = "" | ||
| if isinstance(last_message.get("content"), str): | ||
| result = last_message["content"] # type: ignore[assignment] | ||
| else: | ||
| result = "".join( | ||
| block["text"] | ||
| for block in last_message["content"] # type: ignore[index] | ||
| if isinstance(block, Dict) and block.get("type") == "text" | ||
| ) | ||
|
|
||
| # Extract the final result | ||
| if not final_messages: | ||
| raise ValueError("No messages were generated during the sampling loop") | ||
|
|
||
| last_message = final_messages[-1] | ||
| if not last_message: | ||
| raise ValueError( | ||
| "Failed to get the last message from the sampling loop" | ||
| ) | ||
|
|
||
| result = "" | ||
| if isinstance(last_message.get("content"), str): | ||
| result = last_message["content"] # type: ignore[assignment] | ||
| else: | ||
| result = "".join( | ||
| block["text"] | ||
| for block in last_message["content"] # type: ignore[index] | ||
| if isinstance(block, Dict) and block.get("type") == "text" | ||
| ) | ||
|
|
||
| return {"result": result} | ||
| except Exception as exc: | ||
| print(f"Error in sampling loop: {exc}") | ||
| raise | ||
| finally: | ||
| if browser is not None: | ||
| await browser.close() | ||
| client.browsers.delete_by_id(kernel_browser.session_id) | ||
| return { | ||
| "result": result, | ||
| "replay_url": session.replay_view_url, | ||
| } |
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.
Uh oh!
There was an error while loading. Please reload this page.