feat: integra Simple Memory nel ReActAgent
- Aggiunti tool memory: remember, recall, preference, memory_stats - Memory persistente tra sessioni (file .langcode/simple_memory.json) - create_react_agent() supporta include_memory_tools - Metodi便捷: remember(), recall(), get_memory_stats() - Tool disponibili: 10 totali (6 built-in + 4 memory)
This commit is contained in:
1 parent
cce8709149
commit
fc60fc1fd0
1 file changed
+110
-4
+110
-4
@@ -23,7 +23,7 @@ from langchain_core.messages import HumanMessage, AIMessage, SystemMessage, Base
|
||||
from langchain_core.tools import Tool
|
||||
|
||||
from enhancements.planning_enhancement import EnhancedPlanner, TaskPriority
|
||||
from enhancements.simple_memory import SimplePersistentMemory
|
||||
from enhancements.simple_memory import SimplePersistentMemory, create_simple_memory_tools
|
||||
|
||||
|
||||
class AgentState(Enum):
|
||||
@@ -77,7 +77,8 @@ class ReActAgent:
|
||||
max_iterations: int = 10,
|
||||
planner: Optional[EnhancedPlanner] = None,
|
||||
memory: Optional[SimplePersistentMemory] = None,
|
||||
verbose: bool = False
|
||||
verbose: bool = False,
|
||||
include_memory_tools: bool = True
|
||||
):
|
||||
"""
|
||||
Inizializza il ReActAgent.
|
||||
@@ -89,9 +90,9 @@ class ReActAgent:
|
||||
planner: Istanza EnhancedPlanner (creato se None)
|
||||
memory: Istanza SimplePersistentMemory (creato se None)
|
||||
verbose: Se True, stampa debug info
|
||||
include_memory_tools: Se True, aggiunge tool memory (remember, recall, preference)
|
||||
"""
|
||||
self.llm = llm
|
||||
self.tools = {tool.name: tool for tool in tools}
|
||||
self.max_iterations = max_iterations
|
||||
self.verbose = verbose
|
||||
|
||||
@@ -99,10 +100,18 @@ class ReActAgent:
|
||||
self.planner = planner or EnhancedPlanner()
|
||||
self.memory = memory or SimplePersistentMemory()
|
||||
|
||||
# Aggiungi memory tools se richiesto
|
||||
if include_memory_tools:
|
||||
memory_tools = create_simple_memory_tools(self.memory)
|
||||
tools = tools + memory_tools
|
||||
|
||||
self.tools = {tool.name: tool for tool in tools}
|
||||
|
||||
# Stato interno
|
||||
self.steps: List[Step] = []
|
||||
self.current_goal: Optional[str] = None
|
||||
self.context: str = ""
|
||||
self.conversation_history: List[Dict[str, str]] = []
|
||||
|
||||
# System prompt per il loop
|
||||
self._system_prompt = self._build_system_prompt()
|
||||
@@ -493,12 +502,107 @@ Salva il report come report_mese.md"""
|
||||
print(f"⚠️ Decomposition failed: {e}")
|
||||
# Fallback: ritorna goal originale
|
||||
return [complex_goal]
|
||||
|
||||
def get_relevant_facts(self, query: str) -> List[str]:
|
||||
"""
|
||||
Cerca fatti rilevanti nella memoria.
|
||||
|
||||
Args:
|
||||
query: Query di ricerca
|
||||
|
||||
Returns:
|
||||
Lista di fatti rilevanti
|
||||
"""
|
||||
facts = self.memory.search_facts(query)
|
||||
return [f"{f['fact']} ({f['category']})" for f in facts]
|
||||
|
||||
def save_conversation(self, user_input: str, agent_response: str) -> None:
|
||||
"""
|
||||
Salva una conversazione nella memoria.
|
||||
|
||||
Args:
|
||||
user_input: Input dell'utente
|
||||
agent_response: Risposta dell'agente
|
||||
"""
|
||||
self.memory.add_conversation(user_input, agent_response)
|
||||
|
||||
def remember(self, fact: str, category: str = "general") -> str:
|
||||
"""
|
||||
Ricorda un fatto.
|
||||
|
||||
Args:
|
||||
fact: Il fatto da ricordare
|
||||
category: Categoria del fatto
|
||||
|
||||
Returns:
|
||||
Messaggio di conferma
|
||||
"""
|
||||
self.memory.add_fact(fact, category)
|
||||
return f"Ricordato: {fact}"
|
||||
|
||||
def recall(self, query: str) -> str:
|
||||
"""
|
||||
Cerca fatti nella memoria.
|
||||
|
||||
Args:
|
||||
query: Query di ricerca
|
||||
|
||||
Returns:
|
||||
Risultati della ricerca
|
||||
"""
|
||||
facts = self.memory.search_facts(query)
|
||||
if not facts:
|
||||
return f"Nessun ricordo trovato per: {query}"
|
||||
|
||||
result = f"Trovati {len(facts)} ricordi:\n"
|
||||
for f in facts[:5]:
|
||||
result += f"- {f['fact']} ({f['category']})\n"
|
||||
return result
|
||||
|
||||
def get_memory_stats(self) -> Dict[str, Any]:
|
||||
"""
|
||||
Restituisce statistiche della memoria.
|
||||
|
||||
Returns:
|
||||
Statistiche memoria
|
||||
"""
|
||||
return self.memory.get_memory_stats()
|
||||
|
||||
def add_preference(self, key: str, value: Any) -> str:
|
||||
"""
|
||||
Imposta una preferenza.
|
||||
|
||||
Args:
|
||||
key: Chiave preferenza
|
||||
value: Valore preferenza
|
||||
|
||||
Returns:
|
||||
Messaggio di conferma
|
||||
"""
|
||||
self.memory.set_preference(key, value)
|
||||
return f"Preferenza impostata: {key} = {value}"
|
||||
|
||||
def get_preference(self, key: str) -> str:
|
||||
"""
|
||||
Recupera una preferenza.
|
||||
|
||||
Args:
|
||||
key: Chiave preferenza
|
||||
|
||||
Returns:
|
||||
Valore della preferenza
|
||||
"""
|
||||
val = self.memory.get_preference(key)
|
||||
if val is None:
|
||||
return f"Preferenza '{key}' non trovata"
|
||||
return f"{key} = {val}"
|
||||
|
||||
|
||||
def create_react_agent(
|
||||
llm,
|
||||
tools: Optional[List[Tool]] = None,
|
||||
include_builtin_tools: bool = True,
|
||||
include_memory_tools: bool = True,
|
||||
max_iterations: int = 10,
|
||||
verbose: bool = False
|
||||
) -> ReActAgent:
|
||||
@@ -509,6 +613,7 @@ def create_react_agent(
|
||||
llm: Modello LLM
|
||||
tools: Lista tool personalizzati
|
||||
include_builtin_tools: Se True, aggiunge tool built-in
|
||||
include_memory_tools: Se True, aggiunge tool memory
|
||||
max_iterations: Massimo iterazioni
|
||||
verbose: Debug output
|
||||
|
||||
@@ -528,5 +633,6 @@ def create_react_agent(
|
||||
llm=llm,
|
||||
tools=tools,
|
||||
max_iterations=max_iterations,
|
||||
verbose=verbose
|
||||
verbose=verbose,
|
||||
include_memory_tools=include_memory_tools
|
||||
)
|
||||
Reference in new issue
Block a user