亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python調(diào)用DeepSeek?API的完整操作指南

 更新時間:2025年02月07日 09:21:01   作者:老大白菜  
本文將詳細(xì)介紹如何使用?Python?調(diào)用?DeepSeek?API,實(shí)現(xiàn)流式對話并保存對話記錄,相比?Go?版本,Python?實(shí)現(xiàn)更加簡潔優(yōu)雅,適合快速開發(fā)和原型驗(yàn)證,文中通過代碼示例講解的非常詳細(xì),需要的朋友可以參考下

簡介

本文將詳細(xì)介紹如何使用 Python 調(diào)用 DeepSeek API,實(shí)現(xiàn)流式對話并保存對話記錄。相比 Go 版本,Python 實(shí)現(xiàn)更加簡潔優(yōu)雅,適合快速開發(fā)和原型驗(yàn)證。https://cloud.siliconflow.cn/i/vnCCfVaQ

1. 環(huán)境準(zhǔn)備

1.1 依賴安裝

pip install requests

1.2 項(xiàng)目結(jié)構(gòu)

deepseek-project/
├── main.py           # 主程序
└── conversation.txt  # 對話記錄文件

2. 完整代碼實(shí)現(xiàn)

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

def save_to_file(file, content, is_question=False):
    """保存對話內(nèi)容到文件"""
    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)

            # 準(zhǔn)備請求數(shù)據(jù)
            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:
                # 發(fā)送流式請求
                response = requests.post(url, json=data, headers=headers, stream=True)
                response.raise_for_status()  # 檢查響應(yīng)狀態(tài)

                # 處理流式響應(yīng)
                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 函數(shù)負(fù)責(zé):

  • 生成時間戳
  • 格式化保存問題和答案
  • 自動刷新文件緩沖區(qū)

API 配置

headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer YOUR_API_KEY"  # 替換為你的 API Key
}

流式請求處理

程序使用 requests 庫的流式處理功能:

  • 使用 stream=True 啟用流式傳輸
  • 逐行處理響應(yīng)數(shù)據(jù)
  • 實(shí)時顯示和保存內(nèi)容

3.2 配置參數(shù)說明

API 請求參數(shù):

  • model: 使用的模型名稱
  • stream: 啟用流式輸出
  • max_tokens: 最大輸出長度 (2048)
  • temperature: 控制隨機(jī)性 (0.7)
  • top_ptop_k: 采樣參數(shù)
  • frequency_penalty: 重復(fù)懲罰系數(shù)

4. 錯誤處理

代碼包含完整的錯誤處理機(jī)制:

  • 檢查 HTTP 響應(yīng)狀態(tài)
  • 捕獲網(wǎng)絡(luò)異常
  • 處理 JSON 解析錯誤
  • 文件操作錯誤處理

5. 使用方法

5.1 修改配置

在代碼中替換 YOUR_API_KEY 為你的實(shí)際 API Key。

5.2 運(yùn)行程序

python main.py

5.3 交互方式

  • 輸入問題進(jìn)行對話
  • 輸入 ‘q’ 退出程序
  • 查看 conversation.txt 獲取對話記錄

6. 性能優(yōu)化建議

  1. 文件操作

    • 使用適當(dāng)?shù)木彌_區(qū)大小
    • 定期刷新文件緩沖
    • 正確關(guān)閉文件句柄
  2. 網(wǎng)絡(luò)請求

    • 設(shè)置適當(dāng)?shù)某瑫r
    • 使用會話(Session)復(fù)用連接
    • 處理網(wǎng)絡(luò)異常
  3. 內(nèi)存管理

    • 及時釋放資源
    • 避免大量數(shù)據(jù)積累
    • 使用生成器處理流式數(shù)據(jù)

總結(jié)

Python 版本的 DeepSeek API 調(diào)用實(shí)現(xiàn)簡單直觀,適合快速開發(fā)和測試。通過流式處理和文件記錄,提供了完整的對話體驗(yàn)。

到此這篇關(guān)于Python調(diào)用DeepSeek API的完整操作指南的文章就介紹到這了,更多相關(guān)Python調(diào)用DeepSeek API內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論