Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
Refactor advanced_search.py to use SERP API for web search and improve error handling for API keys. Added logging for debugging and updated agent initialization with BrowserProfile.
Magnus Müller18c13bda2643
diff --git a/examples/custom-functions/advanced_search.py b/examples/custom-functions/advanced_search.pyindex a62289484..df4dd3c2a 100644--- a/examples/custom-functions/advanced_search.py+++ b/examples/custom-functions/advanced_search.py@@ -1,4 +1,5 @@import asyncio+import httpimport jsonimport osimport sys@@ -9,11 +10,15 @@ from dotenv import load_dotenvload_dotenv()-import httpx+import logging+from langchain_openai import ChatOpenAIfrom pydantic import BaseModelfrom browser_use import ActionResult, Agent, Controller+from browser_use.browser.profile import BrowserProfile++logger = logging.getLogger(__name__)class Person(BaseModel):@@ -25,31 +30,34 @@ class PersonList(BaseModel):people: list[Person]-controller = Controller(exclude_actions=['search_google'], output_model=PersonList)-BEARER_TOKEN = os.getenv('BEARER_TOKEN')+SERP_API_KEY = os.getenv('SERPER_API_KEY')+if not SERP_API_KEY:+ raise ValueError('SERPER_API_KEY is not set')-if not BEARER_TOKEN:- # use the api key for ask tessa- # you can also use other apis like exa, xAI, perplexity, etc.- raise ValueError('BEARER_TOKEN is not set - go to https://www.heytessa.ai/ and create an api key')+controller = Controller(exclude_actions=['search_google'], output_model=PersonList)@controller.registry.action('Search the web for a specific query')async def search_web(query: str):- keys_to_use = ['url', 'title', 'content', 'author', 'score']- headers = {'Authorization': f'Bearer {BEARER_TOKEN}'}- async with httpx.AsyncClient() as client:- response = await client.post('https://asktessa.ai/api/search', headers=headers, json={'query': query})-- final_results = [- {key: source[key] for key in keys_to_use if key in source}- for source in response.json()['sources']- if source['score'] >= 0.8- ]- # print(json.dumps(final_results, indent=4))- result_text = json.dumps(final_results, indent=4)- print(result_text)- return ActionResult(extracted_content=result_text, include_in_memory=True)+ # do a serp search for the query+ conn = http.client.HTTPSConnection('google.serper.dev')+ payload = json.dumps({'q': query})+ headers = {'X-API-KEY': SERP_API_KEY, 'Content-Type': 'application/json'}+ conn.request('POST', '/search', payload, headers)+ res = conn.getresponse()+ data = res.read()+ serp_data = json.loads(data.decode('utf-8'))++ # exclude searchParameters and credits+ serp_data = {k: v for k, v in serp_data.items() if k not in ['searchParameters', 'credits']}++ # print the original data+ logger.debug(json.dumps(serp_data, indent=2))++ # to string+ serp_data_str = json.dumps(serp_data)++ return ActionResult(extracted_content=serp_data_str, include_in_memory=True)names = [@@ -80,7 +88,8 @@ async def main():task = 'use search_web with "find email address of the following ETH professor:" for each of the following persons in a list of actions. Finally return the list with name and email if provided'task += '\n' + '\n'.join(names)model = ChatOpenAI(model='gpt-4o')- agent = Agent(task=task, llm=model, controller=controller, max_actions_per_step=20)+ browser_profile = BrowserProfile()+ agent = Agent(task=task, llm=model, controller=controller, browser_profile=browser_profile)history = await agent.run()