【PythonAI】4.1.2 国产AI助手API调用简介(DeepSeek为例)
代码定义了一个DeepSeekAssistant类,封装了调用DeepSeek API的三种对话模式(普通对话、多轮对话、流式输出),并通过示例展示了如何生成电商文案、进行上下文连贯的多轮对话以及实时逐字输出回复内容。
·
# deepseek_assistant.py
import requests
import json
class DeepSeekAssistant:
def __init__(self, api_key):
self.api_key = api_key
self.base_url = "https://api.deepseek.com" # DeepSeek API地址
self.headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
def chat(self, prompt, model="deepseek-chat", temperature=0.7, max_tokens=2000):
"""
发送对话请求
Args:
prompt: 用户输入的问题
model: 模型名称,可选 deepseek-chat 或 deepseek-reasoner
temperature: 温度参数,控制回复的随机性
max_tokens: 最大输出token数
Returns:
str: 模型回复的内容
"""
payload = {
"model": model, # deepseek-chat 对应 DeepSeek-V3.2
"messages": [
{"role": "system", "content": "你是DeepSeek,一个乐于助人的AI助手。"},
{"role": "user", "content": prompt}
],
"temperature": temperature,
"max_tokens": max_tokens,
"stream": False # 非流式输出
}
try:
response = requests.post(
f"{self.base_url}/chat/completions",
headers=self.headers,
json=payload,
timeout=60
)
response.raise_for_status() # 如果状态码不是200,抛出异常
# 解析返回结果
result = response.json()
return result['choices'][0]['message']['content']
except requests.exceptions.RequestException as e:
return f"网络请求失败: {str(e)}"
except KeyError as e:
return f"解析响应失败: {str(e)}"
except Exception as e:
return f"调用失败: {str(e)}"
def chat_with_history(self, messages, model="deepseek-chat", temperature=0.7):
"""
支持多轮对话的方法
Args:
messages: 消息列表,格式为 [{"role": "user", "content": "..."}, ...]
model: 模型名称
temperature: 温度参数
Returns:
str: 模型回复的内容
"""
payload = {
"model": model,
"messages": messages,
"temperature": temperature,
"stream": False
}
try:
response = requests.post(
f"{self.base_url}/chat/completions",
headers=self.headers,
json=payload,
timeout=60
)
response.raise_for_status()
return response.json()['choices'][0]['message']['content']
except Exception as e:
return f"调用失败: {str(e)}"
def stream_chat(self, prompt, model="deepseek-chat", temperature=0.7):
"""
流式输出方法(逐字显示)
Args:
prompt: 用户输入的问题
model: 模型名称
temperature: 温度参数
Yields:
str: 逐块返回的文本内容
"""
payload = {
"model": model,
"messages": [
{"role": "system", "content": "你是DeepSeek,一个乐于助人的AI助手。"},
{"role": "user", "content": prompt}
],
"temperature": temperature,
"stream": True # 开启流式输出
}
try:
response = requests.post(
f"{self.base_url}/chat/completions",
headers=self.headers,
json=payload,
stream=True,
timeout=60
)
for line in response.iter_lines():
if line:
line = line.decode('utf-8')
if line.startswith('data: '):
data = line[6:] # 去掉 "data: " 前缀
if data != '[DONE]':
try:
chunk = json.loads(data)
if 'choices' in chunk and len(chunk['choices']) > 0:
delta = chunk['choices'][0].get('delta', {})
if 'content' in delta:
yield delta['content']
except json.JSONDecodeError:
continue
except Exception as e:
yield f"调用失败: {str(e)}"
# 使用示例
if __name__ == "__main__":
# 替换为你的DeepSeek API密钥
api_key = "your-deepseek-api-key-here" # 在 https://platform.deepseek.com 获取
# 创建DeepSeek助手实例
deepseek = DeepSeekAssistant(api_key)
# 示例1:电商文案生成
prompt = """
请为新疆和田大枣写一段电商详情页文案,
突出"沙漠阳光孕育、昆仑雪水灌溉"的产地优势,
字数200字左右,语言要有感染力。
"""
print("=" * 50)
print("示例1:电商文案生成")
print("=" * 50)
result = deepseek.chat(prompt)
print(result)
# 示例2:多轮对话
print("\n" + "=" * 50)
print("示例2:多轮对话")
print("=" * 50)
conversation = [
{"role": "system", "content": "你是一个专业的电商文案助手。"},
{"role": "user", "content": "我想为新疆和田大枣写文案,它的特点是甜度高、营养丰富。"},
{"role": "assistant", "content": "好的,我了解了。新疆和田大枣以甜度高、营养丰富著称。您希望文案突出哪些方面呢?"},
{"role": "user", "content": "突出它的产地优势和健康价值"}
]
result2 = deepseek.chat_with_history(conversation)
print(result2)
# 示例3:流式输出(可选)
print("\n" + "=" * 50)
print("示例3:流式输出演示")
print("=" * 50)
print("DeepSeek: ", end="", flush=True)
for chunk in deepseek.stream_chat("请用一句话介绍新疆和田大枣"):
print(chunk, end="", flush=True)
print() # 换行
运行结果:
(uos_ai_env) Muhtar@UOS-Desktop:~/AI_Projects$ python3 deepseek_assistant.py
==================================================
示例1:电商文案生成
==================================================
# 昆仑雪水浇灌,沙漠阳光滋养
## 每一颗都是时光沉淀的甜蜜奇迹
生长在世界黄金水果带——新疆和田,这里拥有极致的自然馈赠:每年超过3000小时的沙漠阳光,让枣肉积累饱满糖分;纯净的昆仑雪水灌溉,赋予果实清润不腻的甘甜。
我们坚持自然挂枝成熟,手工精选每一颗枣。红润饱满的枣身,撕开可见金黄拉丝果肉,口感厚实绵密,枣香浓郁纯正。无论是直接食用、煮粥煲汤,还是作为养生茶点,都是天然健康的味觉享受。
✨ 源自核心产区,直达您手中
✨ 自然熟成,无添加加工
✨ 颗颗精选,锁住阳光味道
尝一口,便是辽阔新疆的甜蜜馈赠。
==================================================
示例2:多轮对话
==================================================
好的,没问题。新疆和田大枣的“甜”和“营养”是其核心,而“产地优势”和“健康价值”是让这两个核心点升华、更具说服力的关键。
为您精心构思了几个不同风格和用途的文案,您可以根据需要选择或组合使用:
---
### **方案一:大气磅礴 · 品牌故事型**
(适合品牌主页、详情页头部、宣传册)
**标题:来自“世界水果优生区”的甜蜜能量**
**文案:**
不是所有的红枣,都配称为“和田大枣”。
它生长于昆仑山与塔克拉玛干沙漠之间的绿洲——新疆和田。这里,每年超3000小时的日照,昼夜近20度的温差,以及纯净的雪水灌溉,共同缔造了红枣生长的“黄金纬度”。
极致的自然条件,催生出极致的果实:
* **甜度凝聚时光**:漫长的生长期让糖分充分积累,甜入心扉,是自然的浓缩蜜意。
* **营养源自天地**:充沛的光合作用,孕育出丰富的维生素、环磷酸腺苷及铁元素,是名副其实
更多推荐



所有评论(0)