Skip to content

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

replace aiofiles with anyio.Path

Cyrus9d7dfd773867
diff --git a/browser_use/dom/playground/tree.py b/browser_use/dom/playground/tree.py
index 2039f769a..9a049c39c 100644
--- a/browser_use/dom/playground/tree.py
+++ b/browser_use/dom/playground/tree.py
@@ -2,7 +2,7 @@ import asyncio
import json
import time
-import aiofiles
+import anyio
from browser_use.browser import BrowserProfile, BrowserSession
from browser_use.browser.types import ViewportSize
@@ -67,8 +67,7 @@ async def main():
end = time.time()
print(f'Time taken: {end - start} seconds')
- async with aiofiles.open('tmp/enhanced_dom_tree.json', 'w') as f:
- await f.write(json.dumps(dom_tree.__json__(), indent=1))
+ await anyio.Path('tmp/enhanced_dom_tree.json').write_text(json.dumps(dom_tree.__json__(), indent=1))
print('Saved enhanced dom tree to tmp/enhanced_dom_tree.json')
@@ -95,8 +94,7 @@ async def main():
serialized_dom_state, timing_info = await dom_service.get_serialized_dom_tree()
- async with aiofiles.open('tmp/serialized_dom_tree.txt', 'w') as f:
- await f.write(serialized_dom_state.llm_representation())
+ await anyio.Path('tmp/serialized_dom_tree.txt').write_text(serialized_dom_state.llm_representation())
# print(serialized)
print('Saved serialized dom tree to tmp/serialized_dom_tree.txt')
@@ -106,14 +104,11 @@ async def main():
end = time.time()
print(f'Time taken: {end - start} seconds')
- async with aiofiles.open('tmp/snapshot.json', 'w') as f:
- await f.write(json.dumps(snapshot, indent=1))
+ await anyio.Path('tmp/snapshot.json').write_text(json.dumps(snapshot, indent=1))
- async with aiofiles.open('tmp/dom_tree.json', 'w') as f:
- await f.write(json.dumps(dom_tree, indent=1))
+ await anyio.Path('tmp/dom_tree.json').write_text(json.dumps(dom_tree, indent=1))
- async with aiofiles.open('tmp/ax_tree.json', 'w') as f:
- await f.write(json.dumps(ax_tree, indent=1))
+ await anyio.Path('tmp/ax_tree.json').write_text(json.dumps(ax_tree, indent=1))
print('saved dom tree to tmp/dom_tree.json')
print('saved snapshot to tmp/snapshot.json')
diff --git a/browser_use/integrations/gmail/service.py b/browser_use/integrations/gmail/service.py
index 3658a3036..00cf2f995 100644
--- a/browser_use/integrations/gmail/service.py
+++ b/browser_use/integrations/gmail/service.py
@@ -10,7 +10,7 @@ import os
from pathlib import Path
from typing import Any
-import aiofiles
+import anyio
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
@@ -123,8 +123,7 @@ class GmailService:
self.creds = flow.run_local_server(port=8080, open_browser=True)
# Save tokens for next time
- async with aiofiles.open(self.token_file, 'w') as token:
- await token.write(self.creds.to_json())
+ await anyio.Path(self.token_file).write_text(self.creds.to_json())
logger.info(f'💾 Tokens saved to {self.token_file}')
# Build Gmail service
diff --git a/browser_use/tokens/service.py b/browser_use/tokens/service.py
index 2eca9a708..8a12d9939 100644
--- a/browser_use/tokens/service.py
+++ b/browser_use/tokens/service.py
@@ -12,7 +12,7 @@ from datetime import datetime, timedelta
from pathlib import Path
from typing import Any
-import aiofiles
+import anyio
import httpx
from dotenv import load_dotenv
@@ -113,9 +113,7 @@ class TokenCost:
return False
# Read the cached data
- async with aiofiles.open(cache_file, 'r') as f:
- content = await f.read()
- cached = CachedPricingData.model_validate_json(content)
+ cached = CachedPricingData.model_validate_json(await anyio.Path(cache_file).read_text())
# Check if cache is still valid
return datetime.now() - cached.timestamp < self.CACHE_DURATION
@@ -125,10 +123,9 @@ class TokenCost:
async def _load_from_cache(self, cache_file: Path) -> None:
"""Load pricing data from a specific cache file"""
try:
- async with aiofiles.open(cache_file, 'r') as f:
- content = await f.read()
- cached = CachedPricingData.model_validate_json(content)
- self._pricing_data = cached.data
+ content = await anyio.Path(cache_file).read_text()
+ cached = CachedPricingData.model_validate_json(content)
+ self._pricing_data = cached.data
except Exception as e:
logger.debug(f'Error loading cached pricing data from {cache_file}: {e}')
# Fall back to fetching
@@ -153,9 +150,7 @@ class TokenCost:
timestamp_str = datetime.now().strftime('%Y%m%d_%H%M%S')
cache_file = self._cache_dir / f'pricing_{timestamp_str}.json'
- async with aiofiles.open(cache_file, 'w') as f:
- await f.write(cached.model_dump_json(indent=2))
-
+ await anyio.Path(cache_file).write_text(cached.model_dump_json(indent=2))
except Exception as e:
logger.debug(f'Error fetching pricing data: {e}')
# Fall back to empty pricing data
diff --git a/examples/custom-functions/file_upload.py b/examples/custom-functions/file_upload.py
index 5ef3af752..9f9e4794a 100644
--- a/examples/custom-functions/file_upload.py
+++ b/examples/custom-functions/file_upload.py
@@ -9,7 +9,7 @@ import logging
import os
import sys
-import aiofiles
+import anyio
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
@@ -83,8 +83,7 @@ async def main():
# Create test files if they don't exist
for file_path in available_file_paths:
if not os.path.exists(file_path):
- async with aiofiles.open(file_path, 'w') as f:
- await f.write('Test file content for upload example')
+ await anyio.Path(file_path).write_text('Test file content for upload example')
# Create the agent with file upload capability
agent = Agent(
diff --git a/pyproject.toml b/pyproject.toml
index 2720439a0..1190ed5b2 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -11,7 +11,6 @@ classifiers = [
"Operating System :: OS Independent",
]
dependencies = [
- "aiofiles>=24.1.0",
"aiohttp==3.12.15",
"anyio>=4.9.0",
"bubus>=1.5.6",
diff --git a/tests/ci/evaluate_tasks.py b/tests/ci/evaluate_tasks.py
index 435ba38dd..b4b4736fd 100644
--- a/tests/ci/evaluate_tasks.py
+++ b/tests/ci/evaluate_tasks.py
@@ -13,7 +13,7 @@ import os
import sys
import warnings
-import aiofiles
+import anyio
import yaml
from pydantic import BaseModel
@@ -47,8 +47,7 @@ async def run_single_task(task_file):
warnings.filterwarnings('ignore')
print('[DEBUG] Loading task file...', file=sys.stderr)
- async with aiofiles.open(task_file, 'r') as f:
- content = await f.read()
+ content = await anyio.Path(task_file).read_text()
task_data = yaml.safe_load(content)
task = task_data['task']
judge_context = task_data.get('judge_context', ['The agent must solve the task'])