跳到正文

科技·工程

经典Python调用DeepSeek v4 Flash代码

WxjzKK约 22 分钟
原文
文章信息与版本

文章信息

发布
2026年10月21日
收录
2026年10月22日
更新
2026年11月16日
篇幅
约 22 分钟

版本

  1. v1当前
Python
      
"""
DeepSeek API 教程版案例:在终端里和大模型连续对话

这个案例演示:
    1. 什么是 API Key。
    2. 如何把用户输入包装成 messages。
    3. 如何通过 HTTP 请求调用 DeepSeek 大模型。
    4. 如何在终端里做连续多轮对话。
    5. 如何处理常见错误,例如 API Key 错误、网络失败、余额不足、请求过快。

本文件只使用 Python 标准库,不需要安装 openai、requests 等第三方库。
只要电脑已经安装 Python,就可以运行。

DeepSeek 官方 API 信息:
    - API 基础地址:https://api.deepseek.com
    - Chat Completions 接口:/chat/completions
    - 本案例默认模型:deepseek-v4-flash

注意:
    API Key 相当于你的“账号密码”,不要写进代码里发给别人,也不要截图公开。
    本案例会优先从环境变量 DEEPSEEK_API_KEY 读取 API Key。
    如果没有设置环境变量,程序会让你在终端里临时输入 API Key,输入时不会显示出来。

运行方式:

    1. 先把终端 / 命令提示符切换到本文件所在的文件夹。

       Windows 示例:
           cd 你的课程文件夹\\deepseek_api

       macOS 示例:
           cd 你的课程文件夹/deepseek_api

    2. 可选:设置环境变量 DEEPSEEK_API_KEY。

       Windows PowerShell 示例:
           $env:DEEPSEEK_API_KEY="你的 DeepSeek API Key"

       Windows CMD 示例:
           set DEEPSEEK_API_KEY=你的 DeepSeek API Key

       macOS / Linux 示例:
           export DEEPSEEK_API_KEY="你的 DeepSeek API Key"

       如果不设置环境变量,也可以直接运行程序,程序会提示你输入 API Key。

    3. 运行程序。

       Windows 常用命令:
           py terminal_chat_with_deepseek.py

       macOS 常用命令:
           python3 terminal_chat_with_deepseek.py

终端内置命令:
    /exit   退出程序
    /clear  清空对话上下文
    /help   查看帮助

课堂建议:
    第一次讲解时,可以先让学生只看“课堂可修改配置”和 main() 主流程。
    等学生理解“用户输入 -> HTTP 请求 -> 模型回答”之后,再讲 send_chat_request() 的细节。
"""

import getpass
import json
import os
import sys
import time
import urllib.error
import urllib.request


# =========================
# 1. 可修改配置
# =========================
# 初学者如果要调整程序,建议先只改这里。

# DeepSeek API 基础地址。
# 一般不需要修改。
API_BASE_URL = "https://api.deepseek.com"

# Chat Completions 接口路径。
# 完整请求地址会拼成:https://api.deepseek.com/chat/completions
CHAT_COMPLETIONS_PATH = "/chat/completions"

# 默认模型。
# deepseek-v4-flash:速度较快,适合普通聊天、问答、课堂演示。
# deepseek-v4-pro:能力更强,适合复杂推理,但通常更慢、费用更高。
MODEL_NAME = "deepseek-v4-flash"

# 是否开启流式输出。
# True:模型一边生成,一边在终端显示,更像真实聊天。
# False:等模型完整回答结束后一次性显示。
STREAM = True

# 控制回答长度。
# 数字越大,模型最多可以输出越长的内容,也可能消耗更多 token。
MAX_TOKENS = 1000




# 控制回答的随机性。
# 0.0 更稳定、更像标准答案;1.0 更发散、更有创造性。
TEMPERATURE = 0.7





# 系统提示词。
# system 消息用于告诉模型“你应该扮演什么角色、回答风格是什么”。
SYSTEM_PROMPT = """
你是一位耐心的编程课助教。
请用清晰、准确、适合初学者的中文回答问题。
如果学生的问题涉及代码,请优先解释思路,再给出简洁示例。
"""




# 最多保留多少轮历史对话。
# 一轮 = 用户说一次 + 模型答一次。
# 保留历史可以让模型“记得前文”,但历史越长,请求越大,费用也可能越高。
MAX_HISTORY_ROUNDS = 8






# 请求超时时间,单位是秒。
# 网络慢或模型回答很长时,可以适当调大。
REQUEST_TIMEOUT_SECONDS = 120


