Python 调用 DeepSeek API 完整指南

简介

本文将详细介绍如何使用 Python 调用 DeepSeek API,实现流式对话并保存对话记录。相比 Go 版本,Python 实现更加简洁优雅,适合快速开发和原型验证。https://cloud.siliconflow.cn/i/vnCCfVaQ

1. 环境准备

1.1 依赖安装

pip install requests

1.2 项目结构

deepseek-project/
├── main.py           # 主程序
└── conversation.txt  # 对话记录文件

2. 完整代码实现

import os
import json
import time
import requests
from datetime import datetime

def save_to_file(file, content, is_question=False):
    """保存对话内容到文件"""
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    if is_question:
        file.write(f"\n[{timestamp}] Question:\n{content}\n\n[{timestamp}] Answer:\n")
    else:
        file.write(content)

def main():
    # 配置
    url = "https://api.siliconflow.cn/v1/chat/completions"
    headers = {
        "Content-Type": "application/json",
        "Authorization": "Bearer YOUR_API_KEY"  # 替换为你的 API Key
    }

    # 打开文件用于保存对话
    with open("conversation.txt", "a", encoding="utf-8") as file:
        while True:
            # 获取用户输入
            question = input("\n请输入您的问题 (输入 q 退出): ").strip()
            
            if question.lower() == 'q':
                print("程序已退出")
                break

            # 保存问题
            save_to_file(file, question, is_question=True)

            # 准备请求数据
            data = {
                "model": "deepseek-ai/DeepSeek-V3",
                "messages": [
                    {
                        "role": "user",
                        "content": question
                    }
                ],
                "stream": True,
                "max_tokens": 2048,
                "temperature": 0.7,
                "top_p": 0.7,
                "top_k": 50,
                "frequency_penalty": 0.5,
                "n": 1,
                "response_format": {
                    "type": "text"
                }
            }

            try:
                # 发送流式请求
                response = requests.post(url, json=data, headers=headers, stream=True)
                response.raise_for_status()  # 检查响应状态

                # 处理流式响应
                for line in response.iter_lines():
                    if line:
                        line = line.decode('utf-8')
                        if line.startswith('data: '):
                            if line == 'data: [DONE]':
                                continue
                            
                            try:
                                content = json.loads(line[6:])  # 去掉 'data: ' 前缀
                                if content['choices'][0]['delta'].get('content'):
                                    chunk = content['choices'][0]['delta']['content']
                                    print(chunk, end='', flush=True)
                                    file.write(chunk)
                                    file.flush()
                            except json.JSONDecodeError:
                                continue

                # 添加分隔符
                print("\n----------------------------------------")
                file.write("\n----------------------------------------\n")
                file.flush()

            except requests.RequestException as e:
                error_msg = f"请求错误: {str(e)}\n"
                print(error_msg)
                file.write(error_msg)
                file.flush()

if __name__ == "__main__":
    main()

3. 代码详解

3.1 核心功能

文件记录功能

save_to_file 函数负责:

  • 生成时间戳
  • 格式化保存问题和答案
  • 自动刷新文件缓冲区
API 配置
headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer YOUR_API_KEY"  # 替换为你的 API Key
}
流式请求处理

程序使用 requests 库的流式处理功能:

  • 使用 stream=True 启用流式传输
  • 逐行处理响应数据
  • 实时显示和保存内容

3.2 配置参数说明

API 请求参数:

  • model: 使用的模型名称
  • stream: 启用流式输出
  • max_tokens: 最大输出长度 (2048)
  • temperature: 控制随机性 (0.7)
  • top_p, top_k: 采样参数
  • frequency_penalty: 重复惩罚系数

4. 错误处理

代码包含完整的错误处理机制:

  • 检查 HTTP 响应状态
  • 捕获网络异常
  • 处理 JSON 解析错误
  • 文件操作错误处理

5. 使用方法

5.1 修改配置

在代码中替换 YOUR_API_KEY 为你的实际 API Key。

5.2 运行程序

python main.py

5.3 交互方式

  1. 输入问题进行对话
  2. 输入 ‘q’ 退出程序
  3. 查看 conversation.txt 获取对话记录

6. 性能优化建议

  1. 文件操作

    • 使用适当的缓冲区大小
    • 定期刷新文件缓冲
    • 正确关闭文件句柄
  2. 网络请求

    • 设置适当的超时
    • 使用会话(Session)复用连接
    • 处理网络异常
  3. 内存管理

    • 及时释放资源
    • 避免大量数据积累
    • 使用生成器处理流式数据

总结

Python 版本的 DeepSeek API 调用实现简单直观,适合快速开发和测试。通过流式处理和文件记录,提供了完整的对话体验。

立即体验

现在就来体验 DeepSeek 的强大功能!

快来体验 DeepSeek:https://cloud.siliconflow.cn/i/vnCCfVaQ

快来体验 DeepSeek:https://cloud.siliconflow.cn/i/vnCCfVaQ

快来体验 DeepSeek:https://cloud.siliconflow.cn/i/vnCCfVaQ

### 使用Python调用DeepSeek API 对于希望利用Python访问DeepSeek API的情况,通常涉及几个关键步骤来设置环境并编写必要的代码逻辑。虽然提供的参考资料未直接提及DeepSeek API的具体应用实例[^1],可以基于一般性的API交互原则以及网络服务接口编程的经验来进行说明。 #### 安装依赖包 为了简化HTTP请求处理过程,推荐安装`requests`库: ```bash pip install requests ``` #### 获取认证令牌 大多数现代Web APIs都要求开发者通过OAuth或其他形式的身份验证机制获取访问权限。假设DeepSeek采用的是Bearer Token方式,则需先向官方申请得到相应的API Key或Secret,并据此换取可实际使用的Token。 ```python import requests url = "https://api.deepseek.example.com/auth/token" data = { 'client_id': 'YOUR_CLIENT_ID', 'client_secret': 'YOUR_CLIENT_SECRET' } response = requests.post(url, data=data) access_token = response.json().get('access_token') print(f'Access token received: {access_token}') ``` #### 发送查询请求 一旦拥有了有效的授权凭证,就可以构建针对特定资源路径的GET/POST等类型的HTTP请求了。这里展示了一个简单的例子,用于发起搜索请求给DeepSeek引擎: ```python search_query = input("Enter your search query:") headers = {'Authorization': f'Bearer {access_token}'} params = {'q': search_query} response = requests.get( url='https://api.deepseek.example.com/search', headers=headers, params=params ) results = response.json() for result in results['items']: print(result['title'], ': ', result['link']) ``` 需要注意的是上述URLs均为虚构示例,在真实场景下应当替换为DeepSeek官方文档中指定的服务端点地址。
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老大白菜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值