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:
@@ -7,3 +7,5 @@ class MessagesState(TypedDict):
|
||||
messages: Annotated[list[AnyMessage], add_messages]
|
||||
llm_calls: int
|
||||
customer_phone: str
|
||||
customer_name: str
|
||||
customer_id: int
|
||||
|
||||
@@ -49,6 +49,8 @@ prompts:
|
||||
- get_current_datetime: Consultar fecha y hora actual para tomar desciciones.
|
||||
- schedule_appointment: Agendar y confirmar cita.
|
||||
- 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>
|
||||
"""
|
||||
|
||||
@@ -27,6 +27,7 @@ class NaliiaTools:
|
||||
self.schedule_appointment,
|
||||
self.find_service_centers,
|
||||
self.find_products_and_services,
|
||||
self.find_customer_by_identifier,
|
||||
]
|
||||
|
||||
@tool
|
||||
@@ -72,6 +73,32 @@ class NaliiaTools:
|
||||
|
||||
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
|
||||
def find_service_centers():
|
||||
"""
|
||||
|
||||
@@ -3,12 +3,15 @@ from langchain.messages import HumanMessage
|
||||
from ...dependencies import get_agent
|
||||
from ....logger import logger
|
||||
from ....schemes.chat_schemes import SendMessageScheme
|
||||
from naliiabot.bot.tools.naliia_tools import NaliiaTools
|
||||
import httpx
|
||||
import json
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
_TOOLS = NaliiaTools()
|
||||
|
||||
|
||||
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)],
|
||||
"llm_calls": 0,
|
||||
"customer_phone": "",
|
||||
"customer_name": "",
|
||||
"customer_id": 0,
|
||||
}
|
||||
|
||||
existing_state = await agent.checkpointer.aget(config)
|
||||
if existing_state is None:
|
||||
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}")
|
||||
|
||||
agent_response = await agent.ainvoke(initial_state, config=config)
|
||||
|
||||
Reference in New Issue
Block a user