首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >DeepSeek 智能生成:从模型能力到文章生成流水线的专业实践

DeepSeek 智能生成:从模型能力到文章生成流水线的专业实践

原创
作者头像
IT大佬 jzit-top
发布2026-09-18 14:06:38
发布2026-09-18 14:06:38
1010
举报

摘要

DeepSeek 系列模型以 MoE 架构、MLA 注意力、强化学习推理和 OpenAI 兼容 API 为核心特征,正在成为智能生成领域的重要基础设施。它不仅能完成通用对话、代码生成、文档写作,还能通过 deepseek-reasoner 处理复杂推理任务。本文从模型定位、API 接入、文章生成流水线、结构化输出、RAG、本地部署、评估、安全与反模式等维度,给出一套可落地的工程方法,并附带完整 Python 代码。

关键词:DeepSeek;智能生成;MoE;MLA;deepseek-chat;deepseek-reasoner;RAG;vLLM;内容安全


1. DeepSeek 的能力定位

DeepSeek 模型家族主要分为两类:

模型

定位

适用场景

deepseek-chat

通用对话与生成

写作、摘要、翻译、代码、函数调用

deepseek-reasoner

深度推理

数学、逻辑、复杂分析、链式思考

deepseek-chat 适合大多数智能生成任务;deepseek-reasoner 在需要多步推理、证明、复杂规划时更有优势,但延迟与成本通常更高。API 兼容 OpenAI SDK,迁移成本低。

核心工程原则:

  1. 通用生成优先 deepseek-chat
  2. 复杂推理再切 deepseek-reasoner
  3. 结构化输出必须校验;
  4. 长文生成采用“大纲 → 分节 → 汇总”;
  5. 所有事实性内容需人工或检索验证。

2. API 接入:OpenAI 兼容

2.1 安装与配置

代码语言:javascript
复制
pip install openai
export DEEPSEEK_API_KEY="sk-..."

代码语言:javascript
复制
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["DEEPSEEK_API_KEY"],
    base_url="https://api.deepseek.com",
)

2.2 基础对话

代码语言:javascript
复制
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)

2.3 流式输出

代码语言:javascript
复制
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)

2.4 推理模型

代码语言:javascript
复制
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,具体以官方文档为准。生产系统应做能力探测与降级。


3. 文章生成流水线

直接让模型生成 5000 字长文,容易出现结构松散、重复、前后矛盾。专业做法是拆成流水线:

代码语言:javascript
复制
主题 → 大纲 → 分节生成 → 合并 → 润色 → 事实核查 → 导出

3.1 生成结构化大纲

代码语言:javascript
复制
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)

3.2 分节生成

代码语言:javascript
复制
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.content

3.3 合并与润色

代码语言:javascript
复制
def 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])

3.4 长文分块与续写

当超过 max_tokens 时,采用滑动窗口续写:

代码语言:javascript
复制
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 text

4. 结构化输出与函数调用

4.1 JSON 输出

deepseek-chat 支持 response_format={"type": "json_object"},适合抽取、分类、摘要。

代码语言:javascript
复制
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)

4.2 Function Calling

代码语言:javascript
复制
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 或文件删除。


5. RAG 增强生成

DeepSeek 本身不更新知识,事实性内容应通过 RAG 提供。

代码语言:javascript
复制
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 是什么?"))

6. 本地部署与私有化

DeepSeek 完整模型参数量大,本地部署通常选择蒸馏版或量化版。

代码语言:javascript
复制
# 使用 vLLM 启动 OpenAI 兼容服务
vllm serve deepseek-ai/DeepSeek-R1-Distill-Qwen-7B \
  --port 8000 \
  --dtype bfloat16 \
  --max-model-len 8192

代码语言:javascript
复制
local_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)

本地部署要点:

  • 显存估算:参数量 × 精度字节 + KV Cache;
  • 量化:GPTQ、AWQ、GGUF、bitsandbytes;
  • 推理优化:PagedAttention、Continuous Batching、Prefix Caching;
  • 多卡:Tensor Parallel、Pipeline Parallel;
  • 安全:内网隔离、权限控制、审计日志。

7. 评估、成本与可观测性

7.1 评估指标

  • 相关性:是否回应主题;
  • 事实性:是否有依据;
  • 结构:章节是否清晰;
  • 可读性:语言是否流畅;
  • 代码正确性:能否运行;
  • 安全:是否包含违规内容。

代码语言:javascript
复制
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)

7.2 成本与延迟

  • 记录 prompt_tokens、completion_tokens;
  • 缓存系统提示与大纲;
  • 简单任务用 deepseek-chat,复杂任务用 deepseek-reasoner
  • 流式输出提升感知速度;
  • 限制 max_tokens,避免失控。

代码语言:javascript
复制
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 resp

8. 安全与合规

DeepSeek 智能生成的内容必须经过审核:

  • 输入输出内容安全检测;
  • 事实核查与引用溯源;
  • 版权与肖像权检查;
  • 敏感信息脱敏;
  • 提示注入防护;
  • 工具调用权限控制;
  • 审计日志与可追溯;
  • 遵守平台与行业规范。

代码语言:javascript
复制
def guard_output(text: str) -> bool:
    banned = ["违法", "暴力", "仇恨", "隐私泄露"]
    return not any(word in text for word in banned)

9. 常见反模式

  • 直接让模型生成万字长文,不做大纲;
  • 不校验 JSON,直接 json.loads
  • 用模型记忆替代 RAG;
  • 不记录 token 与成本;
  • 不审核就发布;
  • deepseek-reasoner 用于所有任务,导致成本过高;
  • 让模型直接执行危险工具;
  • 不做版本管理与回滚;
  • 忽略版权与事实核查。

10. 结论

DeepSeek 智能生成的核心不是“一句话调用”,而是以模型为推理与生成引擎,构建“大纲 → 分节 → 合并 → 润色 → 核查 → 导出”的工程流水线。deepseek-chat 负责通用生成与结构化输出,deepseek-reasoner 负责复杂推理;RAG 提供事实,函数调用连接工具,vLLM 支持私有化,评估与可观测性保障质量,安全护栏控制风险。真正可用的智能生成系统,是在质量、延迟、成本与合规之间持续权衡的结果。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

目录
  • 摘要
    • 1. DeepSeek 的能力定位
    • 2. API 接入:OpenAI 兼容
      • 2.1 安装与配置
      • 2.2 基础对话
      • 2.3 流式输出
      • 2.4 推理模型
    • 3. 文章生成流水线
      • 3.1 生成结构化大纲
      • 3.2 分节生成
      • 3.3 合并与润色
      • 3.4 长文分块与续写
    • 4. 结构化输出与函数调用
      • 4.1 JSON 输出
      • 4.2 Function Calling
    • 5. RAG 增强生成
    • 6. 本地部署与私有化
    • 7. 评估、成本与可观测性
      • 7.1 评估指标
      • 7.2 成本与延迟
    • 8. 安全与合规
    • 9. 常见反模式
    • 10. 结论
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档