structure saas with tools and mcps with load_memory

This commit is contained in:
Davidson Gomes 2025-04-25 19:16:56 -03:00
parent b3f87abce1
commit 9dd63b3d42
5 changed files with 22 additions and 9 deletions

View File

@ -12,6 +12,8 @@ from sqlalchemy.orm import Session
from contextlib import AsyncExitStack from contextlib import AsyncExitStack
from google.adk.agents.callback_context import CallbackContext from google.adk.agents.callback_context import CallbackContext
from google.adk.models import LlmResponse, LlmRequest from google.adk.models import LlmResponse, LlmRequest
from google.adk.tools import load_memory
from typing import Optional from typing import Optional
import logging import logging
import os import os
@ -161,11 +163,10 @@ def search_knowledge_base_function_sync(query: str, history=[]):
class AgentBuilder: class AgentBuilder:
def __init__(self, db: Session, memory_service: InMemoryMemoryService): def __init__(self, db: Session):
self.db = db self.db = db
self.custom_tool_builder = CustomToolBuilder() self.custom_tool_builder = CustomToolBuilder()
self.mcp_service = MCPService() self.mcp_service = MCPService()
self.memory_service = memory_service
async def _create_llm_agent( async def _create_llm_agent(
self, agent self, agent
@ -184,11 +185,6 @@ class AgentBuilder:
# Combina todas as ferramentas # Combina todas as ferramentas
all_tools = custom_tools + mcp_tools all_tools = custom_tools + mcp_tools
# Verifica se load_memory está habilitado
before_model_callback_func = None
if agent.config.get("load_memory") == True:
before_model_callback_func = before_model_callback
now = datetime.now() now = datetime.now()
current_datetime = now.strftime("%d/%m/%Y %H:%M") current_datetime = now.strftime("%d/%m/%Y %H:%M")
@ -204,6 +200,13 @@ class AgentBuilder:
current_time=current_time, current_time=current_time,
) )
# Verifica se load_memory está habilitado
# before_model_callback_func = None
if agent.config.get("load_memory") == True:
all_tools.append(load_memory)
# before_model_callback_func = before_model_callback
formatted_prompt = formatted_prompt + "\n\n<memory_instructions>ALWAYS use the load_memory tool to retrieve knowledge for your context</memory_instructions>\n\n"
return ( return (
LlmAgent( LlmAgent(
name=agent.name, name=agent.name,
@ -211,7 +214,7 @@ class AgentBuilder:
instruction=formatted_prompt, instruction=formatted_prompt,
description=agent.description, description=agent.description,
tools=all_tools, tools=all_tools,
before_model_callback=before_model_callback_func, # before_model_callback=before_model_callback_func,
), ),
mcp_exit_stack, mcp_exit_stack,
) )

View File

@ -42,7 +42,7 @@ async def run_agent(
raise AgentNotFoundError(f"Agente com ID {agent_id} não encontrado") raise AgentNotFoundError(f"Agente com ID {agent_id} não encontrado")
# Usando o AgentBuilder para criar o agente # Usando o AgentBuilder para criar o agente
agent_builder = AgentBuilder(db, memory_service) agent_builder = AgentBuilder(db)
root_agent, exit_stack = await agent_builder.build_agent(get_root_agent) root_agent, exit_stack = await agent_builder.build_agent(get_root_agent)
logger.info("Configurando Runner") logger.info("Configurando Runner")
@ -51,6 +51,7 @@ async def run_agent(
app_name=get_root_agent.name, app_name=get_root_agent.name,
session_service=session_service, session_service=session_service,
artifact_service=artifacts_service, artifact_service=artifacts_service,
memory_service=memory_service,
) )
session_id = contact_id + "_" + agent_id session_id = contact_id + "_" + agent_id
@ -82,6 +83,15 @@ async def run_agent(
if event.is_final_response() and event.content and event.content.parts: if event.is_final_response() and event.content and event.content.parts:
final_response_text = event.content.parts[0].text final_response_text = event.content.parts[0].text
logger.info(f"Resposta final recebida: {final_response_text}") logger.info(f"Resposta final recebida: {final_response_text}")
completed_session = session_service.get_session(
app_name=root_agent.name,
user_id=contact_id,
session_id=session_id,
)
memory_service.add_session_to_memory(completed_session)
finally: finally:
# Garante que o exit_stack seja fechado corretamente # Garante que o exit_stack seja fechado corretamente
if exit_stack: if exit_stack: