当前位置: 首页 > article >正文

DeepSeek API 客户端使用文档

1. 简介

deep.py 是一个用于与 DeepSeek API 交互的 Python 客户端封装。它提供了简单易用的接口,支持对话历史管理、日志记录等功能,使得与 DeepSeek API 的交互更加便捷和可靠。

2. 功能特点

  • 简单的接口设计
  • 自动管理对话历史
  • 完整的日志记录
  • 灵活的配置选项
  • 异常处理机制

3. 安装依赖

pip install openai

4. 配置环境

在项目根目录创建 .env 文件:

# Windows
set DEEPSEEK_API_KEY=your_api_key_here

# Linux/Mac
export DEEPSEEK_API_KEY=your_api_key_here

5. 代码结构

5.1 主要组件

class DeepSeekChat:
    def __init__(self, api_key: str, base_url: str = "https://api.deepseek.com")
    def send_message(self, message: str, ...) -> str
    def clear_history(self)

5.2 日志配置

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('deepseek.log'),
        logging.StreamHandler()
    ]
)

6. 使用示例

6.1 基本使用

from deep import DeepSeekChat

# 创建客户端实例
chat = DeepSeekChat(api_key="your_api_key")

# 发送消息
response = chat.send_message("Hello")
print("Assistant:", response)

6.2 高级配置

# 自定义系统提示词和其他参数
response = chat.send_message(
    message="Tell me a joke",
    system_prompt="You are a funny assistant",
    temperature=0.8,
    max_tokens=150,
    save_history=True
)

# 清除对话历史
chat.clear_history()

7. API 参数说明

7.1 DeepSeekChat 类初始化参数

参数类型默认值说明
api_keystr必填DeepSeek API 密钥
base_urlstr“https://api.deepseek.com”API 基础 URL

7.2 send_message 方法参数

参数类型默认值说明
messagestr必填用户消息内容
system_promptstr“You are a helpful assistant”系统提示词
modelstr“deepseek-chat”使用的模型名称
streamboolFalse是否使用流式响应
save_historyboolTrue是否保存对话历史
temperaturefloat可选控制回复的随机性
max_tokensint可选限制回复长度

8. 日志记录

日志文件 deepseek.log 记录以下信息:

  • 请求发送时间和内容
  • 响应接收时间和处理时长
  • 错误信息(如果有)

9. 错误处理

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

  • API 调用错误捕获
  • 环境变量检查
  • 详细的错误日志记录

10. 最佳实践

  1. 环境变量管理

    • 使用 .env 文件管理 API 密钥
    • 不要在代码中硬编码密钥
  2. 错误处理

    • 始终使用 try-except 块包装 API 调用
    • 检查并记录错误信息
  3. 对话历史

    • 根据需要保存或清除对话历史
    • 长对话时注意 token 限制
  4. 性能优化

    • 适当设置 max_tokens 参数
    • 必要时使用流式响应

11. 注意事项

  1. API 密钥安全

    • 不要将 API 密钥提交到版本控制系统
    • 使用环境变量或配置文件管理密钥
  2. 错误处理

    • 注意处理网络超时等异常
    • 记录详细的错误日志
  3. 资源管理

    • 及时清理不需要的对话历史
    • 注意 API 调用频率限制

12. 完整代码

import os
from typing import List, Dict, Optional
from openai import OpenAI
import logging
from datetime import datetime

