operations_project/apps/common/services/ai_service.py
2025-05-13 18:36:06 +08:00

202 lines
6.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import requests
import logging
import json
from django.conf import settings
from datetime import datetime
logger = logging.getLogger(__name__)
class AIService:
"""
通用AI服务类提供对不同AI模型的统一调用接口
"""
@staticmethod
def call_silicon_cloud_api(messages, model="deepseek-ai/DeepSeek-V3", max_tokens=512, temperature=0.7):
"""
调用SiliconCloud API
Args:
messages: 消息列表,格式为[{"role": "user", "content": "..."}, ...]
model: 使用的模型名称默认为DeepSeek-V3
max_tokens: 最大生成token数
temperature: 温度参数,控制创造性
Returns:
tuple: (生成内容, 错误信息)
"""
try:
# 获取API密钥
api_key = getattr(settings, 'SILICON_CLOUD_API_KEY', '')
if not api_key:
return None, "未配置Silicon Cloud API密钥"
url = "https://api.siliconflow.cn/v1/chat/completions"
payload = {
"model": model,
"stream": False,
"max_tokens": max_tokens,
"temperature": temperature,
"top_p": 0.7,
"top_k": 50,
"frequency_penalty": 0.5,
"n": 1,
"stop": [],
"messages": messages
}
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
# 设置代理(如果配置了)
proxies = None
proxy_url = getattr(settings, 'PROXY_URL', None)
if proxy_url:
proxies = {
"http": proxy_url,
"https": proxy_url
}
# 发送请求
logger.info(f"正在调用SiliconCloud API模型: {model}")
response = requests.post(url, json=payload, headers=headers, proxies=proxies)
if response.status_code != 200:
logger.error(f"API请求失败状态码: {response.status_code},响应: {response.text}")
return None, f"API请求失败状态码: {response.status_code}"
result = response.json()
# 从API响应中提取内容
if 'choices' in result and result['choices']:
content = result['choices'][0]['message']['content'].strip()
return content, None
else:
logger.error(f"API响应格式错误: {result}")
return None, "API响应格式错误无法提取内容"
except requests.exceptions.RequestException as e:
logger.error(f"API请求异常: {str(e)}")
return None, f"API请求异常: {str(e)}"
except Exception as e:
logger.error(f"调用AI服务失败: {str(e)}")
return None, f"调用AI服务失败: {str(e)}"
@staticmethod
def generate_email_reply(goal_description, conversation_summary, last_message):
"""
生成邮件回复话术
Args:
goal_description: 用户目标描述
conversation_summary: 对话摘要
last_message: 达人最后发送的消息内容
Returns:
tuple: (推荐话术内容, 错误信息)
"""
try:
# 验证必要参数
if not goal_description or not last_message:
return None, "缺少必要参数:目标描述或最后消息"
# 准备提示信息
prompt = f"""
请为用户提供一条回复达人邮件的推荐话术,帮助用户实现销售目标。
用户目标:{goal_description}
对话摘要:{conversation_summary or '无对话摘要'}
达人最后发送的消息:
{last_message}
要求:
1. 回复应当专业礼貌,并围绕用户目标展开
2. 提供有说服力的话术,推动促成合作
3. 不超过200字
4. 直接给出回复内容,不要包含任何额外解释
"""
messages = [
{
"role": "system",
"content": "你是一名专业的邮件回复助手,你的任务是生成有效的销售话术,帮助用户实现销售目标。"
},
{
"role": "user",
"content": prompt
}
]
# 调用通用API方法
return AIService.call_silicon_cloud_api(
messages,
model="Pro/deepseek-ai/DeepSeek-R1",
max_tokens=512,
temperature=0.7
)
except Exception as e:
logger.error(f"生成回复话术失败: {str(e)}")
return None, f"生成回复话术失败: {str(e)}"
@staticmethod
def generate_conversation_summary(conversation_history):
"""
生成对话摘要
Args:
conversation_history: 对话历史记录列表
Returns:
tuple: (摘要内容, 错误信息)
"""
try:
if not conversation_history:
return None, "无对话历史,无法生成摘要"
# 构造对话历史文本
conversation_text = "\n\n".join([
f"**{'用户' if msg.get('is_from_user', False) else '达人'}**: {msg.get('content', '')}"
for msg in conversation_history
])
# 准备提示信息
prompt = f"""
请对以下用户与达人之间的对话内容进行总结:
{conversation_text}
要求:
1. 总结应包含双方主要讨论的话题和关键点
2. 特别关注产品详情、价格谈判、合作意向等商务要点
3. 简明扼要不超过200字
4. 直接给出总结内容,不要包含任何额外解释
"""
messages = [
{
"role": "system",
"content": "你是一名专业的对话总结助手,擅长提取商务沟通中的关键信息。"
},
{
"role": "user",
"content": prompt
}
]
# 调用通用API方法
return AIService.call_silicon_cloud_api(
messages,
model="Pro/deepseek-ai/DeepSeek-R1",
max_tokens=512,
temperature=0.5
)
except Exception as e:
logger.error(f"生成对话摘要失败: {str(e)}")
return None, f"生成对话摘要失败: {str(e)}"