feat: add find_customer_by_identifier tool and customer state fields

- Add find_customer_by_identifier tool to NaliiaTools
- Add customer_name and customer_id to MessagesState schema
- Update NALIIA_PROMPT template with new tools
- Integrate customer lookup in chat webhook using phone number
This commit is contained in:
2026-03-11 00:02:56 -05:00
parent 4669ae2289
commit 5de87b7c8f
4 changed files with 59 additions and 0 deletions

View File

@@ -7,3 +7,5 @@ class MessagesState(TypedDict):
messages: Annotated[list[AnyMessage], add_messages] messages: Annotated[list[AnyMessage], add_messages]
llm_calls: int llm_calls: int
customer_phone: str customer_phone: str
customer_name: str
customer_id: int

View File

@@ -49,6 +49,8 @@ prompts:
- get_current_datetime: Consultar fecha y hora actual para tomar desciciones. - get_current_datetime: Consultar fecha y hora actual para tomar desciciones.
- schedule_appointment: Agendar y confirmar cita. - schedule_appointment: Agendar y confirmar cita.
- find_service_centers: Consultar los centros de atencion o servicio disponibles. - find_service_centers: Consultar los centros de atencion o servicio disponibles.
- find_products_and_services: Consultar los productos y servicios disponibles con precios.
- find_customer_by_identifier: Buscar cliente por telefono, email o numero de documento.
</Tools Disponibles Para Brindar Atencion al Cliente> </Tools Disponibles Para Brindar Atencion al Cliente>
""" """

View File

@@ -27,6 +27,7 @@ class NaliiaTools:
self.schedule_appointment, self.schedule_appointment,
self.find_service_centers, self.find_service_centers,
self.find_products_and_services, self.find_products_and_services,
self.find_customer_by_identifier,
] ]
@tool @tool
@@ -72,6 +73,32 @@ class NaliiaTools:
return today_date_formated return today_date_formated
@tool
def find_customer_by_identifier(identifier: str) -> str:
"""
Busca un cliente por su identificador (teléfono, email o número de documento).
Args:
identifier: Identificador del cliente (teléfono, email o número de documento).
Returns:
str: JSON con la información del cliente encontrado.
Estructura: {"id": int, "name": str, "phone": str, "email": str}
Ejemplo: '{"id": 1, "name": "Juan Perez", "phone": "573001234567", "email": "juan@example.com"}'
Retorna "{}" si no se encuentra el cliente.
"""
async def call_tool():
async with _MCP_CLIENT:
result = await _MCP_CLIENT.call_tool(
"find_customer_by_identifier", {"identifier": identifier}
)
logger.info(result.content[0].text)
return result
result = asyncio.run(call_tool())
return result.content[0].text
@tool @tool
def find_service_centers(): def find_service_centers():
""" """

View File

@@ -3,12 +3,15 @@ from langchain.messages import HumanMessage
from ...dependencies import get_agent from ...dependencies import get_agent
from ....logger import logger from ....logger import logger
from ....schemes.chat_schemes import SendMessageScheme from ....schemes.chat_schemes import SendMessageScheme
from naliiabot.bot.tools.naliia_tools import NaliiaTools
import httpx import httpx
import json import json
router = APIRouter() router = APIRouter()
_TOOLS = NaliiaTools()
async def send_whatsapp_message(request_data: SendMessageScheme): async def send_whatsapp_message(request_data: SendMessageScheme):
""" """
@@ -68,11 +71,36 @@ async def webhook_chat(request: Request, agent=Depends(get_agent)):
"messages": [HumanMessage(content=user_message)], "messages": [HumanMessage(content=user_message)],
"llm_calls": 0, "llm_calls": 0,
"customer_phone": "", "customer_phone": "",
"customer_name": "",
"customer_id": 0,
} }
existing_state = await agent.checkpointer.aget(config) existing_state = await agent.checkpointer.aget(config)
if existing_state is None: if existing_state is None:
initial_state["customer_phone"] = customer_phone initial_state["customer_phone"] = customer_phone
find_customer_tool = _TOOLS.find_customer_by_identifier
customer_result = await find_customer_tool.ainvoke(
{"identifier": customer_phone}
)
try:
customer_data = json.loads(customer_result)
if isinstance(customer_data, list):
customer_data = customer_data[0] if customer_data else {}
if customer_data and customer_data.get("id"):
initial_state["customer_name"] = customer_data.get("party.", {}).get("name", "Cliente Final")
initial_state["customer_id"] = customer_data.get("id", 0)
logger.info(
f"Cliente registrado encontrado: {initial_state["customer_name"]} (ID: {initial_state["customer_id"]})"
)
else:
logger.info(
f"Cliente no encontrado para el teléfono: {customer_phone}"
)
except (json.JSONDecodeError, AttributeError) as e:
logger.error(f"Error al parsear datos del cliente: {e}")
logger.info(f"Nueva conversación iniciada con cliente: {customer_phone}") logger.info(f"Nueva conversación iniciada con cliente: {customer_phone}")
agent_response = await agent.ainvoke(initial_state, config=config) agent_response = await agent.ainvoke(initial_state, config=config)