nlu-backend / example.py
Salahin's picture
Upload 221 files
d50175f verified
Raw History Blame Contribute Delete
5.99 kB
from langchain_openai import ChatOpenAI
import re
import asyncio
from browser_use.agent.service import Agent
from browser_use.browser.browser import Browser, BrowserConfig
from browser_use.browser.context import BrowserContext, BrowserContextConfig
from langchain_core.language_models.chat_models import BaseChatModel
class MultiTaskAgent(Agent):
"""
Single agent that processes multiple subtasks (Task_1, Task_2, etc.)
in one browser session without re-initializing or closing between tasks.
"""
def __init__(
self,
multi_task_string: str,
llm: BaseChatModel,
browser: Browser = None,
browser_context: BrowserContext = None,
**kwargs
):
# 1) Parse out all subtasks from the full string
self.subtasks = self._parse_subtasks(multi_task_string)
if not self.subtasks:
# If no Task_x found, treat the entire string as one subtask
self.subtasks = [multi_task_string]
# 2) If no user-provided browser, create one (headless or not)
if not browser:
browser = Browser(
config=BrowserConfig(
headless=False,
)
)
if not browser_context:
browser_context = BrowserContext(
browser=browser,
config=BrowserContextConfig(
browser_window_size={"width": 1280, "height": 720},
disable_security=True,
)
)
# 3) Call base Agent __init__ with the *first* subtask
super().__init__(
task=self.subtasks[0],
llm=llm,
browser=browser, # ensures base class won't auto-close
browser_context=browser_context, # same reason
**kwargs
)
def _parse_subtasks(self, text: str) -> list[str]:
"""
Quick regex to extract each 'Task_#' block.
"""
pattern = r"(Task_\d+)(.*?)(?=Task_\d+|$)"
found = re.findall(pattern, text, flags=re.DOTALL)
return [subcontent.strip() for _, subcontent in found if subcontent.strip()]
async def run_all_subtasks(self, max_steps: int = 10) -> list[str]:
"""
Runs each subtask in the same Agent instance, returning a final list of
each subtask's "done" output (if any).
"""
results = []
# Already loaded the first subtask in __init__
for i, subtask in enumerate(self.subtasks):
if i > 0:
# For subtask #2, #3, etc., just add to the conversation
self.add_new_task(subtask)
done_output = await self._run_until_done(max_steps)
results.append(done_output)
# Unmark done so we can proceed to the next subtask
self._unmark_agent_done()
return results
async def _run_until_done(self, max_steps: int) -> str:
"""
Similar to the loop inside Agent.run(),
but we don't let the base class close the browser or finalize.
Returns the final 'done' text if any.
"""
done_text = ""
# (Optional) Reset consecutive_failures for each subtask
self.state.consecutive_failures = 0
for _ in range(max_steps):
# If user code stops or the agent is paused, break early
if self.state.stopped:
break
while self.state.paused:
await asyncio.sleep(0.2)
if self.state.stopped:
break
# Call the built-in single step
await self.step()
if self.state.history.is_done():
# The base Agent sets is_done when it calls "done" action
# The final result is usually in the last action's extracted_content
if self.state.history.history:
last_item = self.state.history.history[-1]
if last_item.result and last_item.result[-1].extracted_content:
done_text = last_item.result[-1].extracted_content
break
return done_text
def _unmark_agent_done(self):
"""
Clear the agent's 'done' state so we can continue another subtask
in the same conversation.
"""
if self.state.history.is_done():
self.state.history.history[-1].result[-1].is_done = False
async def close_browser(self):
"""
Manually close everything once you're truly done.
"""
if not self.injected_browser_context and self.browser_context:
await self.browser_context.close()
if not self.injected_browser and self.browser:
await self.browser.close()
# --------------------------------------------
# Example usage
# --------------------------------------------
async def main():
multi_tasks = """
Task_1
Please go to amazon.com and tell me the page title."
Task_2
tell me the price of samsung s24 mobile
Task_3
tell me the price of mac m1 laptop
"""
# A shared browser so it never closes until we decide
shared_browser = Browser(config=BrowserConfig(headless=False))
agent = MultiTaskAgent(
multi_task_string=multi_tasks,
llm=ChatOpenAI(model='gpt-4o'),
browser=shared_browser, # ensures it won't close each subtask
)
# 2) Run all subtasks in one pass
subtask_outputs = await agent.run_all_subtasks(max_steps=8)
# 3) Print final outputs
for i, text in enumerate(subtask_outputs, start=1):
print(f"\n=== Subtask_{i} DONE ===\n{text}\n")
# 4) Manually close browser after everything
await agent.close_browser()
if __name__ == '__main__':
asyncio.run(main())