# =========================
# 2. API Key 读取
# =========================
def get_api_key():
    """
    获取 DeepSeek API Key。

    推荐方式:
        把 API Key 放到环境变量 DEEPSEEK_API_KEY。

    为什么不直接写在代码里?
        因为代码可能会发给同学、提交到网盘或 GitHub。
        API Key 泄露后,别人可能会使用你的额度。

    如果环境变量不存在:
        使用 getpass.getpass() 临时输入。
        这样输入时不会显示在屏幕上,也不会保存在代码里。
    """
    api_key = os.getenv("DEEPSEEK_API_KEY")

    if api_key:
        return api_key.strip()

    print("没有检测到环境变量 DEEPSEEK_API_KEY。")
    print("请临时输入你的 DeepSeek API Key。输入内容不会显示在屏幕上。")
    api_key = getpass.getpass("DeepSeek API Key: ").strip()

    if not api_key:
        print("没有输入 API Key,程序退出。")
        sys.exit(1)

    return api_key


# =========================
# 3. 构造 messages
# =========================
def build_messages(history, user_input):
    """
    构造发送给大模型的 messages。

    Chat Completions API 的核心就是 messages 列表。
    列表里的每一项都是一个字典,常见 role 有:

        system:
            系统设定。告诉模型它是谁、应该怎么回答。

        user:
            用户说的话。也就是学生在终端里输入的问题。

        assistant:
            模型之前回答过的话。保留它可以形成多轮对话上下文。

    例子:
        [
            {"role": "system", "content": "你是编程助教"},
            {"role": "user", "content": "什么是变量?"},
            {"role": "assistant", "content": "变量可以理解为..."},
            {"role": "user", "content": "那列表是什么?"}
        ]
    """
    messages = [{"role": "system", "content": SYSTEM_PROMPT}]
    messages.extend(history)
    messages.append({"role": "user", "content": user_input})
    return messages


def trim_history(history):
    """
    控制历史对话长度。

    为什么要裁剪历史?
        每次请求都会把历史对话一起发给模型。
        历史太长会导致:
            - 请求变慢
            - token 消耗增加
            - 超过模型上下文长度

    history 里每一轮通常有两条消息:
        user 一条,assistant 一条。
    所以保留 MAX_HISTORY_ROUNDS * 2 条。
    """
    max_messages = MAX_HISTORY_ROUNDS * 2

    if len(history) <= max_messages:
        return history

    return history[-max_messages:]


# =========================
# 4. 发送 HTTP 请求
# =========================
def make_request_body(messages):
    """
    构造请求体。

    最终会被转成 JSON,发送给 DeepSeek API。

    参数说明:
        model:
            要调用哪个模型。

        messages:
            对话内容。

        stream:
            是否流式输出。

        max_tokens:
            限制模型最多输出多少 token。

        temperature:
            控制随机性。
    """
    return {
        "model": MODEL_NAME,
        "messages": messages,
        "stream": STREAM,
        "max_tokens": MAX_TOKENS,
        "temperature": TEMPERATURE,
    }


def make_http_request(api_key, body):
    """
    创建 HTTP 请求对象。

    这里不用第三方库 requests,而是使用 Python 标准库 urllib。
    虽然 urllib 写起来稍微长一点,但好处是学生不需要额外安装库。
    """
    url = API_BASE_URL + CHAT_COMPLETIONS_PATH
    json_bytes = json.dumps(body, ensure_ascii=False).encode("utf-8")

    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}",
    }

    return urllib.request.Request(
        url=url,
        data=json_bytes,
        headers=headers,
        method="POST",
    )


def send_chat_request(api_key, messages):
    """
    发送请求,并返回模型回答文本。

    根据 STREAM 的值,这个函数有两种工作方式:

        STREAM=True:
            DeepSeek 会不断返回小片段。
            程序一边收到片段,一边打印到终端。

        STREAM=False:
            程序等待完整 JSON 返回,再从 JSON 中取出回答。
    """
    body = make_request_body(messages)
    request = make_http_request(api_key, body)

    try:
        with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT_SECONDS) as response:
            if STREAM:
                return read_streaming_response(response)
            return read_normal_response(response)

    except urllib.error.HTTPError as error:
        handle_http_error(error)
        return None

    except urllib.error.URLError as error:
        print("\n网络连接失败。")
        print(f"错误信息:{error.reason}")
        print("排查建议:检查网络连接、代理设置,或稍后重试。")
        return None

    except TimeoutError:
        print("\n请求超时。")
        print("排查建议:检查网络,或者把 REQUEST_TIMEOUT_SECONDS 调大。")
        return None


def read_normal_response(response):
    """
    读取非流式响应。

    非流式响应是一个完整 JSON。
    常见结构类似:

        {
            "choices": [
                {
                    "message": {
                        "role": "assistant",
                        "content": "模型回答"
                    }
                }
            ]
        }
    """
    raw_text = response.read().decode("utf-8")
    data = json.loads(raw_text)
    return data["choices"][0]["message"]["content"]


