商城首页欢迎来到中国正版软件门户

您的位置:首页 >DeepSeek-7B-chat FastApi 部署教程

DeepSeek-7B-chat FastApi 部署教程

  发布于2025-08-04 阅读(0)

扫一扫,手机访问

DeepSeek-7B-chat FastApi 部署与调用指南

DeepSeek 模型简介

DeepSeek LLM 是一款具备70亿参数的高性能语言模型,基于包含中英文在内的2万亿token数据集从零训练而成。为推动学术研究发展,DeepSeek 已向研究社区开源了多个版本的模型,包括 DeepSeek LLM 7B/67B Base 以及 DeepSeek LLM 7B/67B Chat 版本。

环境搭建

在 autodl 平台上选择配备 NVIDIA 3090 或其他具备 24GB 显存的 GPU 实例。镜像配置建议选择:PyTorch → 2.0.0 → Python 3.8 (Ubuntu20.04) → CUDA 11.8(CUDA 11.3 及以上均可)。创建实例后,进入 JupyterLab 界面,并打开终端进行后续环境配置、模型下载与服务部署。

[大模型]DeepSeek-7B-chat FastApi 部署调用

更换 pip 源并安装所需依赖

# 升级pip
python -m pip install --upgrade pip

设置清华源加速下载

pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple

安装必要库

pip install fastapi==0.104.1 pip install uvicorn==0.24.0.post1 pip install requests==2.25.1 pip install modelscope==1.9.5 pip install transformers==4.35.2 pip install streamlit==1.24.0 pip install sentencepiece==0.1.99 pip install accelerate==0.24.1 pip install transformers_stream_generator==0.0.4

下载模型文件

使用 ModelScope 提供的 snapshot_download 方法获取 DeepSeek-7B-chat 模型。在 /root/autodl-tmp 目录下创建 download.py 文件,写入以下代码并保存(如图所示),然后执行 python /root/autodl-tmp/download.py 开始下载。模型体积约为 15GB,预计耗时 10-20 分钟。

import torch
from modelscope import snapshot_download, AutoModel, AutoTokenizer
from modelscope import GenerationConfig

model_dir = snapshot_download('deepseek-ai/deepseek-llm-7b-chat', cache_dir='/root/autodl-tmp', revision='master')

编写 API 接口服务

/root/autodl-tmp 路径下新建 api.py 文件,填入如下代码并保存。该脚本已添加详细注释,便于理解各模块功能。

from fastapi import FastAPI, Request
from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig
import uvicorn
import json
import datetime
import torch

配置设备信息

DEVICE = "cuda" DEVICE_ID = "0" CUDA_DEVICE = f"{DEVICE}:{DEVICE_ID}" if DEVICE_ID else DEVICE

GPU内存清理函数

def torch_gc(): if torch.cuda.is_available(): with torch.cuda.device(CUDA_DEVICE): torch.cuda.empty_cache() torch.cuda.ipc_collect()

初始化FastAPI应用

app = FastAPI()

@app.post("/") async def create_item(request: Request): global model, tokenizer json_post_raw = await request.json() json_post = json.dumps(json_post_raw) json_post_list = json.loads(json_post)

prompt = json_post_list.get('prompt')
max_length = json_post_list.get('max_length', 512)  # 默认最大长度为512

# 构建对话消息格式
messages = [
    {"role": "user", "content": prompt}
]

# 生成输入张量
input_tensor = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt").to(model.device)

# 模型推理
outputs = model.generate(input_tensor, max_new_tokens=max_length)
result = tokenizer.decode(outputs[0][input_tensor.shape[1]:], skip_special_tokens=True)

now = datetime.datetime.now()
time = now.strftime("%Y-%m-%d %H:%M:%S")

# 返回响应结构
answer = {
    "response": result,
    "status": 200,
    "time": time
}

# 日志输出
log = "[" + time + "] " + ', prompt:"' + prompt + '", response:"' + repr(result) + '"'
print(log)

torch_gc()
return answer

if name == 'main': model_path = '/root/autodl-tmp/deepseek-ai/deepseek-llm-7b-chat'

# 加载分词器和模型
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
    model_path,
    trust_remote_code=True,
    torch_dtype=torch.bfloat16,
    device_map="auto"
)

# 配置生成参数
model.generation_config = GenerationConfig.from_pretrained(model_path)
model.generation_config.pad_token_id = model.generation_config.eos_token_id
model.eval()

# 启动服务
uvicorn.run(app, host='0.0.0.0', port=6006, workers=1)</code></pre><h4>启动 API 服务</h4><p>在终端中运行以下命令启动服务:</p><pre><code class="language-javascript">cd /root/autodl-tmp

python api.py

当模型加载完成后,若看到类似下图的日志输出,则表示服务已成功启动。

[大模型]DeepSeek-7B-chat FastApi 部署调用

服务默认监听 6006 端口,支持通过 POST 请求调用。

使用 curl 调用示例:

curl -X POST "http://127.0.0.1:6006" \
-H 'Content-Type: application/json' \
-d '{"prompt": "你好"}'

使用 Python requests 调用示例:

import requests
import json

def get_completion(prompt): headers = {'Content-Type': 'application/json'} data = {"prompt": prompt} response = requests.post(url='http://127.0.0.1:6006', headers=headers, data=json.dumps(data)) return response.json()['response']

if name == 'main': print(get_completion('你好'))

返回结果示例:

{
'response': '你好!有什么我可以帮助你的吗?', 
'status': 200, 
'time': '2023-12-01 17:06:10'
}

[大模型]DeepSeek-7B-chat FastApi 部署调用

本文转载于:https://cloud.tencent.com/developer/article/2542006 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注