huytofu92 commited on
Commit
beb3f4b
·
1 Parent(s): a1dd06e
Files changed (2) hide show
  1. browser.py +35 -44
  2. mini_agents.py +3 -5
browser.py CHANGED
@@ -28,41 +28,38 @@ class BrowserManager:
28
  subprocess.run(["bash", "scripts.sh"])
29
  self.initialized = True
30
 
31
- async def _create_async_tools(self):
32
- """Create async browser tools in the correct event loop"""
33
- # Create browsers in the current context
34
- async_browser = await create_async_playwright_browser()
 
35
 
36
- # Create toolkit and tools
37
- browser_toolkit = PlayWrightBrowserToolkit.from_browser(
38
- async_browser=async_browser,
39
- sync_browser=None # Don't use sync browser
40
- )
41
- tools = [
42
- Tool.from_langchain(tool)
43
- for tool in browser_toolkit.get_tools()
44
- ]
45
-
46
- # Store browser reference for cleanup
47
- for tool in tools:
48
- tool._browser = async_browser
49
-
50
- return tools
51
-
52
- def _ensure_event_loop(self):
53
- """Ensure we have a valid event loop in this thread"""
54
  try:
55
- loop = asyncio.get_event_loop()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  if loop.is_running():
57
- # If loop is running, we're in an async context
58
- # Create a new loop for our browser tools
59
- loop = asyncio.new_event_loop()
60
- asyncio.set_event_loop(loop)
61
- except RuntimeError:
62
- # No event loop exists, create one
63
- loop = asyncio.new_event_loop()
64
- asyncio.set_event_loop(loop)
65
- return loop
66
 
67
  @contextmanager
68
  def get_browser_tools(self):
@@ -71,12 +68,7 @@ class BrowserManager:
71
  if self._browser_tools is None:
72
  with self._lock:
73
  if self._browser_tools is None:
74
- # Get or create event loop
75
- loop = self._ensure_event_loop()
76
- self._loop = loop
77
-
78
- # Create tools in the event loop
79
- self._browser_tools = loop.run_until_complete(self._create_async_tools())
80
 
81
  yield self._browser_tools
82
 
@@ -84,21 +76,20 @@ class BrowserManager:
84
  print(f"Error in browser context: {e}")
85
  # Reset tools on error
86
  self._browser_tools = None
87
- self._loop = None
88
  raise
89
  finally:
90
  # Cleanup if needed
91
  if self._browser_tools:
92
  for tool in self._browser_tools:
93
- if hasattr(tool, '_browser'):
94
  try:
95
- # Use the stored loop for cleanup
96
- if self._loop and not self._loop.is_closed():
97
- self._loop.run_until_complete(tool._browser.close())
 
98
  except Exception as e:
99
  print(f"Error during browser cleanup: {e}")
100
  self._browser_tools = None
101
- self._loop = None
102
 
103
  # Create a singleton instance
104
  browser_manager = BrowserManager()
 
28
  subprocess.run(["bash", "scripts.sh"])
29
  self.initialized = True
30
 
31
+ def _create_browser_tools(self):
32
+ """Create browser tools in a new event loop"""
33
+ # Create a new event loop for browser tools
34
+ loop = asyncio.new_event_loop()
35
+ asyncio.set_event_loop(loop)
36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  try:
38
+ # Create browsers in the new loop
39
+ async_browser = loop.run_until_complete(create_async_playwright_browser())
40
+
41
+ # Create toolkit and tools
42
+ browser_toolkit = PlayWrightBrowserToolkit.from_browser(
43
+ async_browser=async_browser,
44
+ sync_browser=None # Don't use sync browser
45
+ )
46
+ tools = [
47
+ Tool.from_langchain(tool)
48
+ for tool in browser_toolkit.get_tools()
49
+ ]
50
+
51
+ # Store browser reference for cleanup
52
+ for tool in tools:
53
+ tool._browser = async_browser
54
+ tool._loop = loop
55
+
56
+ return tools
57
+ except Exception as e:
58
+ print(f"Error creating browser tools: {e}")
59
  if loop.is_running():
60
+ loop.stop()
61
+ loop.close()
62
+ raise
 
 
 
 
 
 
63
 
64
  @contextmanager
65
  def get_browser_tools(self):
 
68
  if self._browser_tools is None:
69
  with self._lock:
70
  if self._browser_tools is None:
71
+ self._browser_tools = self._create_browser_tools()
 
 
 
 
 
72
 
73
  yield self._browser_tools
74
 
 
76
  print(f"Error in browser context: {e}")
77
  # Reset tools on error
78
  self._browser_tools = None
 
79
  raise
80
  finally:
81
  # Cleanup if needed
82
  if self._browser_tools:
83
  for tool in self._browser_tools:
84
+ if hasattr(tool, '_browser') and hasattr(tool, '_loop'):
85
  try:
86
+ loop = tool._loop
87
+ if loop and not loop.is_closed():
88
+ loop.run_until_complete(tool._browser.close())
89
+ loop.close()
90
  except Exception as e:
91
  print(f"Error during browser cleanup: {e}")
92
  self._browser_tools = None
 
93
 
94
  # Create a singleton instance
95
  browser_manager = BrowserManager()
mini_agents.py CHANGED
@@ -170,15 +170,14 @@ class MasterAgentWrapper:
170
  )
171
 
172
  def _run_with_browser_tools(self, question: str, browser_tools: List[Tool]) -> str:
173
- """Run agent with browser tools in the current event loop"""
174
  # Temporarily add browser tools
175
  original_tools = self.master_agent.tools
176
  self.master_agent.tools = original_tools + browser_tools
177
 
178
  try:
179
- # Run the agent using sync run, but in a way that doesn't block the event loop
180
- loop = asyncio.get_running_loop()
181
- result = loop.run_in_executor(None, self.master_agent.run, question)
182
  return result
183
  finally:
184
  # Restore original tools
@@ -190,7 +189,6 @@ class MasterAgentWrapper:
190
  # Get browser tools in the correct context
191
  with browser_manager.get_browser_tools() as browser_tools:
192
  # Run with browser tools
193
- # The browser tools will handle their own async operations
194
  return self._run_with_browser_tools(question, browser_tools)
195
 
196
  except Exception as e:
 
170
  )
171
 
172
  def _run_with_browser_tools(self, question: str, browser_tools: List[Tool]) -> str:
173
+ """Run agent with browser tools"""
174
  # Temporarily add browser tools
175
  original_tools = self.master_agent.tools
176
  self.master_agent.tools = original_tools + browser_tools
177
 
178
  try:
179
+ # Run the agent directly since we're in a sync context
180
+ result = self.master_agent.run(question)
 
181
  return result
182
  finally:
183
  # Restore original tools
 
189
  # Get browser tools in the correct context
190
  with browser_manager.get_browser_tools() as browser_tools:
191
  # Run with browser tools
 
192
  return self._run_with_browser_tools(question, browser_tools)
193
 
194
  except Exception as e: