2026-01-14 19:25:22 +08:00
|
|
|
"""
|
|
|
|
|
ZhipuAI LLM Client for B2B Shopping AI Assistant
|
|
|
|
|
"""
|
2026-01-16 18:36:17 +08:00
|
|
|
import concurrent.futures
|
|
|
|
|
from typing import Any, Optional
|
2026-01-14 19:25:22 +08:00
|
|
|
from dataclasses import dataclass
|
|
|
|
|
|
|
|
|
|
from zhipuai import ZhipuAI
|
|
|
|
|
|
|
|
|
|
from config import settings
|
|
|
|
|
from utils.logger import get_logger
|
|
|
|
|
|
|
|
|
|
logger = get_logger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
|
class Message:
|
|
|
|
|
"""Chat message structure"""
|
|
|
|
|
role: str # "system", "user", "assistant"
|
|
|
|
|
content: str
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
|
class LLMResponse:
|
|
|
|
|
"""LLM response structure"""
|
|
|
|
|
content: str
|
|
|
|
|
finish_reason: str
|
|
|
|
|
usage: dict[str, int]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class ZhipuLLMClient:
|
|
|
|
|
"""ZhipuAI LLM Client wrapper"""
|
2026-01-16 18:36:17 +08:00
|
|
|
|
|
|
|
|
DEFAULT_TIMEOUT = 30 # seconds
|
|
|
|
|
|
2026-01-14 19:25:22 +08:00
|
|
|
def __init__(
|
|
|
|
|
self,
|
|
|
|
|
api_key: Optional[str] = None,
|
2026-01-16 18:36:17 +08:00
|
|
|
model: Optional[str] = None,
|
|
|
|
|
timeout: Optional[int] = None
|
2026-01-14 19:25:22 +08:00
|
|
|
):
|
|
|
|
|
self.api_key = api_key or settings.zhipu_api_key
|
|
|
|
|
self.model = model or settings.zhipu_model
|
2026-01-16 18:36:17 +08:00
|
|
|
self.timeout = timeout or self.DEFAULT_TIMEOUT
|
2026-01-14 19:25:22 +08:00
|
|
|
self._client = ZhipuAI(api_key=self.api_key)
|
2026-01-16 18:36:17 +08:00
|
|
|
logger.info("ZhipuAI client initialized", model=self.model, timeout=self.timeout)
|
|
|
|
|
|
2026-01-14 19:25:22 +08:00
|
|
|
async def chat(
|
|
|
|
|
self,
|
|
|
|
|
messages: list[Message],
|
|
|
|
|
temperature: float = 0.7,
|
|
|
|
|
max_tokens: int = 2048,
|
|
|
|
|
top_p: float = 0.9,
|
|
|
|
|
**kwargs: Any
|
|
|
|
|
) -> LLMResponse:
|
2026-01-16 18:36:17 +08:00
|
|
|
"""Send chat completion request"""
|
2026-01-14 19:25:22 +08:00
|
|
|
formatted_messages = [
|
|
|
|
|
{"role": msg.role, "content": msg.content}
|
|
|
|
|
for msg in messages
|
|
|
|
|
]
|
2026-01-16 18:36:17 +08:00
|
|
|
|
|
|
|
|
logger.info(
|
2026-01-14 19:25:22 +08:00
|
|
|
"Sending chat request",
|
|
|
|
|
model=self.model,
|
|
|
|
|
message_count=len(messages),
|
|
|
|
|
temperature=temperature
|
|
|
|
|
)
|
2026-01-16 18:36:17 +08:00
|
|
|
|
|
|
|
|
def _make_request():
|
|
|
|
|
return self._client.chat.completions.create(
|
2026-01-14 19:25:22 +08:00
|
|
|
model=self.model,
|
|
|
|
|
messages=formatted_messages,
|
|
|
|
|
temperature=temperature,
|
|
|
|
|
max_tokens=max_tokens,
|
|
|
|
|
top_p=top_p,
|
|
|
|
|
**kwargs
|
|
|
|
|
)
|
2026-01-16 18:36:17 +08:00
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
|
|
|
|
|
future = executor.submit(_make_request)
|
|
|
|
|
response = future.result(timeout=self.timeout)
|
|
|
|
|
|
2026-01-14 19:25:22 +08:00
|
|
|
choice = response.choices[0]
|
2026-01-16 18:36:17 +08:00
|
|
|
content = choice.message.content
|
|
|
|
|
|
|
|
|
|
logger.info(
|
|
|
|
|
"Chat response received",
|
|
|
|
|
finish_reason=choice.finish_reason,
|
|
|
|
|
content_length=len(content) if content else 0,
|
|
|
|
|
usage=response.usage.__dict__ if hasattr(response, 'usage') else {}
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
if not content:
|
|
|
|
|
logger.warning("LLM returned empty content")
|
|
|
|
|
|
|
|
|
|
return LLMResponse(
|
|
|
|
|
content=content or "",
|
2026-01-14 19:25:22 +08:00
|
|
|
finish_reason=choice.finish_reason,
|
|
|
|
|
usage={
|
|
|
|
|
"prompt_tokens": response.usage.prompt_tokens,
|
|
|
|
|
"completion_tokens": response.usage.completion_tokens,
|
|
|
|
|
"total_tokens": response.usage.total_tokens
|
|
|
|
|
}
|
|
|
|
|
)
|
2026-01-16 18:36:17 +08:00
|
|
|
|
|
|
|
|
except concurrent.futures.TimeoutError:
|
|
|
|
|
logger.error("Chat request timed out", timeout=self.timeout)
|
|
|
|
|
raise TimeoutError(f"Request timed out after {self.timeout} seconds")
|
|
|
|
|
|
2026-01-14 19:25:22 +08:00
|
|
|
except Exception as e:
|
|
|
|
|
logger.error("Chat request failed", error=str(e))
|
|
|
|
|
raise
|
2026-01-16 18:36:17 +08:00
|
|
|
|
2026-01-14 19:25:22 +08:00
|
|
|
async def chat_with_tools(
|
|
|
|
|
self,
|
|
|
|
|
messages: list[Message],
|
|
|
|
|
tools: list[dict[str, Any]],
|
|
|
|
|
temperature: float = 0.7,
|
|
|
|
|
**kwargs: Any
|
2026-01-16 18:36:17 +08:00
|
|
|
) -> tuple[LLMResponse, None]:
|
|
|
|
|
"""Send chat completion request with tool calling"""
|
2026-01-14 19:25:22 +08:00
|
|
|
formatted_messages = [
|
|
|
|
|
{"role": msg.role, "content": msg.content}
|
|
|
|
|
for msg in messages
|
|
|
|
|
]
|
2026-01-16 18:36:17 +08:00
|
|
|
|
|
|
|
|
logger.info(
|
2026-01-14 19:25:22 +08:00
|
|
|
"Sending chat request with tools",
|
|
|
|
|
model=self.model,
|
|
|
|
|
tool_count=len(tools)
|
|
|
|
|
)
|
2026-01-16 18:36:17 +08:00
|
|
|
|
2026-01-14 19:25:22 +08:00
|
|
|
try:
|
|
|
|
|
response = self._client.chat.completions.create(
|
|
|
|
|
model=self.model,
|
|
|
|
|
messages=formatted_messages,
|
|
|
|
|
tools=tools,
|
|
|
|
|
temperature=temperature,
|
|
|
|
|
**kwargs
|
|
|
|
|
)
|
2026-01-16 18:36:17 +08:00
|
|
|
|
2026-01-14 19:25:22 +08:00
|
|
|
choice = response.choices[0]
|
2026-01-16 18:36:17 +08:00
|
|
|
content = choice.message.content or ""
|
|
|
|
|
|
|
|
|
|
return LLMResponse(
|
|
|
|
|
content=content,
|
2026-01-14 19:25:22 +08:00
|
|
|
finish_reason=choice.finish_reason,
|
|
|
|
|
usage={
|
|
|
|
|
"prompt_tokens": response.usage.prompt_tokens,
|
|
|
|
|
"completion_tokens": response.usage.completion_tokens,
|
|
|
|
|
"total_tokens": response.usage.total_tokens
|
|
|
|
|
}
|
2026-01-16 18:36:17 +08:00
|
|
|
), None
|
|
|
|
|
|
2026-01-14 19:25:22 +08:00
|
|
|
except Exception as e:
|
|
|
|
|
logger.error("Chat with tools request failed", error=str(e))
|
|
|
|
|
raise
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
llm_client: Optional[ZhipuLLMClient] = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_llm_client() -> ZhipuLLMClient:
|
|
|
|
|
"""Get or create global LLM client instance"""
|
|
|
|
|
global llm_client
|
|
|
|
|
if llm_client is None:
|
|
|
|
|
llm_client = ZhipuLLMClient()
|
|
|
|
|
return llm_client
|