Python 接入DeepSeek

不知不觉DeepSeek已经火了半年左右,冲浪都赶不上时代了。

今天开始学习。

本文旨在使用Python调用DeepSeek的接口(

这里写目录标题

  • 一、环境准备
    • [1.1 DeepSeek](#1.1 DeepSeek)
    • [1.2 Python](#1.2 Python)
  • 二、接入DeepSeek
    • [2.1 参数](#2.1 参数)
    • [2.2 requests](#2.2 requests)
    • [2.3 openai](#2.3 openai)
    • [2.4 返回示例](#2.4 返回示例)

一、环境准备

1.1 DeepSeek

在线的话,可以直接调用DeepSeek官网的api,只是token付费

离线的话,如果个人学习,可以通过Ollama来装大模型,商业试用可以VLLM

具体部署步骤,官网已经有了,就不在这里赘述

1.2 Python

目前要接入DeepSeek,要求Python 至少 3.7 以上版本。(我自己用的3.13.3)

安装可以借鉴我以前写的Python(一)------了解和安装

二、接入DeepSeek

目前所谓的接入DeepSeek,只不过是调用DeepSeek的对话接口。

主要通过两种方式调用:

  • requests
  • openai

2.1 参数

DeepSeek api 请求的参数

参数名 描述
baseUrl 请求的地址
api-key 请求的key
model 模型的id,由你安装大模型时自己定义的id
message 对话的内容

2.2 requests

需要安装python 的requests

shell 复制代码
pip install requests

代码示例

python 复制代码
import requests

API_KEY = 'api-key'
url = baseUrl+'/chat/completions'

headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer ' + API_KEY
}

data = {
        "model": model,
        "messages": [
            {"role": "user", "content": "deepseek是怎么样的一家公司?"}
        ]
}

response = requests.post(url, headers=headers, json=data)

if response.status_code == 200:
    result = response.json()
    print(result['choices'][0]['message']['content'])
else:
    print("请求失败,错误码:", response.status_code)

2.3 openai

需要安装python 的openai

shell 复制代码
pip install openai

代码示例

python 复制代码
from openai import OpenAI

client = OpenAI(api_key=api-key, base_url=baseUrl)

response = client.chat.completions.create(
    model=model,
    messages=[
        {"role": "user", "content": "deepseek是怎么样的一家公司?"}
    ],
    stream=False
)

print(response.choices[0].message.content)

2.4 返回示例

相关推荐
金銀銅鐵15 小时前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup1119 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi0021 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵1 天前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf1 天前
Agent 流程编排
后端·python·agent
copyer_xyf1 天前
Agent RAG
后端·python·agent
copyer_xyf1 天前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf1 天前
Agent 记忆管理
后端·python·agent
星云穿梭2 天前
用Python写一个带图形界面的学生管理系统——完整教程
python