File size: 5,990 Bytes
d50175f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
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())