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
Change order of action output
magmueller1fe98bc50a09
diff --git a/examples/flight_search_example.ipynb b/examples/flight_search_example.ipynbnew file mode 100644index 000000000..887b228b1--- /dev/null+++ b/examples/flight_search_example.ipynb@@ -0,0 +1,85 @@+{+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "# Flight Search Example using AI Agent\n",+ "\n",+ "This notebook demonstrates how to use the AI agent to search for flights on Kayak.com"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "import datetime\n",+ "import os\n",+ "from langchain_openai import ChatOpenAI\n",+ "from src.agent.service import AgentService\n",+ "from src.agent.service import AgentService\n",+ "from src.controller.service import ControllerService\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Setup helper function for organizing outputs\n",+ "def setup_run_folder(timestamp_prefix: str) -> str:\n",+ "\ttimestamp = f'{timestamp_prefix}_{datetime.datetime.now().strftime(\"%Y-%m-%d\")}'\n",+ "\trun_folder = f'temp/{timestamp}'\n",+ "\tif not os.path.exists(run_folder):\n",+ "\t\tos.makedirs(run_folder)\n",+ "\treturn run_folder"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "task = 'Go to kayak.com and find a flight from Zürich to Tokyo on 2024-12-25 for 2 people one way.'\n",+ "run_folder = setup_run_folder('kayak_flight_search')\n",+ "controller = ControllerService()\n",+ "model = ChatOpenAI(model='gpt-4o')\n",+ "agent = AgentService(task, model, controller, use_vision=True)\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Run the agent step by step\n",+ "\n",+ "max_steps = 50\n",+ "for i in range(max_steps):\n",+ "\tprint(f'\\n📍 Step {i+1}')\n",+ "\taction, result = await agent.step()\n",+ "\n",+ "\tprint('Action:', action)\n",+ "\tprint('Result:', result)\n",+ "\n",+ "\tif result.done:\n",+ "\t\tprint('\\n✅ Task completed successfully!')\n",+ "\t\tbreak\n"+ ]+ }+ ],+ "metadata": {+ "kernelspec": {+ "display_name": "Python 3",+ "language": "python",+ "name": "python3"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 2+}diff --git a/src/agent/service.py b/src/agent/service.pyindex 9d5ad4ddf..e67fad07b 100644--- a/src/agent/service.py+++ b/src/agent/service.py@@ -2,10 +2,10 @@ from dotenv import load_dotenvfrom langchain_core.language_models.chat_models import BaseChatModelfrom langchain_core.messages import AIMessage, BaseMessage, HumanMessage-from src.controller.service import ControllerService-from src.controller.views import ControllerActionResult, ControllerPageStatefrom src.agent.prompts import AgentMessagePrompt, AgentSystemPromptfrom src.agent.views import AgentAction+from src.controller.service import ControllerService+from src.controller.views import ControllerActionResult, ControllerPageStateload_dotenv()@@ -31,7 +31,11 @@ class AgentService:self.use_vision = use_visionself.llm = llm- system_prompt = AgentSystemPrompt(task, self._get_action_description()).get_system_message()+ system_prompt = AgentSystemPrompt(+ task, default_action_description=self._get_action_description()+ ).get_system_message()++ print(system_prompt)first_message = HumanMessage(content=f'Your task is: {task}')# self.messages_all: list[BaseMessage] = []@@ -67,10 +71,10 @@ class AgentService:new_message = AgentMessagePrompt(state).get_user_message()input_messages = self.messages + [new_message]- if self.use_vision:- print(f'model input content with image: {new_message.content[0]}')- else:- print(f'model input: {new_message}')+ # if self.use_vision:+ # print(f'model input content with image: {new_message.content[0]}')+ # else:+ # print(f'model input: {new_message}')structured_llm = self.llm.with_structured_output(AgentAction)diff --git a/src/agent/views.py b/src/agent/views.pyindex 3098b0a77..baf76a652 100644--- a/src/agent/views.py+++ b/src/agent/views.py@@ -1,6 +1,8 @@from typing import Optional+from litellm import ConfigDictfrom pydantic import BaseModel+from typing_extensions import Unpackfrom src.controller.views import ControllerActions@@ -9,7 +11,7 @@ class AskHumanAgentAction(BaseModel):question: str-class AgentAction(ControllerActions):+class AgentOnlyAction(BaseModel):valuation_previous_goal: strgoal: str@@ -17,7 +19,17 @@ class AgentAction(ControllerActions):@staticmethoddef description() -> str:- return (- ControllerActions.description()- + '\n\nAsk human for help\nExample: {"ask_human": {"question": "To clarify ..."}}'- )+ return """+- Ask human for help+ Example: {"ask_human": {"question": "To clarify ..."}}+"""+++class AgentAction(ControllerActions, AgentOnlyAction):+ @staticmethod+ def description() -> str:+ return AgentOnlyAction.description() + ControllerActions.description()+++if __name__ == '__main__':+ print(AgentAction(valuation_previous_goal='Failed', goal='Click'))diff --git a/src/controller/views.py b/src/controller/views.pyindex a0d49e5ed..607a43b3b 100644--- a/src/controller/views.py+++ b/src/controller/views.py@@ -44,26 +44,19 @@ class ControllerActions(BaseModel):return """- Search Google with a queryExample: {"search_google": {"query": "weather today"}}-- Navigate directly to a URLExample: {"go_to_url": {"url": "https://abc.com"}}-- Do nothing/waitExample: {"nothing": true}-- Go back to previous pageExample: {"go_back": true}--- Mark task as complete+- Mark entire task as completeExample: {"done": true}-- Click an element by its IDExample: {"click_element": {"id": 1}}-- Input text into an element by its IDExample: {"input_text": {"id": 1, "text": "Hello world"}}--- Extract and return the page content in markdown+- Get the page content in markdownExample: {"extract_page_content": true}"""diff --git a/src/tests/test_mind2web.py b/src/tests/test_mind2web.pyindex 7a492e063..535452281 100644--- a/src/tests/test_mind2web.py+++ b/src/tests/test_mind2web.py@@ -7,7 +7,9 @@ import pytestfrom langchain_openai import ChatOpenAIfrom src.agent.service import AgentService-from src.planning.service import PlaningService+from src.controller.service import ControllerService++#def setup_run_folder(timestamp_prefix: str) -> str:@@ -56,9 +58,9 @@ async def test_mind2web_samples():print('-' * 50)# Initialize new agent and model for each sample- agent = AgentService()+ controller = ControllerService()model = ChatOpenAI(model='gpt-4o')- planning_service = PlaningService(task=task, llm=model, agent=agent, use_vision=True)+ agent = AgentService(task, model, controller, use_vision=True)try:max_steps = 50@@ -66,7 +68,7 @@ async def test_mind2web_samples():for step in range(max_steps):print(f'\n📍 Step {step+1}')- action, result = await planning_service.step()+ action, result = await agent.step()print('Action:', action)print('Result:', result)@@ -93,14 +95,14 @@ async def test_mind2web_samples():except KeyboardInterrupt:print('\nReceived interrupt, closing browser...')- agent.browser.close()+ controller.browser.close()raiseexcept Exception as e:print(f'\n❌ Error processing sample: {str(e)}')results['failed'] += 1results['errors'].append({'sample': i, 'task': sample['task'], 'error': str(e)})finally:- agent.browser.close()+ controller.browser.close()# Save final resultsresults_file = f'{run_folder}/results.json'@@ -145,15 +147,15 @@ async def test_single_mind2web_sample():print(f'Task: {task}')print('=' * 50)- agent = AgentService()+ controller = ControllerService()model = ChatOpenAI(model='gpt-4o')- planning_service = PlaningService(task=task, llm=model, agent=agent, use_vision=True)+ agent = AgentService(task, model, controller, use_vision=True)try:max_steps = 50for step in range(max_steps):print(f'\n📍 Step {step+1}')- action, result = await planning_service.step()+ action, result = await agent.step()print('Action:', action)print('Result:', result)@@ -172,10 +174,10 @@ async def test_single_mind2web_sample():except KeyboardInterrupt:print('\nReceived interrupt, closing browser...')- agent.browser.close()+ controller.browser.close()raisefinally:- agent.browser.close()+ controller.browser.close()if __name__ == '__main__':