def read_streaming_response(response):
    """
    读取流式响应。

    流式响应不是一次性返回完整 JSON,而是一行一行返回。
    每行通常长这样:

        data: {"choices":[{"delta":{"content":"你好"}}]}

    当收到:

        data: [DONE]

    表示这次回答结束。
    """
    answer_parts = []

    for raw_line in response:
        line = raw_line.decode("utf-8").strip()

        # 空行没有内容,跳过。
        if not line:
            continue

        # Server-Sent Events 常见格式是以 "data: " 开头。
        if not line.startswith("data: "):
            continue

        data_text = line[len("data: "):]

        if data_text == "[DONE]":
            break

        try:
            data = json.loads(data_text)
        except json.JSONDecodeError:
            continue

        choices = data.get("choices", [])
        if not choices:
            continue

        delta = choices[0].get("delta", {})

        # 普通回答内容通常在 content 字段。
        content = delta.get("content")

        # 如果以后切换到推理模型,有些接口可能还会返回 reasoning_content。
        reasoning_content = delta.get("reasoning_content")

        text_piece = content or reasoning_content or ""

        if text_piece:
            print(text_piece, end="", flush=True)
            answer_parts.append(text_piece)

    print()
    return "".join(answer_parts)


# =========================
# 5. 错误处理
# =========================
def handle_http_error(error):
    """
    把 HTTP 错误翻译成学生更容易理解的提示。

    常见状态码:
        400:请求格式有问题。
        401:API Key 错误或没有权限。
        402:账户余额不足或计费相关问题。
        429:请求太频繁。
        500:服务端错误。
    """
    status_code = error.code

    try:
        error_body = error.read().decode("utf-8")
    except Exception:
        error_body = ""

    print("\nAPI 请求失败。")
    print(f"HTTP 状态码:{status_code}")

    if status_code == 400:
        print("可能原因:请求参数格式有问题,例如模型名写错、messages 格式不正确。")
    elif status_code == 401:
        print("可能原因:API Key 错误、过期,或者没有正确放到 Authorization 请求头。")
    elif status_code == 402:
        print("可能原因:账户余额不足或计费状态异常。")
    elif status_code == 429:
        print("可能原因:请求太频繁,触发限流。请稍等几秒再试。")
    elif 500 <= status_code < 600:
        print("可能原因:DeepSeek 服务端暂时异常。可以稍后重试。")
    else:
        print("可能原因:未知 HTTP 错误。")

    if error_body:
        print("\n服务端返回的错误内容:")
        print(error_body)


# =========================
# 6. 终端交互
# =========================
def print_welcome():
    """打印欢迎信息和基本操作说明。"""
    print("=" * 64)
    print("DeepSeek 终端对话教学案例")
    print("=" * 64)
    print(f"模型:{MODEL_NAME}")
    print(f"流式输出:{'开启' if STREAM else '关闭'}")
    print("输入问题后按 Enter 发送。")
    print("输入 /help 查看命令,输入 /exit 退出。")
    print("=" * 64)


def print_help():
    """打印终端命令帮助。"""
    print("\n可用命令:")
    print("  /help   查看帮助")
    print("  /clear  清空当前对话上下文")
    print("  /exit   退出程序")
    print("\n普通输入会作为问题发送给 DeepSeek。")
    print("例如:请用一个生活例子解释什么是 API。\n")


def main():
    """
    主程序入口。

    这个循环做的事情很简单:
        1. 等待学生在终端输入问题。
        2. 把问题和历史对话组成 messages。
        3. 调用 DeepSeek API。
        4. 把模型回答加入历史,形成连续对话。
    """
    api_key = get_api_key()
    history = []

    print_welcome()

    while True:
        try:
            user_input = input("\n你:").strip()
        except (KeyboardInterrupt, EOFError):
            print("\n已退出。")
            break

        if not user_input:
            continue

        if user_input == "/exit":
            print("已退出。")
            break

        if user_input == "/help":
            print_help()
            continue

        if user_input == "/clear":
            history.clear()
            print("已清空对话上下文。")
            continue

        messages = build_messages(history, user_input)

        print("\nDeepSeek:", end="", flush=True)
        start_time = time.time()
        answer = send_chat_request(api_key, messages)
        elapsed = time.time() - start_time

        if answer is None:
            print("这次请求没有得到有效回答。你可以检查错误信息后重试。")
            continue

        history.append({"role": "user", "content": user_input})
        history.append({"role": "assistant", "content": answer})
        history = trim_history(history)

        print(f"\n本次用时:{elapsed:.1f} 秒")


if __name__ == "__main__":
    main()

    
原文