DeepSeek 系列模型以 MoE 架构、MLA 注意力、强化学习推理和 OpenAI 兼容 API 为核心特征,正在成为智能生成领域的重要基础设施。它不仅能完成通用对话、代码生成、文档写作,还能通过 deepseek-reasoner 处理复杂推理任务。本文从模型定位、API 接入、文章生成流水线、结构化输出、RAG、本地部署、评估、安全与反模式等维度,给出一套可落地的工程方法,并附带完整 Python 代码。
关键词:DeepSeek;智能生成;MoE;MLA;deepseek-chat;deepseek-reasoner;RAG;vLLM;内容安全
DeepSeek 模型家族主要分为两类:
模型 | 定位 | 适用场景 |
|---|---|---|
deepseek-chat | 通用对话与生成 | 写作、摘要、翻译、代码、函数调用 |
deepseek-reasoner | 深度推理 | 数学、逻辑、复杂分析、链式思考 |
deepseek-chat 适合大多数智能生成任务;deepseek-reasoner 在需要多步推理、证明、复杂规划时更有优势,但延迟与成本通常更高。API 兼容 OpenAI SDK,迁移成本低。
核心工程原则:
deepseek-chat;deepseek-reasoner;pip install openai
export DEEPSEEK_API_KEY="sk-..."import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["DEEPSEEK_API_KEY"],
base_url="https://api.deepseek.com",
)resp = client.chat.completions.create(
model="deepseek-chat",
messages=[
{"role": "system", "content": "你是一位严谨的中文技术作者。"},
{"role": "user", "content": "用一句话解释什么是 MoE 架构。"},
],
temperature=0.3,
max_tokens=256,
)
print(resp.choices[0].message.content)def stream_chat(prompt: str):
stream = client.chat.completions.create(
model="deepseek-chat",
messages=[{"role": "user", "content": prompt}],
stream=True,
temperature=0.6,
)
for chunk in stream:
delta = chunk.choices[0].delta.content
if delta:
yield delta
for token in stream_chat("写一段关于 DeepSeek 的技术简介。"):
print(token, end="", flush=True)resp = client.chat.completions.create(
model="deepseek-reasoner",
messages=[{"role": "user", "content": "证明:若 n 为偶数,则 n^2 为偶数。"}],
)
msg = resp.choices[0].message
reasoning = getattr(msg, "reasoning_content", "")
print("推理过程:", reasoning)
print("最终答案:", msg.content)工程建议:deepseek-reasoner 可能不支持 Function Calling 或 JSON Output,具体以官方文档为准。生产系统应做能力探测与降级。
直接让模型生成 5000 字长文,容易出现结构松散、重复、前后矛盾。专业做法是拆成流水线:
主题 → 大纲 → 分节生成 → 合并 → 润色 → 事实核查 → 导出import json
def generate_outline(topic: str, sections: int = 6) -> dict:
resp = client.chat.completions.create(
model="deepseek-chat",
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": "你只输出 JSON,不要输出解释。"},
{
"role": "user",
"content": (
f"为主题《{topic}》生成文章大纲,包含 {sections} 个章节。"
"JSON 格式:"
'{"title":"...","summary":"...","keywords":["..."],'
'"sections":[{"heading":"...","points":["...","..."]}]}'
),
},
],
temperature=0.3,
)
return json.loads(resp.choices[0].message.content)def generate_section(topic: str, heading: str, points: list[str], style: str = "专业") -> str:
point_text = "\n".join(f"- {p}" for p in points)
resp = client.chat.completions.create(
model="deepseek-chat",
messages=[
{
"role": "system",
"content": (
f"你是一位资深技术作者,写作风格:{style}。"
"要求结构清晰、有代码示例(如适用)、不编造事实。"
),
},
{
"role": "user",
"content": (
f"文章主题:{topic}\n"
f"当前章节:{heading}\n"
f"要点:\n{point_text}\n"
"请输出该章节的 Markdown 内容,约 500-800 字。"
),
},
],
temperature=0.5,
max_tokens=2048,
)
return resp.choices[0].message.contentdef generate_article(topic: str, sections: int = 6, style: str = "专业") -> str:
outline = generate_outline(topic, sections)
parts = [
f"# {outline['title']}\n",
f"> 摘要:{outline.get('summary', '')}\n",
f"**关键词**:{'、'.join(outline.get('keywords', []))}\n",
]
for sec in outline["sections"]:
heading = sec["heading"]
points = sec.get("points", [])
content = generate_section(topic, heading, points, style)
parts.append(f"\n## {heading}\n\n{content}\n")
draft = "\n".join(parts)
final = client.chat.completions.create(
model="deepseek-chat",
messages=[
{"role": "system", "content": "你是资深编辑,负责润色与统一风格。"},
{
"role": "user",
"content": (
"请对以下文章进行润色,保持 Markdown 结构,"
"消除重复、修正语病、统一术语,不改变事实。\n\n" + draft
),
},
],
temperature=0.3,
max_tokens=8192,
)
return final.choices[0].message.content
article = generate_article("DeepSeek 智能生成", sections=6)
with open("deepseek_article.md", "w", encoding="utf-8") as f:
f.write(article)
print(article[:500])当超过 max_tokens 时,采用滑动窗口续写:
def continue_writing(prefix: str, instruction: str, max_rounds: int = 3) -> str:
text = prefix
for _ in range(max_rounds):
tail = text[-2000:]
resp = client.chat.completions.create(
model="deepseek-chat",
messages=[
{"role": "system", "content": "你负责续写文章,保持风格与结构一致。"},
{
"role": "user",
"content": f"已有内容结尾:\n{tail}\n\n续写要求:{instruction}",
},
],
temperature=0.5,
max_tokens=2048,
)
addition = resp.choices[0].message.content
if not addition:
break
text += "\n" + addition
return textdeepseek-chat 支持 response_format={"type": "json_object"},适合抽取、分类、摘要。
def extract_metadata(article: str) -> dict:
resp = client.chat.completions.create(
model="deepseek-chat",
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": "只输出 JSON。"},
{
"role": "user",
"content": (
"从文章中抽取:标题、摘要、关键词、目标读者、难度。"
'JSON 格式:{"title":"","summary":"","keywords":[],"audience":"","level":""}\n\n'
+ article[:4000]
),
},
],
temperature=0,
)
return json.loads(resp.choices[0].message.content)tools = [{
"type": "function",
"function": {
"name": "save_markdown",
"description": "将 Markdown 内容保存到文件",
"parameters": {
"type": "object",
"properties": {
"filename": {"type": "string"},
"content": {"type": "string"},
},
"required": ["filename", "content"],
},
},
}]
resp = client.chat.completions.create(
model="deepseek-chat",
messages=[{"role": "user", "content": "把刚才的文章保存为 deepseek.md"}],
tools=tools,
tool_choice="auto",
)生产环境必须对工具参数做白名单和路径校验,禁止模型直接执行 Shell、SQL 或文件删除。
DeepSeek 本身不更新知识,事实性内容应通过 RAG 提供。
import numpy as np
def embed(texts: list[str]) -> np.ndarray:
# 可使用 DeepSeek 兼容的 embedding 服务,或本地 embedding 模型
resp = client.embeddings.create(
model="text-embedding-3-small",
input=texts,
)
return np.array([d.embedding for d in resp.data], dtype=np.float32)
class VectorStore:
def __init__(self):
self.docs: list[str] = []
self.mat: np.ndarray | None = None
def add(self, docs: list[str]):
self.docs.extend(docs)
vecs = embed(docs)
self.mat = vecs if self.mat is None else np.vstack([self.mat, vecs])
def search(self, query: str, top_k: int = 3) -> list[str]:
q = embed([query])[0]
sims = self.mat @ q / (
np.linalg.norm(self.mat, axis=1) * np.linalg.norm(q) + 1e-8
)
idx = np.argsort(-sims)[:top_k]
return [self.docs[i] for i in idx]
store = VectorStore()
store.add([
"DeepSeek-V3 采用 MoE 架构,总参数量大,但每 token 激活参数较少。",
"DeepSeek-R1 通过强化学习提升推理能力,适合数学与逻辑任务。",
"DeepSeek API 兼容 OpenAI SDK,base_url 为 https://api.deepseek.com。",
])
def rag_answer(question: str) -> str:
context = "\n".join(store.search(question))
resp = client.chat.completions.create(
model="deepseek-chat",
messages=[
{"role": "system", "content": "只基于给定资料回答,不知道就说不知道。"},
{"role": "user", "content": f"资料:\n{context}\n\n问题:{question}"},
],
temperature=0.2,
)
return resp.choices[0].message.content
print(rag_answer("DeepSeek API 的 base_url 是什么?"))DeepSeek 完整模型参数量大,本地部署通常选择蒸馏版或量化版。
# 使用 vLLM 启动 OpenAI 兼容服务
vllm serve deepseek-ai/DeepSeek-R1-Distill-Qwen-7B \
--port 8000 \
--dtype bfloat16 \
--max-model-len 8192local_client = OpenAI(
api_key="EMPTY",
base_url="http://localhost:8000/v1",
)
resp = local_client.chat.completions.create(
model="deepseek-ai/DeepSeek-R1-Distill-Qwen-7B",
messages=[{"role": "user", "content": "解释一下 MLA 注意力。"}],
temperature=0.3,
)
print(resp.choices[0].message.content)本地部署要点:
def evaluate_article(article: str, topic: str) -> dict:
resp = client.chat.completions.create(
model="deepseek-chat",
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": "你是严格的技术评审,只输出 JSON。"},
{
"role": "user",
"content": (
f"评估文章《{topic}》。"
'输出 {"relevance":0-10,"factuality":0-10,'
'"structure":0-10,"readability":0-10,"safety":0-10,"comments":"..."}'
f"\n\n文章:\n{article[:6000]}"
),
},
],
temperature=0,
)
return json.loads(resp.choices[0].message.content)deepseek-chat,复杂任务用 deepseek-reasoner;import time
def traced_chat(messages, **kwargs):
start = time.time()
resp = client.chat.completions.create(messages=messages, **kwargs)
usage = resp.usage
print({
"model": kwargs.get("model"),
"prompt_tokens": usage.prompt_tokens,
"completion_tokens": usage.completion_tokens,
"latency_ms": int((time.time() - start) * 1000),
})
return respDeepSeek 智能生成的内容必须经过审核:
def guard_output(text: str) -> bool:
banned = ["违法", "暴力", "仇恨", "隐私泄露"]
return not any(word in text for word in banned)json.loads;deepseek-reasoner 用于所有任务,导致成本过高;DeepSeek 智能生成的核心不是“一句话调用”,而是以模型为推理与生成引擎,构建“大纲 → 分节 → 合并 → 润色 → 核查 → 导出”的工程流水线。deepseek-chat 负责通用生成与结构化输出,deepseek-reasoner 负责复杂推理;RAG 提供事实,函数调用连接工具,vLLM 支持私有化,评估与可观测性保障质量,安全护栏控制风险。真正可用的智能生成系统,是在质量、延迟、成本与合规之间持续权衡的结果。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。