Commit 37643d07 authored by Vũ Hoàng Anh's avatar Vũ Hoàng Anh

fix: resolve empty product_ids, fix sql bug, handle decimal json error & add check_is_stock tool

parent 1090ad4e
......@@ -17,7 +17,7 @@ from config import DEFAULT_MODEL, REDIS_CACHE_TURN_ON
from langfuse import propagate_attributes
from .graph import build_graph
from .helper import extract_product_ids, handle_post_chat_async, parse_ai_response
from .helper import extract_product_ids, handle_post_chat_async, parse_ai_response_async
from .models import AgentState, get_config
logger = logging.getLogger(__name__)
......@@ -44,6 +44,7 @@ async def chat_controller(
"""
effective_identity_key = identity_key or user_id
logger.info(
"chat_controller start: model=%s, user_id=%s, identity_key=%s",
model_name, user_id, effective_identity_key
......@@ -129,10 +130,13 @@ async def chat_controller(
result = await graph.ainvoke(initial_state, config=exec_config)
# Parse Response
all_product_ids = extract_product_ids(result.get("messages", []))
final_messages = result.get("messages", [])
# Combine history + current messages to find ALL products mentioned in conversation
full_conversation = messages + final_messages
all_product_ids = extract_product_ids(full_conversation)
ai_raw_content = result.get("ai_response").content if result.get("ai_response") else ""
# Unpack 3 values now
ai_text_response, final_product_ids, new_insight = parse_ai_response(ai_raw_content, all_product_ids)
ai_text_response, final_product_ids, new_insight = await parse_ai_response_async(ai_raw_content, all_product_ids)
# Save new insight to Redis if available
if new_insight and effective_identity_key:
......
This diff is collapsed.
import logging
import httpx
from langchain_core.tools import tool
from pydantic import BaseModel, Field
logger = logging.getLogger(__name__)
class StockCheckInput(BaseModel):
skus: str = Field(
description="Danh sách mã SKU sản phẩm cần kiểm tra tồn kho, phân cách bằng dấu phẩy. Ví dụ: '6ST25W005-SE091-L,6ST25W005-SE091-M'"
)
@tool("check_is_stock", args_schema=StockCheckInput)
async def check_is_stock(skus: str) -> str:
"""
Kiểm tra tình trạng tồn kho của các mã sản phẩm (SKU) thực tế từ hệ thống Canifa.
Sử dụng tool này khi người dùng hỏi về tình trạng còn hàng, hết hàng của sản phẩm cụ thể.
Input nhận vào là chuỗi các SKU phân cách bởi dấu phẩy.
"""
logger.info(f"🔍 [Stock Check] Checking stock for SKUs: {skus}")
url = "https://canifa.com/v1/middleware/stock_get_stock_list"
params = {"skus": skus}
try:
async with httpx.AsyncClient() as client:
response = await client.get(url, params=params, timeout=10.0)
response.raise_for_status()
data = response.json()
logger.info(f"✅ Stock Check response: {str(data)[:200]}...")
# Trả về raw JSON để LLM tự xử lý thông tin
return str(data)
except httpx.RequestError as e:
logger.error(f"❌ Network error checking stock: {e}")
return f"Lỗi kết nối khi kiểm tra tồn kho: {str(e)}"
except httpx.HTTPStatusError as e:
logger.error(f"❌ HTTP error {e.response.status_code}: {e}")
return f"Lỗi server khi kiểm tra tồn kho (Status {e.response.status_code})"
except Exception as e:
logger.error(f"❌ Unexpected error in check_is_stock: {e}")
return f"Lỗi không xác định khi kiểm tra tồn kho: {str(e)}"
......@@ -9,11 +9,12 @@ from .brand_knowledge_tool import canifa_knowledge_search
from .customer_info_tool import collect_customer_info
from .data_retrieval_tool import data_retrieval_tool
from .promotion_canifa_tool import canifa_get_promotions
from .check_is_stock import check_is_stock
def get_retrieval_tools() -> list[Tool]:
"""Các tool chỉ dùng để đọc/truy vấn dữ liệu (Có thể cache)"""
return [data_retrieval_tool, canifa_knowledge_search, canifa_get_promotions]
return [data_retrieval_tool, canifa_knowledge_search, canifa_get_promotions, check_is_stock]
def get_collection_tools() -> list[Tool]:
......
......@@ -99,6 +99,7 @@ async def build_starrocks_query(params, query_vector: list[float] | None = None)
product_line_en,
1.0 as max_score
FROM shared_source.magento_product_dimension_with_text_embedding
WHERE internal_ref_code = %s OR magento_ref_code = %s
"""
return sql, [magento_code, magento_code]
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment