大模型模型部署和暴露接口

创建环境

激活案件

安装相关依赖

复制代码
conda create -n fastApi python=3.10
conda activate fastApi
conda install -c conda-forge fastapi uvicorn transformers pytorch
pip install safetensors sentencepiece protobuf

新建文件夹

复制代码
mkdir App
cd App
touch main.py

复制代码main.py

复制代码
from fastapi import FastAPI
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

app = FastAPI()

# 模型路径
model_path = "/root/autodl-tmp/Models/deepseek-r1-1.5b-merged"

# 加载 tokenizer (分词器)
tokenizer = AutoTokenizer.from_pretrained(model_path)

# 加载模型并移动到可用设备(GPU/CPU)
device = "cuda" if torch.cuda.is_available() else "cpu"
model = AutoModelForCausalLM.from_pretrained(model_path).to(device)

@app.get("/generate")
async def generate_text(prompt: str):
    # 使用 tokenizer 编码输入的 prompt
    inputs = tokenizer(prompt, return_tensors="pt").to(device)
    
    # 使用模型生成文本
    outputs = model.generate(inputs["input_ids"], max_length=150)
    
    # 解码生成的输出
    generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
    
    return {"generated_text": generated_text}

运行app.py文件

复制代码
uvicorn main:app --reload --host 0.0.0.0

可能报错,升级 huggingface-hub,运行以下命令升级到兼容版本

复制代码
pip install --upgrade huggingface-hub
uvicorn main:app --reload --host 0.0.0.0

浏览器打开

复制代码
http://localhost:8000/docs

后端接口

然后就是做一个网站调用大模型接口,类似如下

前端项目:https://github.com/huangyf2013320506/magic_conch_frontend.git

复制代码
npm instal1
npm run dev

后端项目:https://github.com/huangyf2013320506/magic_conch_backend.git

记得把jdk改一下,之前一直用的是1.8

把网址改成"http://127.0.0.1:5173",因为前端网址是这

编译一下

然后运行启动就行,注意要在在MagicconchBackendApplication.java 类中启动

相关推荐
C_心欲无痕3 小时前
ts - tsconfig.json配置讲解
linux·前端·ubuntu·typescript·json
冰西瓜6003 小时前
国科大2025操作系统高级教程期末回忆版
linux
HIT_Weston4 小时前
93、【Ubuntu】【Hugo】搭建私人博客:面包屑(一)
linux·运维·ubuntu
cuijiecheng20184 小时前
Linux下Beyond Compare过期
linux·运维·服务器
喵叔哟4 小时前
20.部署与运维
运维·docker·容器·.net
HIT_Weston5 小时前
92、【Ubuntu】【Hugo】搭建私人博客:侧边导航栏(六)
linux·运维·ubuntu
CodeAllen嵌入式5 小时前
Windows 11 本地安装 WSL 支持 Ubuntu 24.04 完整指南
linux·运维·ubuntu
期待のcode5 小时前
前后端分离项目 Springboot+vue 在云服务器上的部署
服务器·vue.js·spring boot
AI 智能服务5 小时前
第6课__本地工具调用(文件操作)
服务器·人工智能·windows·php
码农小韩6 小时前
基于Linux的C++学习——指针
linux·开发语言·c++·学习·算法