Skip to content

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

Save conversation to folder

magmuellerd0f088eb2029
diff --git a/src/agent/prompts.py b/src/agent/prompts.py
index 43cfbc9ae..a6a7bc139 100644
--- a/src/agent/prompts.py
+++ b/src/agent/prompts.py
@@ -33,19 +33,19 @@ class AgentSystemPrompt:
Additional you get a list of your previous actions.
- Available actions (choose EXACTLY ONE, not 0 or 2):
+
+ Respond with a valid JSON object, containing the current_state and action.
+ In current_state you need to provide:
+ valuation_previous_goal: valuation of the previous goal if it is achieved or what went wrong.
+ memory: This you can use as a memory to store where you are in your overall task. E.g. if you need to find 10 jobs, you can store the already found jobs here.
+ next_goal: Short description of the next goal you need to achieve.
+ In action choose EXACTLY ONE from the following list:
{self.default_action_description}
To interact with elements, use their index number in the click_element() or input_text() actions.
If you need more text from the page you can use the extract_page_content action.
- Respond with a valid JSON object, containing the valuation_previous_goal, memory, next_goal and your next action to achieve the next goal.
-
- valuation_previous_goal: valuation of the previous goal if it is achieved or what went wrong.
- memory: This you can use as a memory to store where you are in your overall task. E.g. if you need to find 10 jobs, you can store the already found jobs here.
- next_goal: Short description of the next goal you need to achieve.
-
If you get stuck and multiple time 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.py
index ef707ed0b..2e69b6143 100644
--- a/src/agent/service.py
+++ b/src/agent/service.py
@@ -5,7 +5,7 @@ from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.messages import AIMessage, BaseMessage, HumanMessage
from src.agent.prompts import AgentMessagePrompt, AgentSystemPrompt
-from src.agent.views import AgentAction
+from src.agent.views import AgentOutput, Output
from src.controller.service import ControllerService
from src.controller.views import ControllerActionResult, ControllerPageState
from src.utils import time_execution_async
@@ -45,8 +45,11 @@ class AgentService:
# self.messages_all: list[BaseMessage] = []
self.messages: list[BaseMessage] = [system_prompt, first_message]
self.save_file = save_file
+ if save_file is not None:
+ print(f'Saving conversation to {save_file}')
+ self.n = 0
- async def step(self) -> tuple[AgentAction, ControllerActionResult]:
+ async def step(self) -> tuple[AgentOutput, ControllerActionResult]:
state = self.controller.get_current_state(screenshot=self.use_vision)
action = await self.get_next_action(state)
@@ -54,23 +57,24 @@ class AgentService:
action = await self._take_human_input(action.ask_human.question)
result = self.controller.act(action)
+ self.n += 1
return action, result
- async def _take_human_input(self, question: str) -> AgentAction:
+ async def _take_human_input(self, question: str) -> AgentOutput:
human_input = input(f'Human input required: {question}')
self.messages.append(HumanMessage(content=human_input))
- structured_llm = self.llm.with_structured_output(AgentAction)
- action: AgentAction = await structured_llm.ainvoke(self.messages) # type: ignore
+ structured_llm = self.llm.with_structured_output(AgentOutput)
+ action: AgentOutput = await structured_llm.ainvoke(self.messages) # type: ignore
self.messages.append(AIMessage(content=action.model_dump_json()))
return action
@time_execution_async('get_next_action')
- async def get_next_action(self, state: ControllerPageState) -> AgentAction:
+ async def get_next_action(self, state: ControllerPageState) -> AgentOutput:
# TODO: include state, actions, etc.
new_message = AgentMessagePrompt(state).get_user_message()
@@ -81,11 +85,11 @@ class AgentService:
# else:
# print(f'model input: {new_message}')
- structured_llm = self.llm.with_structured_output(AgentAction, include_raw=False)
+ structured_llm = self.llm.with_structured_output(Output, include_raw=False)
# print(f'state:\n{state}')
#
- response: AgentAction = await structured_llm.ainvoke(input_messages) # type: ignore
+ response: Output = await structured_llm.ainvoke(input_messages) # type: ignore
# raw_response, response = invoke_response
# if store_conversation:
# # save conversation
@@ -133,12 +137,35 @@ class AgentService:
# if len(self.messages) > 20:
# self.messages = self.messages[-20:]
- return response
+ return response.action
def _get_action_description(self) -> str:
- return AgentAction.description()
-
- def _save_conversation(self, input_messages: list[BaseMessage], response: AgentAction):
- if self.save_file:
- with open(self.save_file, 'w') as f:
- json.dump({'input_messages': input_messages, 'response': response}, f, indent=4)
+ return AgentOutput.description()
+
+ def _save_conversation(self, input_messages: list[BaseMessage], response: Output):
+ if self.save_file is not None:
+ with open(self.save_file + f'_{self.n}.txt', 'w') as f:
+ # Write messages with proper formatting
+ for message in input_messages:
+ f.write('=' * 33 + f' {message.__class__.__name__} ' + '=' * 33 + '\n\n')
+
+ # Handle different content types
+ if isinstance(message.content, list):
+ # Handle vision model messages
+ for item in message.content:
+ if item['type'] == 'text':
+ f.write(item['text'].strip() + '\n')
+ elif isinstance(message.content, str):
+ try:
+ # Try to parse and format JSON content
+ content = json.loads(message.content)
+ f.write(json.dumps(content, indent=2) + '\n')
+ except json.JSONDecodeError:
+ # If not JSON, write as regular text
+ f.write(message.content.strip() + '\n')
+
+ f.write('\n')
+
+ # Write final response as formatted JSON
+ f.write('=' * 33 + ' Response ' + '=' * 33 + '\n\n')
+ f.write(json.dumps(json.loads(response.model_dump_json()), indent=2))
diff --git a/src/agent/views.py b/src/agent/views.py
index 08e65376f..c9120ee32 100644
--- a/src/agent/views.py
+++ b/src/agent/views.py
@@ -9,12 +9,13 @@ class AskHumanAgentAction(BaseModel):
question: str
-class AgentOnlyAction(BaseModel):
- # TODO this is not really and action with function, but more an output only
+class AgentState(BaseModel):
valuation_previous_goal: str
memory: str
next_goal: str
+
+class AgentOnlyAction(BaseModel):
ask_human: Optional[AskHumanAgentAction] = None
@staticmethod
@@ -25,11 +26,24 @@ class AgentOnlyAction(BaseModel):
"""
-class AgentAction(ControllerActions, AgentOnlyAction):
+class AgentOutput(ControllerActions, AgentOnlyAction):
@staticmethod
def description() -> str:
return AgentOnlyAction.description() + ControllerActions.description()
+ #
+
+
+class Output(BaseModel):
+ current_state: AgentState
+ action: AgentOutput
if __name__ == '__main__':
- print(AgentAction(valuation_previous_goal='Failed', next_goal='Click', memory=''))
+ print(
+ Output(
+ current_state=AgentState(
+ valuation_previous_goal='Failed', next_goal='Click', memory=''
+ ),
+ action=AgentOutput(),
+ )
+ )
diff --git a/src/tests/test_kayak_search.py b/src/tests/test_kayak_search.py
index 1e4ef68ec..f1374044e 100644
--- a/src/tests/test_kayak_search.py
+++ b/src/tests/test_kayak_search.py
@@ -19,7 +19,7 @@ langfuse = Langfuse(
def setup_run_folder(timestamp_prefix: str) -> str:
- timestamp = f'{timestamp_prefix}_{datetime.datetime.now().strftime("%Y-%m-%d")}'
+ timestamp = f'{timestamp_prefix}_{datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")}'
run_folder = f'temp/{timestamp}'
if not os.path.exists(run_folder):
os.makedirs(run_folder)
@@ -47,7 +47,13 @@ async def test_kayak_flight_search():
)
model = ChatOpenAI(model='gpt-4o', temperature=0.0)
- agent = AgentService(task, model, controller, use_vision=False)
+ agent = AgentService(
+ task,
+ model,
+ controller,
+ use_vision=True,
+ save_file=f'{run_folder}/conversation',
+ )
print('\n' + '=' * 50)
print('🚀 Starting flight search task')
diff --git a/src/tests/test_mind2web.py b/src/tests/test_mind2web.py
index f49d862bc..ef47c04fe 100644
--- a/src/tests/test_mind2web.py
+++ b/src/tests/test_mind2web.py
@@ -13,7 +13,7 @@ from src.controller.service import ControllerService
def setup_run_folder(timestamp_prefix: str) -> str:
- timestamp = f'{timestamp_prefix}_{datetime.datetime.now().strftime("%Y-%m-%d")}'
+ timestamp = f'{timestamp_prefix}_{datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")}'
run_folder = f'temp/{timestamp}'
if not os.path.exists(run_folder):
os.makedirs(run_folder)