feat : frontend message streaming

This commit is contained in:
martin legrand
2025-04-18 15:42:53 +02:00
parent 3a9514629a
commit 83c595144b
13 changed files with 191 additions and 108 deletions
+35 -3
View File
@@ -5,6 +5,9 @@ import os
import random
import time
import asyncio
from concurrent.futures import ThreadPoolExecutor
from sources.memory import Memory
from sources.utility import pretty_print
from sources.schemas import executorResult
@@ -43,7 +46,28 @@ class Agent():
self.blocks_result = []
self.last_answer = ""
self.verbose = verbose
self.executor = ThreadPoolExecutor(max_workers=1)
@property
def get_agent_name(self) -> str:
return self.agent_name
@property
def get_agent_type(self) -> str:
return self.type
@property
def get_agent_role(self) -> str:
return self.role
@property
def get_last_answer(self) -> str:
return self.last_answer
@property
def get_blocks(self) -> list:
return self.blocks_result
@property
def get_tools(self) -> dict:
return self.tools
@@ -90,7 +114,14 @@ class Agent():
end_idx = text.rfind(end_tag)+8
return text[start_idx:end_idx]
def llm_request(self) -> Tuple[str, str]:
async def llm_request(self) -> Tuple[str, str]:
"""
Asynchronously ask the LLM to process the prompt.
"""
loop = asyncio.get_event_loop()
return await loop.run_in_executor(self.executor, self.sync_llm_request)
def sync_llm_request(self) -> Tuple[str, str]:
"""
Ask the LLM to process the prompt and return the answer and the reasoning.
"""
@@ -102,14 +133,15 @@ class Agent():
self.memory.push('assistant', answer)
return answer, reasoning
def wait_message(self, speech_module):
async def wait_message(self, speech_module):
if speech_module is None:
return
messages = ["Please be patient, I am working on it.",
"Computing... I recommand you have a coffee while I work.",
"Hold on, Im crunching numbers.",
"Working on it, please let me think."]
if speech_module: speech_module.speak(messages[random.randint(0, len(messages)-1)])
loop = asyncio.get_event_loop()
return await loop.run_in_executor(self.executor, lambda: speech_module.speak(messages[random.randint(0, len(messages)-1)]))
def get_blocks_result(self) -> list:
return self.blocks_result
+10 -7
View File
@@ -3,6 +3,7 @@ import time
from datetime import date
from typing import List, Tuple, Type, Dict
from enum import Enum
import asyncio
from sources.utility import pretty_print, animate_thinking
from sources.agents.agent import Agent
@@ -166,10 +167,10 @@ class BrowserAgent(Agent):
You must always take notes.
"""
def llm_decide(self, prompt: str, show_reasoning: bool = False) -> Tuple[str, str]:
async def llm_decide(self, prompt: str, show_reasoning: bool = False) -> Tuple[str, str]:
animate_thinking("Thinking...", color="status")
self.memory.push('user', prompt)
answer, reasoning = self.llm_request()
answer, reasoning = await self.llm_request()
if show_reasoning:
pretty_print(reasoning, color="failure")
pretty_print(answer, color="output")
@@ -287,7 +288,7 @@ class BrowserAgent(Agent):
pretty_print(f"Title: {res['title']} - ", color="info", no_newline=True)
pretty_print(f"Link: {res['link']}", color="status")
def process(self, user_prompt: str, speech_module: type) -> Tuple[str, str]:
async def process(self, user_prompt: str, speech_module: type) -> Tuple[str, str]:
"""
Process the user prompt to conduct an autonomous web search.
Start with a google search with searxng using web_search tool.
@@ -302,7 +303,7 @@ class BrowserAgent(Agent):
animate_thinking(f"Thinking...", color="status")
mem_begin_idx = self.memory.push('user', self.search_prompt(user_prompt))
ai_prompt, reasoning = self.llm_request()
ai_prompt, reasoning = await self.llm_request()
if Action.REQUEST_EXIT.value in ai_prompt:
pretty_print(f"Web agent requested exit.\n{reasoning}\n\n{ai_prompt}", color="failure")
return ai_prompt, ""
@@ -315,7 +316,8 @@ class BrowserAgent(Agent):
while not complete and len(unvisited) > 0:
self.memory.clear()
answer, reasoning = self.llm_decide(prompt, show_reasoning = False)
answer, reasoning = await self.llm_decide(prompt, show_reasoning = False)
self.last_answer = answer
pretty_print(''*32, color="status")
extracted_form = self.extract_form(answer)
@@ -324,7 +326,7 @@ class BrowserAgent(Agent):
fill_success = self.browser.fill_form(extracted_form)
page_text = self.browser.get_text()
answer = self.handle_update_prompt(user_prompt, page_text, fill_success)
answer, reasoning = self.llm_decide(prompt)
answer, reasoning = await self.llm_decide(prompt)
if Action.FORM_FILLED.value in answer:
pretty_print(f"Filled form. Handling page update.", color="status")
@@ -355,11 +357,12 @@ class BrowserAgent(Agent):
page_text = self.browser.get_text()
self.navigable_links = self.browser.get_navigable()
prompt = self.make_navigation_prompt(user_prompt, page_text)
self.browser.screenshot()
pretty_print("Exited navigation, starting to summarize finding...", color="status")
prompt = self.conclude_prompt(user_prompt)
mem_last_idx = self.memory.push('user', prompt)
answer, reasoning = self.llm_request()
answer, reasoning = await self.llm_request()
pretty_print(answer, color="output")
return answer, reasoning
+3 -2
View File
@@ -1,3 +1,4 @@
import asyncio
from sources.utility import pretty_print, animate_thinking
from sources.agents.agent import Agent
@@ -17,10 +18,10 @@ class CasualAgent(Agent):
self.role = "talk"
self.type = "casual_agent"
def process(self, prompt, speech_module) -> str:
async def process(self, prompt, speech_module) -> str:
self.memory.push('user', prompt)
animate_thinking("Thinking...", color="status")
answer, reasoning = self.llm_request()
answer, reasoning = await self.llm_request()
self.last_answer = answer
return answer, reasoning
+9 -7
View File
@@ -1,4 +1,5 @@
import platform, os
import asyncio
from sources.utility import pretty_print, animate_thinking
from sources.agents.agent import Agent, executorResult
@@ -26,7 +27,6 @@ class CoderAgent(Agent):
self.work_dir = self.tools["file_finder"].get_work_dir()
self.role = "code"
self.type = "code_agent"
def add_sys_info_prompt(self, prompt):
"""Add system information to the prompt."""
@@ -36,7 +36,7 @@ class CoderAgent(Agent):
f"\nYou must save file in work directory: {self.work_dir}"
return f"{prompt}\n\n{info}"
def process(self, prompt, speech_module) -> str:
async def process(self, prompt, speech_module) -> str:
answer = ""
attempt = 0
max_attempts = 4
@@ -46,20 +46,22 @@ class CoderAgent(Agent):
while attempt < max_attempts:
animate_thinking("Thinking...", color="status")
self.wait_message(speech_module)
answer, reasoning = self.llm_request()
await self.wait_message(speech_module)
answer, reasoning = await self.llm_request()
if clarify_trigger in answer:
self.last_answer = answer
await asyncio.sleep(0)
return answer, reasoning
if not "```" in answer:
self.last_answer = answer
await asyncio.sleep(0)
break
animate_thinking("Executing code...", color="status")
exec_success, _ = self.execute_modules(answer)
answer = self.remove_blocks(answer)
self.last_answer = answer
if self.get_last_tool_type() == "bash":
continue
if exec_success:
await asyncio.sleep(0)
if exec_success and self.get_last_tool_type() != "bash":
break
pretty_print("Execution failure", color="failure")
pretty_print("Correcting code...", color="status")
+4 -3
View File
@@ -1,3 +1,4 @@
import asyncio
from sources.utility import pretty_print, animate_thinking
from sources.agents.agent import Agent
@@ -18,14 +19,14 @@ class FileAgent(Agent):
self.role = "files"
self.type = "file_agent"
def process(self, prompt, speech_module) -> str:
async def process(self, prompt, speech_module) -> str:
exec_success = False
prompt += f"\nYou must work in directory: {self.work_dir}"
self.memory.push('user', prompt)
while exec_success is False:
self.wait_message(speech_module)
await self.wait_message(speech_module)
animate_thinking("Thinking...", color="status")
answer, reasoning = self.llm_request()
answer, reasoning = await self.llm_request()
exec_success, _ = self.execute_modules(answer)
answer = self.remove_blocks(answer)
self.last_answer = answer
+7 -7
View File
@@ -86,13 +86,13 @@ class PlannerAgent(Agent):
pretty_print(f"{task['agent']} -> {task['task']}", color="info")
pretty_print("▔▗ E N D ▖▔", color="status")
def make_plan(self, prompt: str) -> str:
async def make_plan(self, prompt: str) -> str:
ok = False
answer = None
while not ok:
animate_thinking("Thinking...", color="status")
self.memory.push('user', prompt)
answer, _ = self.llm_request()
answer, _ = await self.llm_request()
agents_tasks = self.parse_agent_tasks(answer)
if agents_tasks == (None, None):
prompt = f"Failed to parse the tasks. Please make a plan within ```json.\n"
@@ -102,10 +102,10 @@ class PlannerAgent(Agent):
ok = True
return answer
def start_agent_process(self, task: str, required_infos: dict | None) -> str:
async def start_agent_process(self, task: str, required_infos: dict | None) -> str:
agent_prompt = self.make_prompt(task['task'], required_infos)
pretty_print(f"Agent {task['agent']} started working...", color="status")
agent_answer, _ = self.agents[task['agent'].lower()].process(agent_prompt, None)
agent_answer, _ = await self.agents[task['agent'].lower()].process(agent_prompt, None)
self.agents[task['agent'].lower()].show_answer()
pretty_print(f"Agent {task['agent']} completed task.", color="status")
return agent_answer
@@ -113,11 +113,11 @@ class PlannerAgent(Agent):
def get_work_result_agent(self, task_needs, agents_work_result):
return {k: agents_work_result[k] for k in task_needs if k in agents_work_result}
def process(self, prompt: str, speech_module: Speech) -> Tuple[str, str]:
async def process(self, prompt: str, speech_module: Speech) -> Tuple[str, str]:
agents_tasks = (None, None)
agents_work_result = dict()
answer = self.make_plan(prompt)
answer = await self.make_plan(prompt)
agents_tasks = self.parse_agent_tasks(answer)
if agents_tasks == (None, None):
@@ -130,7 +130,7 @@ class PlannerAgent(Agent):
if agents_work_result is not None:
required_infos = self.get_work_result_agent(task['need'], agents_work_result)
try:
self.last_answer = self.start_agent_process(task, required_infos)
self.last_answer = await self.start_agent_process(task, required_infos)
except Exception as e:
raise e
agents_work_result[task['id']] = self.last_answer