|
| 1 | +# How to run this example: |
| 2 | +# uv run python -m playwright install chromium |
| 3 | +# uv run -m examples.tools.computer_use |
| 4 | + |
1 | 5 | import asyncio |
2 | 6 | import base64 |
3 | | -from typing import Literal, Union |
| 7 | +import sys |
| 8 | +from typing import Any, Literal, Union |
4 | 9 |
|
5 | 10 | from playwright.async_api import Browser, Page, Playwright, async_playwright |
6 | 11 |
|
7 | 12 | from agents import ( |
8 | 13 | Agent, |
9 | 14 | AsyncComputer, |
10 | 15 | Button, |
| 16 | + ComputerProvider, |
11 | 17 | ComputerTool, |
12 | 18 | Environment, |
13 | 19 | ModelSettings, |
| 20 | + RunContextWrapper, |
14 | 21 | Runner, |
15 | 22 | trace, |
16 | 23 | ) |
|
21 | 28 | # logging.getLogger("openai.agents").addHandler(logging.StreamHandler()) |
22 | 29 |
|
23 | 30 |
|
24 | | -async def main(): |
25 | | - async with LocalPlaywrightComputer() as computer: |
26 | | - with trace("Computer use example"): |
27 | | - agent = Agent( |
28 | | - name="Browser user", |
29 | | - instructions="You are a helpful agent.", |
30 | | - tools=[ComputerTool(computer)], |
31 | | - # Use the computer using model, and set truncation to auto because its required |
32 | | - model="computer-use-preview", |
33 | | - model_settings=ModelSettings(truncation="auto"), |
34 | | - ) |
35 | | - result = await Runner.run(agent, "Search for SF sports news and summarize.") |
36 | | - print(result.final_output) |
37 | | - |
38 | | - |
39 | 31 | CUA_KEY_TO_PLAYWRIGHT_KEY = { |
40 | 32 | "/": "Divide", |
41 | 33 | "\\": "Backslash", |
@@ -93,6 +85,16 @@ async def __aexit__(self, exc_type, exc_val, exc_tb): |
93 | 85 | await self._browser.close() |
94 | 86 | if self._playwright: |
95 | 87 | await self._playwright.stop() |
| 88 | + return None |
| 89 | + |
| 90 | + async def open(self) -> "LocalPlaywrightComputer": |
| 91 | + """Open resources without using a context manager.""" |
| 92 | + await self.__aenter__() |
| 93 | + return self |
| 94 | + |
| 95 | + async def close(self) -> None: |
| 96 | + """Close resources without using a context manager.""" |
| 97 | + await self.__aexit__(None, None, None) |
96 | 98 |
|
97 | 99 | @property |
98 | 100 | def playwright(self) -> Playwright: |
@@ -164,5 +166,53 @@ async def drag(self, path: list[tuple[int, int]]) -> None: |
164 | 166 | await self.page.mouse.up() |
165 | 167 |
|
166 | 168 |
|
| 169 | +async def run_agent( |
| 170 | + computer_config: ComputerProvider[LocalPlaywrightComputer] | AsyncComputer, |
| 171 | +) -> None: |
| 172 | + with trace("Computer use example"): |
| 173 | + agent = Agent( |
| 174 | + name="Browser user", |
| 175 | + instructions="You are a helpful agent. Find the current weather in Tokyo.", |
| 176 | + tools=[ComputerTool(computer=computer_config)], |
| 177 | + # Use the computer using model, and set truncation to auto because it is required. |
| 178 | + model="computer-use-preview", |
| 179 | + model_settings=ModelSettings(truncation="auto"), |
| 180 | + ) |
| 181 | + result = await Runner.run(agent, "What is the weather in Tokyo right now?") |
| 182 | + print(result.final_output) |
| 183 | + |
| 184 | + |
| 185 | +async def singleton_computer() -> None: |
| 186 | + # Use a shared computer when you do not expect to run multiple agents concurrently. |
| 187 | + async with LocalPlaywrightComputer() as computer: |
| 188 | + await run_agent(computer) |
| 189 | + |
| 190 | + |
| 191 | +async def computer_per_request() -> None: |
| 192 | + # Initialize a new computer per request to avoid sharing state between runs. |
| 193 | + async def create_computer(*, run_context: RunContextWrapper[Any]) -> LocalPlaywrightComputer: |
| 194 | + print(f"Creating computer for run context: {run_context}") |
| 195 | + return await LocalPlaywrightComputer().open() |
| 196 | + |
| 197 | + async def dispose_computer( |
| 198 | + *, |
| 199 | + run_context: RunContextWrapper[Any], |
| 200 | + computer: LocalPlaywrightComputer, |
| 201 | + ) -> None: |
| 202 | + print(f"Disposing computer for run context: {run_context}") |
| 203 | + await computer.close() |
| 204 | + |
| 205 | + await run_agent( |
| 206 | + ComputerProvider[LocalPlaywrightComputer]( |
| 207 | + create=create_computer, |
| 208 | + dispose=dispose_computer, |
| 209 | + ) |
| 210 | + ) |
| 211 | + |
| 212 | + |
167 | 213 | if __name__ == "__main__": |
168 | | - asyncio.run(main()) |
| 214 | + mode = (sys.argv[1] if len(sys.argv) > 1 else "").lower() |
| 215 | + if mode == "singleton": |
| 216 | + asyncio.run(singleton_computer()) |
| 217 | + else: |
| 218 | + asyncio.run(computer_per_request()) |
0 commit comments