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
added history
Gregor Žuničb32176dbae2a
diff --git a/README.md b/README.mdindex 043919bfd..0c96ae276 100644--- a/README.md+++ b/README.md@@ -127,11 +127,13 @@ agent2 = Agent(# Let it work its magicawait agent1.run()-founders = await agent2.run()+founders, history = await agent2.run()print(founders)```+You can use the `history` to run the agents again deterministically.+## 🤖 Supported ModelsAll LangChain chat models are supported.@@ -157,6 +159,6 @@ Contributions are welcome! Also feel free to open issues for any bugs or feature# Future Roadmap- [ ] Pydantic forced output-- [ ] Save agent actions and execute them deterministically (for QA testing etc)+- [x] Save agent actions and execute them deterministically (for QA testing etc)- [ ] Third party SERP API for faster Google Search results- [ ]diff --git a/examples/simple_run.py b/examples/simple_run.pyindex 1b675983d..54d9f7f57 100644--- a/examples/simple_run.py+++ b/examples/simple_run.py@@ -4,6 +4,7 @@ Simple try of the agent.@dev You need to add OPENAI_API_KEY to your environment variables."""+import loggingimport osimport sys@@ -15,6 +16,8 @@ from langchain_openai import ChatOpenAIfrom src import Agent+logging.basicConfig(level=logging.INFO)+llm = ChatOpenAI(model='gpt-4o')agent = Agent(task='Find cheapest flights on Google Flights from London to Kyrgyzstan and return the url.',@@ -23,7 +26,9 @@ agent = Agent(async def main():- await agent.run()+ result, history = await agent.run()+ print(result)+ print(history)asyncio.run(main())diff --git a/examples/talent_kick_apply.py b/examples/talent_kick_apply.pynew file mode 100644index 000000000..ba5e9f31c--- /dev/null+++ b/examples/talent_kick_apply.py@@ -0,0 +1,32 @@+"""+Simple try of the agent.++@dev You need to add OPENAI_API_KEY to your environment variables.+"""++import logging+import os+import sys++sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++import asyncio++from langchain_openai import ChatOpenAI++from src import Agent++logging.basicConfig(level=logging.INFO)++llm = ChatOpenAI(model='gpt-4o')+agent = Agent(+ task='Apply to 2025 batch of Talent Kick. Use dummy data. Here is some information about me: Name: John Doe, Email: [email protected], Phone: +1234567890, LinkedIn: https://www.linkedin.com/in/john-doe, Github: https://github.com/john-doe, Twitter: https://twitter.com/john-doe, StackOverflow: https://stackoverflow.com/users/123456/john-doe, Youtube: https://www.youtube.com/user/john-doe, Education: BSc Computer Science from MIT (2020-2024), Work Experience: Software Engineer at Google (2024-present), Skills: Python, JavaScript, React, Node.js, AWS, Docker, Kubernetes, Projects: Built an AI-powered chatbot with 10k+ users, Created an open-source library with 1k+ stars on Github, Achievements: Won first place in MIT Hackathon 2023, Published paper on ML at ICML 2024, Languages: English (Native), Spanish (Fluent), Mandarin (Basic), Interests: AI/ML, Open Source, Competitive Programming, Hobbies: Playing guitar, Rock climbing, Chess',+ llm=llm,+)+++async def main():+ await agent.run()+++asyncio.run(main())diff --git a/requirements.txt b/requirements.txtindex 7aa76e2f5..bbffd86b7 100644--- a/requirements.txt+++ b/requirements.txt@@ -11,4 +11,5 @@ pytest-asyncio==0.24.0python-dotenv==1.0.1requests==2.32.3selenium==4.26.1-webdriver-manager==4.0.2\ No newline at end of file+webdriver-manager==4.0.2+setuptools==75.3.0\ No newline at end of filediff --git a/src/agent/prompts.py b/src/agent/prompts.pyindex 642673ee3..737abdc5f 100644--- a/src/agent/prompts.py+++ b/src/agent/prompts.py@@ -47,6 +47,8 @@ class AgentSystemPrompt:Make sure to only use indexes that are present in the list.If you need more text from the page you can use the extract_page_content action.+ If you see any cookie or accept privacy policy please always just accepted them without hesitation.+If you evaluate repeatedly that you dont achieve the next_goal, try to find a new element that can help you achieve your task or if persistent, go back or reload the page and try a different approach.You can ask_human for clarification if you are completely stuck or if you really need more information.diff --git a/src/agent/service.py b/src/agent/service.pyindex 64bd9b115..0b2b93b90 100644--- a/src/agent/service.py+++ b/src/agent/service.py@@ -6,9 +6,15 @@ from langchain_core.language_models.chat_models import BaseChatModelfrom langchain_core.messages import AIMessage, BaseMessage, HumanMessagefrom src.agent.prompts import AgentMessagePrompt, AgentSystemPrompt-from src.agent.views import AgentOutput, Output+from src.agent.views import (+ AgentHistory,+ AgentOutput,+ ClickElementControllerHistoryItem,+ InputTextControllerHistoryItem,+ Output,+)from src.controller.service import ControllerService-from src.controller.views import ControllerActionResult, ControllerPageState+from src.controller.views import ControllerActionResult, ControllerActions, ControllerPageStatefrom src.utils import time_execution_asyncload_dotenv()@@ -56,12 +62,15 @@ class AgentService:if save_conversation_path is not None:logger.info(f'Saving conversation to {save_conversation_path}')+ self.action_history: list[AgentHistory] = []+async def run(self, max_steps: int = 100):"""Execute the task.@dev ctrl+c to interrupt"""+try:logger.info('\n' + '=' * 50)logger.info(f'🚀 Starting task: {self.task}')@@ -75,18 +84,18 @@ class AgentService:if result.done:logger.info('\n✅ Task completed successfully')logger.info(f'Extracted content: {result.extracted_content}')- return action.done+ return action.done, self.action_historylogger.info('\n' + '=' * 50)logger.info('❌ Failed to complete task in maximum steps')logger.info('=' * 50)- return None+ return None, self.action_historyfinally:if not self.controller_injected:self.controller.browser.close()@time_execution_async('--step')- async def step(self) -> tuple[AgentOutput, ControllerActionResult]:+ async def step(self) -> tuple[AgentHistory, ControllerActionResult]:state = self.controller.get_current_state(screenshot=self.use_vision)action = await self.get_next_action(state)@@ -103,7 +112,38 @@ class AgentService:self.messages.append(HumanMessage(content=f'Extracted content: {result.extracted_content}'))- return action, result++ # Convert action to history and update click/input fields if present+ history_item = self._make_history_item(action, state)+ self.action_history.append(history_item)++ return history_item, result++ def _make_history_item(self, action: AgentOutput, state: ControllerPageState) -> AgentHistory:+ return AgentHistory(+ search_google=action.search_google,+ go_to_url=action.go_to_url,+ nothing=action.nothing,+ go_back=action.go_back,+ done=action.done,+ click_element=ClickElementControllerHistoryItem(+ id=action.click_element.id, xpath=state.selector_map.get(action.click_element.id)+ )+ if action.click_element and state.selector_map.get(action.click_element.id)+ else None,+ input_text=InputTextControllerHistoryItem(+ id=action.input_text.id,+ xpath=state.selector_map.get(action.input_text.id),+ text=action.input_text.text,+ )+ if action.input_text and state.selector_map.get(action.input_text.id)+ else None,+ extract_page_content=action.extract_page_content,+ switch_tab=action.switch_tab,+ open_tab=action.open_tab,+ ask_human=action.ask_human,+ url=state.url,+ )async def _take_human_input(self, question: str) -> AgentOutput:human_input = input(f'Human input required: {question}\n\n')diff --git a/src/agent/views.py b/src/agent/views.pyindex 6b360a87a..ace6962fa 100644--- a/src/agent/views.py+++ b/src/agent/views.py@@ -2,7 +2,11 @@ from typing import Optionalfrom pydantic import BaseModel-from src.controller.views import ControllerActions+from src.controller.views import (+ ClickElementControllerAction,+ ControllerActions,+ InputTextControllerAction,+)class AskHumanAgentAction(BaseModel):@@ -37,12 +41,15 @@ class Output(BaseModel):action: AgentOutput-if __name__ == '__main__':- print(- Output(- current_state=AgentState(- valuation_previous_goal='Failed', next_goal='Click', memory=''- ),- action=AgentOutput(),- )- )+class ClickElementControllerHistoryItem(ClickElementControllerAction):+ xpath: str | None+++class InputTextControllerHistoryItem(InputTextControllerAction):+ xpath: str | None+++class AgentHistory(AgentOutput):+ click_element: Optional[ClickElementControllerHistoryItem] = None+ input_text: Optional[InputTextControllerHistoryItem] = None+ url: str