Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -24,36 +24,41 @@ except ImportError as e:
|
|
| 24 |
logger.error(f"Import error: {e}")
|
| 25 |
raise
|
| 26 |
|
| 27 |
-
# π€ Helper pour appeler un coroutine dans un contexte synchrone
|
| 28 |
-
def sync_run(coro):
|
| 29 |
-
try:
|
| 30 |
-
loop = asyncio.get_running_loop()
|
| 31 |
-
return loop.run_until_complete(coro)
|
| 32 |
-
except RuntimeError:
|
| 33 |
-
return asyncio.run(coro)
|
| 34 |
-
|
| 35 |
-
# ConversationManager reste identique
|
| 36 |
class ConversationManager:
|
|
|
|
|
|
|
| 37 |
def __init__(self, max_history_pairs: int = 3, max_context_chars: int = 2000):
|
| 38 |
self.max_history_pairs = max_history_pairs
|
| 39 |
self.max_context_chars = max_context_chars
|
| 40 |
-
self.session_context = {}
|
|
|
|
| 41 |
def update_session_context(self, action: str, result: str):
|
|
|
|
| 42 |
self.session_context.update({
|
| 43 |
'last_action': action,
|
| 44 |
-
'last_result': result[:500],
|
| 45 |
'timestamp': datetime.now().isoformat()
|
| 46 |
})
|
|
|
|
| 47 |
def get_optimized_history(self, full_history: List[Tuple[str, str]]) -> List[Tuple[str, str]]:
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
if self.session_context:
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
|
|
|
|
|
|
| 53 |
def get_context_summary(self) -> str:
|
|
|
|
| 54 |
if not self.session_context:
|
| 55 |
return "Browser session not active."
|
| 56 |
-
|
|
|
|
| 57 |
|
| 58 |
class BrowserAgent:
|
| 59 |
def __init__(self, api_key: str):
|
|
@@ -66,165 +71,573 @@ class BrowserAgent:
|
|
| 66 |
self.initialized = False
|
| 67 |
self.available_tools = {}
|
| 68 |
self.system_prompt = ""
|
| 69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
async def generate_tools_prompt(self):
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
async def get_system_prompt_with_tools(self):
|
| 77 |
base = """π Browser Agent β Persistent Session & Optimized Memory
|
| 78 |
-
You are an intelligent browser automation agent (Playwright via MCP)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
"""
|
| 80 |
tools_section = await self.generate_tools_prompt()
|
| 81 |
return base + tools_section
|
| 82 |
|
| 83 |
-
async def
|
| 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 |
-
MessagesPlaceholder(variable_name="chat_history"),
|
| 110 |
-
("human", "{input}"),
|
| 111 |
-
MessagesPlaceholder(variable_name="agent_scratchpad"),
|
| 112 |
-
])
|
| 113 |
-
agent = create_tool_calling_agent(
|
| 114 |
-
llm=self.model, tools=tools, prompt=prompt
|
| 115 |
-
)
|
| 116 |
-
self.agent_executor = AgentExecutor(
|
| 117 |
-
agent=agent, tools=tools, verbose=True,
|
| 118 |
-
max_iterations=15, early_stopping_method="generate",
|
| 119 |
-
handle_parsing_errors=True, return_intermediate_steps=True,
|
| 120 |
-
max_execution_time=180
|
| 121 |
-
)
|
| 122 |
-
self.initialized = True
|
| 123 |
-
return True
|
| 124 |
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
await self.session_context.
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
|
|
|
|
|
|
| 133 |
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
resp = await self.agent_executor.ainvoke({
|
| 143 |
-
"input": enhanced,
|
| 144 |
-
"chat_history": msgs
|
| 145 |
-
})
|
| 146 |
-
out = resp["output"]
|
| 147 |
-
self.conversation_manager.update_session_context(query, out)
|
| 148 |
-
return out
|
| 149 |
|
| 150 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
agent: Optional[BrowserAgent] = None
|
|
|
|
| 152 |
|
| 153 |
-
def
|
|
|
|
| 154 |
global agent
|
|
|
|
| 155 |
if not api_key.strip():
|
| 156 |
-
return "β
|
|
|
|
| 157 |
try:
|
| 158 |
-
|
| 159 |
-
|
|
|
|
|
|
|
|
|
|
| 160 |
agent = BrowserAgent(api_key)
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
|
|
|
|
|
|
| 164 |
except Exception as e:
|
| 165 |
-
|
|
|
|
| 166 |
|
| 167 |
-
def
|
|
|
|
| 168 |
global agent
|
|
|
|
| 169 |
if not agent or not agent.initialized:
|
| 170 |
-
|
| 171 |
-
history.append([message,
|
| 172 |
return "", history
|
|
|
|
| 173 |
if not message.strip():
|
| 174 |
-
|
| 175 |
-
history.append([message,
|
| 176 |
return "", history
|
| 177 |
-
|
| 178 |
-
stats_before = agent.conversation_manager.get_optimized_history(agent_hist)
|
| 179 |
try:
|
| 180 |
-
|
| 181 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
return "", history
|
|
|
|
| 183 |
except Exception as e:
|
| 184 |
-
|
| 185 |
-
|
|
|
|
| 186 |
return "", history
|
| 187 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
def get_token_stats_sync(history: List[List[str]]) -> str:
|
|
|
|
| 189 |
global agent
|
| 190 |
if not agent or not agent.initialized:
|
| 191 |
-
return "Agent
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
|
| 197 |
def create_interface():
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 215 |
return interface
|
| 216 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
def signal_handler(signum, frame):
|
| 218 |
-
|
| 219 |
-
|
|
|
|
|
|
|
|
|
|
| 220 |
sys.exit(0)
|
| 221 |
|
| 222 |
-
|
|
|
|
|
|
|
| 223 |
|
| 224 |
-
|
| 225 |
signal.signal(signal.SIGINT, signal_handler)
|
| 226 |
signal.signal(signal.SIGTERM, signal_handler)
|
| 227 |
|
| 228 |
-
|
| 229 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 230 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
logger.error(f"Import error: {e}")
|
| 25 |
raise
|
| 26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
class ConversationManager:
|
| 28 |
+
"""Manages conversation history with token optimization"""
|
| 29 |
+
|
| 30 |
def __init__(self, max_history_pairs: int = 3, max_context_chars: int = 2000):
|
| 31 |
self.max_history_pairs = max_history_pairs
|
| 32 |
self.max_context_chars = max_context_chars
|
| 33 |
+
self.session_context = {} # Browser state context
|
| 34 |
+
|
| 35 |
def update_session_context(self, action: str, result: str):
|
| 36 |
+
"""Update browser session context (current page, last actions, etc.)"""
|
| 37 |
self.session_context.update({
|
| 38 |
'last_action': action,
|
| 39 |
+
'last_result': result[:500], # Truncate long results
|
| 40 |
'timestamp': datetime.now().isoformat()
|
| 41 |
})
|
| 42 |
+
|
| 43 |
def get_optimized_history(self, full_history: List[Tuple[str, str]]) -> List[Tuple[str, str]]:
|
| 44 |
+
"""Get optimized history with recent messages + session context"""
|
| 45 |
+
|
| 46 |
+
# Take only the last N conversation pairs
|
| 47 |
+
recent_history = full_history[-self.max_history_pairs:] if full_history else []
|
| 48 |
+
|
| 49 |
+
# Add session context as first "message" if we have browser state
|
| 50 |
if self.session_context:
|
| 51 |
+
context_msg = f"[SESSION_CONTEXT] Browser session active. Last action: {self.session_context.get('last_action', 'none')}"
|
| 52 |
+
recent_history.insert(0, ("system", context_msg))
|
| 53 |
+
|
| 54 |
+
return recent_history
|
| 55 |
+
|
| 56 |
def get_context_summary(self) -> str:
|
| 57 |
+
"""Get a summary of current browser session state"""
|
| 58 |
if not self.session_context:
|
| 59 |
return "Browser session not active."
|
| 60 |
+
|
| 61 |
+
return f"Browser session active. Last action: {self.session_context.get('last_action', 'none')} at {self.session_context.get('timestamp', 'unknown')}"
|
| 62 |
|
| 63 |
class BrowserAgent:
|
| 64 |
def __init__(self, api_key: str):
|
|
|
|
| 71 |
self.initialized = False
|
| 72 |
self.available_tools = {}
|
| 73 |
self.system_prompt = ""
|
| 74 |
+
|
| 75 |
+
# Add conversation manager for token optimization
|
| 76 |
+
self.conversation_manager = ConversationManager(
|
| 77 |
+
max_history_pairs=3, # Only keep last 3 exchanges
|
| 78 |
+
max_context_chars=2000 # Limit context size
|
| 79 |
+
)
|
| 80 |
|
| 81 |
async def generate_tools_prompt(self):
|
| 82 |
+
"""Generate a detailed prompt section about available tools"""
|
| 83 |
+
try:
|
| 84 |
+
tools_prompt = "\n## π οΈ AVAILABLE TOOLS\n"
|
| 85 |
+
tools_prompt += "You have access to the following browser automation tools via MCP:\n\n"
|
| 86 |
+
|
| 87 |
+
for tool_name, tool_info in self.available_tools.items():
|
| 88 |
+
tools_prompt += f"### {tool_name}\n"
|
| 89 |
+
|
| 90 |
+
# Add description from StructuredTool object
|
| 91 |
+
description = getattr(tool_info, 'description', 'No description available')
|
| 92 |
+
tools_prompt += f"**Description**: {description}\n"
|
| 93 |
+
|
| 94 |
+
# Add parameters from args_schema if available
|
| 95 |
+
if hasattr(tool_info, 'args_schema') and tool_info.args_schema:
|
| 96 |
+
try:
|
| 97 |
+
schema = tool_info.args_schema.model_json_schema()
|
| 98 |
+
if 'properties' in schema:
|
| 99 |
+
tools_prompt += "**Parameters**:\n"
|
| 100 |
+
for param_name, param_info in schema['properties'].items():
|
| 101 |
+
param_type = param_info.get('type', 'unknown')
|
| 102 |
+
param_desc = param_info.get('description', 'No description')
|
| 103 |
+
required = param_name in schema.get('required', [])
|
| 104 |
+
required_mark = " (required)" if required else " (optional)"
|
| 105 |
+
tools_prompt += f"- `{param_name}` ({param_type}){required_mark}: {param_desc}\n"
|
| 106 |
+
except Exception as schema_error:
|
| 107 |
+
logger.debug(f"Could not parse schema for {tool_name}: {schema_error}")
|
| 108 |
+
tools_prompt += "**Usage**: Call this tool when you need to perform this browser action\n"
|
| 109 |
+
else:
|
| 110 |
+
tools_prompt += "**Usage**: Call this tool when you need to perform this browser action\n"
|
| 111 |
+
|
| 112 |
+
tools_prompt += "\n"
|
| 113 |
+
|
| 114 |
+
tools_prompt += """
|
| 115 |
+
π― MultiβStep Workflow
|
| 116 |
+
Navigate & Snapshot
|
| 117 |
+
Load the target page
|
| 118 |
+
Capture a snapshot
|
| 119 |
+
Assess if further steps are neededβif so, proceed to the next action
|
| 120 |
+
Perform Action & Validate
|
| 121 |
+
if needed closes add or popups
|
| 122 |
+
Capture a snapshot
|
| 123 |
+
Verify results before moving on
|
| 124 |
+
Keep Browser Open
|
| 125 |
+
Never close the session unless explicitly instructed
|
| 126 |
+
Avoid Redundancy
|
| 127 |
+
Donβt repeat actions (e.g., clicking) when data is already collected
|
| 128 |
+
## π¨ SESSION PERSISTENCE RULES
|
| 129 |
+
- Browser stays open for the entire conversation
|
| 130 |
+
- Each action builds on previous state
|
| 131 |
+
- Context is maintained between requests
|
| 132 |
+
"""
|
| 133 |
+
return tools_prompt
|
| 134 |
+
except Exception as e:
|
| 135 |
+
logger.error(f"Failed to generate tools prompt: {e}")
|
| 136 |
+
return "\n## π οΈ TOOLS\nBrowser automation tools available but not detailed.\n"
|
| 137 |
|
| 138 |
async def get_system_prompt_with_tools(self):
|
| 139 |
base = """π Browser Agent β Persistent Session & Optimized Memory
|
| 140 |
+
You are an intelligent browser automation agent (Playwright via MCP) tasked with keeping a lightweight, ongoing session:
|
| 141 |
+
π― Mission
|
| 142 |
+
Navigate pages, extract and analyze data without closing the browser
|
| 143 |
+
Handle popβups and capture snapshots to validate each step
|
| 144 |
+
π Session Management
|
| 145 |
+
Browser remains open across user requests
|
| 146 |
+
Only recent chat history is provided to save tokens
|
| 147 |
+
Session context (current page, recent actions) is maintained separately
|
| 148 |
+
β‘ Response Structure
|
| 149 |
+
For each action:
|
| 150 |
+
State β tool call
|
| 151 |
+
Snapshot β confirmation
|
| 152 |
+
Next plan (if needed)
|
| 153 |
+
π‘ Best Practices
|
| 154 |
+
Use text selectors and wait for content
|
| 155 |
+
Pause 2β―s between tool calls
|
| 156 |
+
Be concise and focused on the current task it s important as soon as you have the information you came for return it
|
| 157 |
+
If earlier context is needed, ask the user to clarify.
|
| 158 |
"""
|
| 159 |
tools_section = await self.generate_tools_prompt()
|
| 160 |
return base + tools_section
|
| 161 |
|
| 162 |
+
async def initialize(self):
|
| 163 |
+
"""Initialize MCP client, model, session and agent"""
|
| 164 |
+
try:
|
| 165 |
+
logger.info("π Initializing Browser Agent...")
|
| 166 |
+
|
| 167 |
+
# LLM
|
| 168 |
+
mistral_key = os.getenv("mistralkey")
|
| 169 |
+
if not mistral_key:
|
| 170 |
+
raise ValueError("Mistral API key is required")
|
| 171 |
+
|
| 172 |
+
self.model = ChatMistralAI(
|
| 173 |
+
model="mistral-small-latest",
|
| 174 |
+
api_key=mistral_key,
|
| 175 |
+
|
| 176 |
+
)
|
| 177 |
+
logger.info("β
Mistral LLM initialized with optimized settings")
|
| 178 |
+
|
| 179 |
+
# MCP client
|
| 180 |
+
self.client = MultiServerMCPClient({
|
| 181 |
+
"browser": {
|
| 182 |
+
"command": "npx",
|
| 183 |
+
"args": ["@playwright/mcp@latest", "--browser", "chromium","--user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36"],
|
| 184 |
+
"transport": "stdio"
|
| 185 |
+
}
|
| 186 |
+
})
|
| 187 |
+
logger.info("β
MCP client created")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
|
| 189 |
+
# Start persistent session
|
| 190 |
+
self.session_context = self.client.session("browser")
|
| 191 |
+
self.session = await self.session_context.__aenter__()
|
| 192 |
+
logger.info("β
MCP session opened")
|
| 193 |
+
|
| 194 |
+
# Load tools
|
| 195 |
+
tools = await load_mcp_tools(self.session)
|
| 196 |
+
tools.append(SleepTool(description="Wait 4 seconds between two calls"))
|
| 197 |
+
logger.info(f"π₯ Loaded {len(tools)} tools")
|
| 198 |
+
self.available_tools = {t.name: t for t in tools}
|
| 199 |
|
| 200 |
+
# Install browser if needed
|
| 201 |
+
install_tool = self.available_tools.get("browser_install")
|
| 202 |
+
if install_tool:
|
| 203 |
+
try:
|
| 204 |
+
result = await install_tool.arun({})
|
| 205 |
+
logger.info(f"π₯ Browser install: {result}")
|
| 206 |
+
except Exception as e:
|
| 207 |
+
logger.warning(f"β οΈ Browser install failed: {e}, continuing.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
|
| 209 |
+
# System prompt
|
| 210 |
+
self.system_prompt = await self.get_system_prompt_with_tools()
|
| 211 |
+
|
| 212 |
+
# Create agent
|
| 213 |
+
prompt = ChatPromptTemplate.from_messages([
|
| 214 |
+
("system", self.system_prompt),
|
| 215 |
+
MessagesPlaceholder(variable_name="chat_history"),
|
| 216 |
+
("human", "{input}"),
|
| 217 |
+
MessagesPlaceholder(variable_name="agent_scratchpad"),
|
| 218 |
+
])
|
| 219 |
+
agent = create_tool_calling_agent(
|
| 220 |
+
llm=self.model,
|
| 221 |
+
tools=tools,
|
| 222 |
+
prompt=prompt
|
| 223 |
+
)
|
| 224 |
+
self.agent_executor = AgentExecutor(
|
| 225 |
+
agent=agent,
|
| 226 |
+
tools=tools,
|
| 227 |
+
verbose=True,
|
| 228 |
+
max_iterations=15, # Reduced from 30
|
| 229 |
+
early_stopping_method="generate",
|
| 230 |
+
handle_parsing_errors=True,
|
| 231 |
+
return_intermediate_steps=True,
|
| 232 |
+
max_execution_time=180 # Reduced from 300
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
self.initialized = True
|
| 236 |
+
logger.info("β
Agent initialized with persistent session and optimized memory")
|
| 237 |
+
return True
|
| 238 |
+
|
| 239 |
+
except Exception as e:
|
| 240 |
+
logger.error(f"β Initialization failed: {e}")
|
| 241 |
+
await self.cleanup()
|
| 242 |
+
raise
|
| 243 |
+
|
| 244 |
+
async def process_query(self, query: str, chat_history: List[Tuple[str, str]]) -> str:
|
| 245 |
+
if not self.initialized:
|
| 246 |
+
return "β Agent not initialized. Please restart the application."
|
| 247 |
+
|
| 248 |
+
try:
|
| 249 |
+
# β
KEY OPTIMIZATION: Use only recent history instead of full history
|
| 250 |
+
optimized_history = self.conversation_manager.get_optimized_history(chat_history)
|
| 251 |
+
|
| 252 |
+
# Convert to message format
|
| 253 |
+
history_messages = []
|
| 254 |
+
for human, ai in optimized_history:
|
| 255 |
+
if human: history_messages.append(("human", human))
|
| 256 |
+
if ai: history_messages.append(("ai", ai))
|
| 257 |
+
|
| 258 |
+
# Add session context
|
| 259 |
+
context_summary = self.conversation_manager.get_context_summary()
|
| 260 |
+
enhanced_query = f"{query}\n\n[SESSION_INFO]: {context_summary}"
|
| 261 |
+
|
| 262 |
+
# Log token savings
|
| 263 |
+
original_pairs = len(chat_history)
|
| 264 |
+
optimized_pairs = len(optimized_history)
|
| 265 |
+
logger.info(f"π° Token optimization: {original_pairs} β {optimized_pairs} history pairs")
|
| 266 |
+
|
| 267 |
+
# Execute with optimized history
|
| 268 |
+
resp = await self.agent_executor.ainvoke({
|
| 269 |
+
"input": enhanced_query,
|
| 270 |
+
"chat_history": history_messages
|
| 271 |
+
})
|
| 272 |
+
|
| 273 |
+
# Update session context with this interaction
|
| 274 |
+
self.conversation_manager.update_session_context(
|
| 275 |
+
action=query,
|
| 276 |
+
result=resp["output"]
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
return resp["output"]
|
| 280 |
+
|
| 281 |
+
except Exception as e:
|
| 282 |
+
logger.error(f"Error processing query: {e}")
|
| 283 |
+
return f"β Error: {e}\nπ‘ Ask for a screenshot to diagnose."
|
| 284 |
+
|
| 285 |
+
async def cleanup(self):
|
| 286 |
+
"""Cleanup resources properly"""
|
| 287 |
+
try:
|
| 288 |
+
if self.session_context:
|
| 289 |
+
await self.session_context.__aexit__(None, None, None)
|
| 290 |
+
logger.info("β
MCP session closed")
|
| 291 |
+
self.session_context = None
|
| 292 |
+
self.session = None
|
| 293 |
+
|
| 294 |
+
if self.client:
|
| 295 |
+
await self.client.close()
|
| 296 |
+
logger.info("β
MCP client closed")
|
| 297 |
+
self.client = None
|
| 298 |
+
|
| 299 |
+
self.initialized = False
|
| 300 |
+
|
| 301 |
+
except Exception as e:
|
| 302 |
+
logger.error(f"Cleanup error: {e}")
|
| 303 |
+
|
| 304 |
+
def get_token_usage_stats(self, full_history: List[Tuple[str, str]]) -> Dict[str, Any]:
|
| 305 |
+
"""Get statistics about token usage optimization"""
|
| 306 |
+
original_pairs = len(full_history)
|
| 307 |
+
optimized_pairs = len(self.conversation_manager.get_optimized_history(full_history))
|
| 308 |
+
|
| 309 |
+
# Rough token estimation (1 token β 4 characters)
|
| 310 |
+
def estimate_tokens(text: str) -> int:
|
| 311 |
+
return len(text) // 4
|
| 312 |
+
|
| 313 |
+
original_tokens = sum(estimate_tokens(msg[0] + msg[1]) for msg in full_history)
|
| 314 |
+
optimized_tokens = sum(estimate_tokens(msg[0] + msg[1]) for msg in self.conversation_manager.get_optimized_history(full_history))
|
| 315 |
+
|
| 316 |
+
return {
|
| 317 |
+
"original_pairs": original_pairs,
|
| 318 |
+
"optimized_pairs": optimized_pairs,
|
| 319 |
+
"pairs_saved": original_pairs - optimized_pairs,
|
| 320 |
+
"estimated_original_tokens": original_tokens,
|
| 321 |
+
"estimated_optimized_tokens": optimized_tokens,
|
| 322 |
+
"estimated_tokens_saved": original_tokens - optimized_tokens,
|
| 323 |
+
"savings_percentage": ((original_tokens - optimized_tokens) / original_tokens * 100) if original_tokens > 0 else 0
|
| 324 |
+
}
|
| 325 |
+
|
| 326 |
+
# Global agent instance
|
| 327 |
agent: Optional[BrowserAgent] = None
|
| 328 |
+
event_loop: Optional[asyncio.AbstractEventLoop] = None
|
| 329 |
|
| 330 |
+
async def initialize_agent_async(api_key: str) -> str:
|
| 331 |
+
"""Initialize the agent asynchronously"""
|
| 332 |
global agent
|
| 333 |
+
|
| 334 |
if not api_key.strip():
|
| 335 |
+
return "β Please provide a Mistral API key"
|
| 336 |
+
|
| 337 |
try:
|
| 338 |
+
# Cleanup existing agent
|
| 339 |
+
if agent:
|
| 340 |
+
await agent.cleanup()
|
| 341 |
+
|
| 342 |
+
# Create new agent
|
| 343 |
agent = BrowserAgent(api_key)
|
| 344 |
+
await agent.initialize()
|
| 345 |
+
|
| 346 |
+
info = await agent.get_system_prompt_with_tools()
|
| 347 |
+
return f"β
Agent Initialized Successfully with Token Optimization!\n\n{info[:1000]}..."
|
| 348 |
+
|
| 349 |
except Exception as e:
|
| 350 |
+
logger.error(f"Initialization error: {e}")
|
| 351 |
+
return f"β Failed to initialize agent: {e}"
|
| 352 |
|
| 353 |
+
async def process_message_async(message: str, history: List[List[str]]) -> Tuple[str, List[List[str]]]:
|
| 354 |
+
"""Process message asynchronously with token optimization"""
|
| 355 |
global agent
|
| 356 |
+
|
| 357 |
if not agent or not agent.initialized:
|
| 358 |
+
error_msg = "β Agent not initialized. Please initialize first with your API key."
|
| 359 |
+
history.append([message, error_msg])
|
| 360 |
return "", history
|
| 361 |
+
|
| 362 |
if not message.strip():
|
| 363 |
+
error_msg = "Please enter a message"
|
| 364 |
+
history.append([message, error_msg])
|
| 365 |
return "", history
|
| 366 |
+
|
|
|
|
| 367 |
try:
|
| 368 |
+
# Convert history format for the agent
|
| 369 |
+
agent_history = [(msg[0], msg[1]) for msg in history]
|
| 370 |
+
|
| 371 |
+
# Get token usage stats before processing
|
| 372 |
+
stats = agent.get_token_usage_stats(agent_history)
|
| 373 |
+
|
| 374 |
+
# Process the query with optimized history
|
| 375 |
+
response = await agent.process_query(message, agent_history)
|
| 376 |
+
|
| 377 |
+
# Add token savings info to response if significant savings
|
| 378 |
+
if stats["savings_percentage"] > 50:
|
| 379 |
+
response += f"\n\nπ° Token savings: {stats['savings_percentage']:.1f}% ({stats['estimated_tokens_saved']} tokens saved)"
|
| 380 |
+
|
| 381 |
+
# Add to history
|
| 382 |
+
history.append([message, response])
|
| 383 |
+
|
| 384 |
return "", history
|
| 385 |
+
|
| 386 |
except Exception as e:
|
| 387 |
+
logger.error(f"Message processing error: {e}")
|
| 388 |
+
error_msg = f"β Error: {e}\nπ‘ Try asking for a screenshot to diagnose."
|
| 389 |
+
history.append([message, error_msg])
|
| 390 |
return "", history
|
| 391 |
|
| 392 |
+
def run_in_event_loop(coro):
|
| 393 |
+
"""Run coroutine in the event loop"""
|
| 394 |
+
global event_loop
|
| 395 |
+
if event_loop and not event_loop.is_closed():
|
| 396 |
+
return asyncio.run_coroutine_threadsafe(coro, event_loop).result()
|
| 397 |
+
else:
|
| 398 |
+
return asyncio.run(coro)
|
| 399 |
+
|
| 400 |
+
# Sync wrappers for Gradio
|
| 401 |
+
def initialize_agent_sync(api_key: str) -> str:
|
| 402 |
+
"""Sync wrapper for agent initialization"""
|
| 403 |
+
return run_in_event_loop(initialize_agent_async(api_key))
|
| 404 |
+
|
| 405 |
+
def process_message_sync(message: str, history: List[List[str]]) -> Tuple[str, List[List[str]]]:
|
| 406 |
+
"""Sync wrapper for message processing"""
|
| 407 |
+
return run_in_event_loop(process_message_async(message, history))
|
| 408 |
+
|
| 409 |
def get_token_stats_sync(history: List[List[str]]) -> str:
|
| 410 |
+
"""Get token usage statistics"""
|
| 411 |
global agent
|
| 412 |
if not agent or not agent.initialized:
|
| 413 |
+
return "Agent not initialized"
|
| 414 |
+
|
| 415 |
+
agent_history = [(msg[0], msg[1]) for msg in history]
|
| 416 |
+
stats = agent.get_token_usage_stats(agent_history)
|
| 417 |
+
|
| 418 |
+
return f"""π Token Usage Statistics:
|
| 419 |
+
β’ Original conversation pairs: {stats['original_pairs']}
|
| 420 |
+
β’ Optimized conversation pairs: {stats['optimized_pairs']}
|
| 421 |
+
β’ Pairs saved: {stats['pairs_saved']}
|
| 422 |
+
β’ Estimated original tokens: {stats['estimated_original_tokens']:,}
|
| 423 |
+
β’ Estimated optimized tokens: {stats['estimated_optimized_tokens']:,}
|
| 424 |
+
β’ Estimated tokens saved: {stats['estimated_tokens_saved']:,}
|
| 425 |
+
β’ Savings percentage: {stats['savings_percentage']:.1f}%"""
|
| 426 |
|
| 427 |
def create_interface():
|
| 428 |
+
"""Create the Gradio interface"""
|
| 429 |
+
|
| 430 |
+
with gr.Blocks(
|
| 431 |
+
title="MCP Browser Agent - Token Optimized",
|
| 432 |
+
theme=gr.themes.Soft(),
|
| 433 |
+
css="""
|
| 434 |
+
.container { max-width: 1200px; margin: auto; }
|
| 435 |
+
.header { text-align: center; margin-bottom: 2rem; }
|
| 436 |
+
.status-box { padding: 1rem; border-radius: 8px; margin: 1rem 0; }
|
| 437 |
+
.token-stats { background: #f0f8ff; padding: 1rem; border-radius: 8px; }
|
| 438 |
+
"""
|
| 439 |
+
) as interface:
|
| 440 |
+
|
| 441 |
+
gr.HTML("""
|
| 442 |
+
<div class="header">
|
| 443 |
+
<h1>π MCP Browser Agent - Token Optimized</h1>
|
| 444 |
+
<p>AI-powered web browsing with persistent sessions and optimized token usage</p>
|
| 445 |
+
</div>
|
| 446 |
+
""")
|
| 447 |
+
|
| 448 |
+
with gr.Row():
|
| 449 |
+
with gr.Column(scale=1):
|
| 450 |
+
gr.Markdown("### π§ Configuration")
|
| 451 |
+
api_key_input = gr.Textbox(
|
| 452 |
+
label="Mistral API Key",
|
| 453 |
+
placeholder="Enter your Mistral API key...",
|
| 454 |
+
type="password",
|
| 455 |
+
lines=1
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
init_button = gr.Button("Initialize Agent", variant="primary")
|
| 459 |
+
status_output = gr.Textbox(
|
| 460 |
+
label="Status & Available Tools",
|
| 461 |
+
interactive=False,
|
| 462 |
+
lines=6
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
gr.Markdown("### π° Token Optimization")
|
| 466 |
+
token_stats_button = gr.Button("Show Token Stats", variant="secondary")
|
| 467 |
+
token_stats_output = gr.Textbox(
|
| 468 |
+
label="Token Usage Statistics",
|
| 469 |
+
interactive=False,
|
| 470 |
+
lines=8
|
| 471 |
+
)
|
| 472 |
+
|
| 473 |
+
gr.Markdown("""
|
| 474 |
+
### π Optimized Usage Tips
|
| 475 |
+
**Token Savings Features:**
|
| 476 |
+
- Only last 3 conversation pairs sent to API
|
| 477 |
+
- Session context maintained separately
|
| 478 |
+
- Reduced max tokens per response
|
| 479 |
+
- Smart context summarization
|
| 480 |
+
|
| 481 |
+
**Best Practices:**
|
| 482 |
+
- Be specific in your requests
|
| 483 |
+
- Use "take screenshot" to check current state
|
| 484 |
+
- Ask for "browser status" if you need context
|
| 485 |
+
- Long conversations automatically optimized
|
| 486 |
+
""")
|
| 487 |
+
|
| 488 |
+
with gr.Column(scale=2):
|
| 489 |
+
gr.Markdown("### π¬ Chat with Browser Agent")
|
| 490 |
+
|
| 491 |
+
chatbot = gr.Chatbot(
|
| 492 |
+
label="Conversation",
|
| 493 |
+
height=500,
|
| 494 |
+
show_copy_button=True
|
| 495 |
+
)
|
| 496 |
+
|
| 497 |
+
with gr.Row():
|
| 498 |
+
message_input = gr.Textbox(
|
| 499 |
+
label="Message",
|
| 500 |
+
placeholder="Enter your browsing request...",
|
| 501 |
+
lines=2,
|
| 502 |
+
scale=4
|
| 503 |
+
)
|
| 504 |
+
send_button = gr.Button("Send", variant="primary", scale=1)
|
| 505 |
+
|
| 506 |
+
with gr.Row():
|
| 507 |
+
clear_button = gr.Button("Clear Chat", variant="secondary")
|
| 508 |
+
screenshot_button = gr.Button("Quick Screenshot", variant="secondary")
|
| 509 |
+
|
| 510 |
+
# Event handlers
|
| 511 |
+
init_button.click(
|
| 512 |
+
fn=initialize_agent_sync,
|
| 513 |
+
inputs=[api_key_input],
|
| 514 |
+
outputs=[status_output]
|
| 515 |
+
)
|
| 516 |
+
|
| 517 |
+
send_button.click(
|
| 518 |
+
fn=process_message_sync,
|
| 519 |
+
inputs=[message_input, chatbot],
|
| 520 |
+
outputs=[message_input, chatbot]
|
| 521 |
+
)
|
| 522 |
+
|
| 523 |
+
message_input.submit(
|
| 524 |
+
fn=process_message_sync,
|
| 525 |
+
inputs=[message_input, chatbot],
|
| 526 |
+
outputs=[message_input, chatbot]
|
| 527 |
+
)
|
| 528 |
+
|
| 529 |
+
clear_button.click(
|
| 530 |
+
fn=lambda: [],
|
| 531 |
+
outputs=[chatbot]
|
| 532 |
+
)
|
| 533 |
+
|
| 534 |
+
screenshot_button.click(
|
| 535 |
+
fn=lambda history: process_message_sync("Take a screenshot of the current page", history),
|
| 536 |
+
inputs=[chatbot],
|
| 537 |
+
outputs=[message_input, chatbot]
|
| 538 |
+
)
|
| 539 |
+
|
| 540 |
+
token_stats_button.click(
|
| 541 |
+
fn=get_token_stats_sync,
|
| 542 |
+
inputs=[chatbot],
|
| 543 |
+
outputs=[token_stats_output]
|
| 544 |
+
)
|
| 545 |
+
|
| 546 |
+
# Add helpful information
|
| 547 |
+
with gr.Accordion("βΉοΈ Token Optimization Guide", open=False):
|
| 548 |
+
gr.Markdown("""
|
| 549 |
+
## π° How Token Optimization Works
|
| 550 |
+
|
| 551 |
+
**The Problem with Original Code:**
|
| 552 |
+
- Every API call sent complete conversation history
|
| 553 |
+
- Token usage grew exponentially with conversation length
|
| 554 |
+
- Costs could explode for long sessions
|
| 555 |
+
|
| 556 |
+
**Our Optimization Solutions:**
|
| 557 |
+
|
| 558 |
+
1. **Limited History Window**: Only last 3 conversation pairs sent to API
|
| 559 |
+
2. **Session Context**: Browser state maintained separately from chat history
|
| 560 |
+
3. **Smart Summarization**: Key session info added to each request
|
| 561 |
+
4. **Reduced Limits**: Lower max_tokens and max_iterations
|
| 562 |
+
5. **Token Tracking**: Real-time savings statistics
|
| 563 |
+
|
| 564 |
+
**Token Savings Example:**
|
| 565 |
+
```
|
| 566 |
+
Original: 10 messages = 5,000 tokens per API call
|
| 567 |
+
Optimized: 10 messages = 500 tokens per API call
|
| 568 |
+
Savings: 90% reduction in token usage!
|
| 569 |
+
```
|
| 570 |
+
|
| 571 |
+
**What This Means:**
|
| 572 |
+
- β
Persistent browser sessions still work
|
| 573 |
+
- β
90%+ reduction in API costs
|
| 574 |
+
- β
Faster response times
|
| 575 |
+
- β
Better performance for long conversations
|
| 576 |
+
- β οΈ Agent has limited memory of old messages
|
| 577 |
+
|
| 578 |
+
**If Agent Needs Earlier Context:**
|
| 579 |
+
- Use "browser status" to check current state
|
| 580 |
+
- Take screenshots to show current page
|
| 581 |
+
- Re-explain context if needed
|
| 582 |
+
- Clear chat periodically for fresh start
|
| 583 |
+
""")
|
| 584 |
+
|
| 585 |
return interface
|
| 586 |
|
| 587 |
+
async def cleanup_agent():
|
| 588 |
+
"""Cleanup agent resources"""
|
| 589 |
+
global agent
|
| 590 |
+
if agent:
|
| 591 |
+
await agent.cleanup()
|
| 592 |
+
logger.info("π§Ή Agent cleaned up")
|
| 593 |
+
|
| 594 |
def signal_handler(signum, frame):
|
| 595 |
+
"""Handle shutdown signals"""
|
| 596 |
+
logger.info(f"π‘ Received signal {signum}, cleaning up...")
|
| 597 |
+
global event_loop
|
| 598 |
+
if event_loop and not event_loop.is_closed():
|
| 599 |
+
event_loop.create_task(cleanup_agent())
|
| 600 |
sys.exit(0)
|
| 601 |
|
| 602 |
+
async def main():
|
| 603 |
+
"""Main async function to run everything"""
|
| 604 |
+
global event_loop
|
| 605 |
|
| 606 |
+
# Set up signal handlers
|
| 607 |
signal.signal(signal.SIGINT, signal_handler)
|
| 608 |
signal.signal(signal.SIGTERM, signal_handler)
|
| 609 |
|
| 610 |
+
# Get the current event loop
|
| 611 |
+
event_loop = asyncio.get_event_loop()
|
| 612 |
+
|
| 613 |
+
try:
|
| 614 |
+
logger.info("π Starting MCP Browser Agent Application with Token Optimization...")
|
| 615 |
+
|
| 616 |
+
# Create and launch interface
|
| 617 |
+
interface = create_interface()
|
| 618 |
+
|
| 619 |
+
# Launch interface (this will block)
|
| 620 |
+
await asyncio.to_thread(
|
| 621 |
+
interface.launch,
|
| 622 |
+
server_name="0.0.0.0",
|
| 623 |
+
server_port=7860,
|
| 624 |
+
share=False,
|
| 625 |
+
debug=False,
|
| 626 |
+
show_error=True,
|
| 627 |
+
quiet=False
|
| 628 |
+
)
|
| 629 |
+
|
| 630 |
+
except Exception as e:
|
| 631 |
+
logger.error(f"Application error: {e}")
|
| 632 |
+
finally:
|
| 633 |
+
await cleanup_agent()
|
| 634 |
|
| 635 |
+
if __name__ == "__main__":
|
| 636 |
+
try:
|
| 637 |
+
asyncio.run(main())
|
| 638 |
+
except KeyboardInterrupt:
|
| 639 |
+
logger.info("π Application stopped by user")
|
| 640 |
+
except Exception as e:
|
| 641 |
+
logger.error(f"Fatal error: {e}")
|
| 642 |
+
finally:
|
| 643 |
+
logger.info("π Application shutdown complete")
|