# 配置日志记录
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('deepseek.log'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

class DeepSeekChat:
    """DeepSeek API 聊天客户端"""
    
    def __init__(self, api_key: str, base_url: str = "https://api.deepseek.com"):
        """
        初始化 DeepSeek 聊天客户端
        
        Args:
            api_key: DeepSeek API密钥
            base_url: DeepSeek API基础URL
        """
        self.client = OpenAI(api_key=api_key, base_url=base_url)
        self.conversation_history: List[Dict[str, str]] = []
        
    def send_message(
        self, 
        message: str,
        system_prompt: str = "You are a helpful assistant",
        model: str = "deepseek-chat",
        stream: bool = False,
        save_history: bool = True,
        **kwargs
    ) -> str:
        """
        发送消息并获取回复
        
        Args:
            message: 用户消息内容
            system_prompt: 系统提示词
            model: 使用的模型名称
            stream: 是否使用流式响应
            save_history: 是否保存对话历史
            **kwargs: 其他API参数

        Returns:
            str: 助手的回复内容

        Raises:
            Exception: API调用失败时抛出异常
        """
        try:
            # 构建消息列表
            messages = [{"role": "system", "content": system_prompt}]
            if save_history:
                messages.extend(self.conversation_history)
            messages.append({"role": "user", "content": message})
            
            # 记录请求
            logger.info(f"Sending message: {message[:100]}...")
            
            # 发送请求
            start_time = datetime.now()
            response = self.client.chat.completions.create(
                model=model,
                messages=messages,
                stream=stream,
                **kwargs
            )
            
            # 获取响应内容
            assistant_message = response.choices[0].message.content
            
            # 计算响应时间
            response_time = (datetime.now() - start_time).total_seconds()
            logger.info(f"Got response in {response_time:.2f} seconds")
            
            # 保存对话历史
            if save_history:
                self.conversation_history.append({"role": "user", "content": message})
                self.conversation_history.append({"role": "assistant", "content": assistant_message})
            
            return assistant_message
            
        except Exception as e:
            logger.error(f"Error in send_message: {str(e)}")
            raise
    
    def clear_history(self):
        """清除对话历史"""
        self.conversation_history.clear()
        logger.info("Conversation history cleared")

def main():
    """示例用法"""
    try:
        # 从环境变量获取API密钥
        api_key = os.getenv("DEEPSEEK_API_KEY")
        if not api_key:
            raise ValueError("Please set DEEPSEEK_API_KEY environment variable")
        
        # 创建聊天客户端
        chat = DeepSeekChat(api_key=api_key)
        
        # 发送消息并获取回复
        response = chat.send_message(
            message="Hello",
            temperature=0.7,  # 可选:控制回复的随机性
            max_tokens=100    # 可选:限制回复长度
        )
        
        print("Assistant:", response)
        
    except Exception as e:
        logger.error(f"Error in main: {str(e)}")
        raise

if __name__ == "__main__":
    main()

.env

# Windows
set DEEPSEEK_API_KEY=your_api_key_here

# Linux/Mac
export DEEPSEEK_API_KEY=your_api_key_here

http://www.kler.cn/a/585568.html

相关文章:

  • Spring Boot对接twilio发送邮件信息
  • Docker 部署Spring boot + Vue(若依为例)
  • Linux系统下安装Gedit文本编辑器的完整指南
  • C++能力测试题
  • 深入 Python 网络爬虫开发:从入门到实战
  • 完善 Django 框架以实现传递视频、图片给算法模块进行识别分析
  • 防止手机验证码被刷:React + TypeScript 与 Node.js + Express 的全面防御策略
  • WebLogic XMLDecoder反序列化漏洞(CVE-2017-10271)深度解析与实战复现
  • JVM 的不同组成部分分别有什么作用?
  • URL 中的参数通常用于跟踪和传递信息,特别是在在线广告和营销活动中。
  • 鸿蒙初学者学习手册(HarmonyOSNext_API14)_UIContext(@ohos.arkui.UIContext (UIContext))
  • tensorflow与torch并行读取数据机制
  • 浅谈StarRocks数据库简介及应用
  • 阿里巴巴发布 R1-Omni:首个基于 RLVR 的全模态大语言模型,用于情感识别
  • ZooKeeper的五大核心作用及其在分布式系统中的关键价值
  • Redis 常用数据类型
  • 在 Qt 中自定义控件样式:使用 QProxyStyle 代理和修改绘制元素
  • AnyAnomaly: 基于大型视觉语言模型的零样本可定制视频异常检测
  • 回文字串(信息学奥赛一本通-2044)
  • 网络华为HCIA+HCIP网络层协议