调用本地魔塔Chatglm3的 api,FastAPI

本文讲述了在使用FastAPI构建API时遇到的CUDA初始化错误和DataParallel问题,以及解决方法,适合IT开发者和技术社区阅读。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.创建.py文件,jupyter会报错

看自己缺什么包,补什么包

先确保自己模型加载,在当前环境下不报错。

from fastapi import FastAPI
from pydantic import BaseModel
import uvicorn
import torch
import os
from modelscope import AutoTokenizer, AutoModel, snapshot_download
os.environ['CUDA_VISIBLE_DEVICES'] = "1,0"

app = FastAPI()

class Query(BaseModel):
    text: str

model_dir = snapshot_download("ZhipuAI/chatglm3-6b-32k", revision = "v1.0.0")
tokenizer = AutoTokenizer.from_pretrained("ZhipuAI/chatglm3-6b-32k", trust_remote_code=True)
model = AutoModel.from_pretrained(model_dir, trust_remote_code=True).half().cuda()
model = torch.nn.DataParallel(model,device_ids=[0,1])
if isinstance(model,torch.nn.DataParallel):
		model = model.module
                
@app.post("/chat/")
async def chat(query: Query):
    input_ids = tokenizer([query.text]).input_ids
    output_ids = model.generate(
        torch.as_tensor(input_ids).cuda(),
        do_sample=False,
        temperature=0.1,
        repetition_penalty=1,
        max_new_tokens=1024)
    output_ids = output_ids[0][len(input_ids[0]):]
    outputs = tokenizer.decode(output_ids, skip_special_tokens=True, spaces_between_special_tokens=False)
    return {"result": outputs}


if __name__ == "__main__":
   uvicorn.run(app, host="0.0.0.0", port=8060)

运行上门的文件

2.测试api 新建一个py文件

import requests
url = "http://0.0.0.0:8060/chat"
query={'text':"hi"}
response = requests.post(url, json=query)
if response.status_code == 200:
    res = response.json()
    print("Chatglm3:",res["result"])
else:
    print("error")

运行,正常返回,表示api调用成功!

查看防火墙,确保端口 8060是允许的,或者换成自己的允许的端口

查询端口状态:ufw status

坑:

当时设置环境os.environ['CUDA_VISIBLE_DEVICES'] = "1,0" 报错

torch.cuda.DeferredCudaCallError: CUDA call failed lazily at initialization 

bash重置指定显卡解决问题

unset CUDA_VISIBLE_DEVICES

并行报错:

AttributeError: ‘DataParallel’ object has no attribute ‘xxxx’

在并行后加入以下代码:

if isinstance(model,torch.nn.DataParallel):
		model = model.module

参考文章:



【FastAPI】利用FastAPI构建大模型接口服务-优快云博客

torch.cuda.DeferredCudaCallError: CUDA call failed lazily at initialization 报错-优快云博客

Pytorch —— AttributeError: ‘DataParallel’ object has no attribute ‘xxxx’_attributeerror: 'dataparallel' object has no attri-优快云博客

### 使用 ChatGLM API 的方法 #### 方法一:通过远程调用 chatGLM-4 API 可以定义一个函数 `call_chat_glm_api` 来封装对 chatGLM-4 API 的请求逻辑。此函数接收输入文本并将其转换为符合 API 需求的格式,随后发送到指定模型进行处理[^1]。 以下是实现该功能的具体代码: ```python def call_chat_glm_api(text): content = gen_prompt(text) # 假设有一个预处理函数 gen_prompt 将原始文本转化为合适的提示形式 try: response = client.chat.completions.create( model="glm-4", messages=[ {"role": "user", "content": content} ], ) except Exception as e: print(f"发生错误:{e}") return None return response.choices[0].message.content # 返回具体的消息内容部分 ``` 注意,在上述代码中需要提前配置好客户端对象 `client` 并导入必要的库来支持与 API 的交互操作。 #### 方法二:利用本地部署的 FastAPI 接口访问魔塔 ChatGML3 如果已经搭建好了基于 FastAPI 的服务端程序,则可以通过 HTTP 请求的方式轻松完成数据交换过程[^2]。下面展示了一个简单的例子用于验证接口是否正常工作以及获取初步响应结果: ```python import requests url = "http://localhost:8060/chat" query = {'text': '你好'} response = requests.post(url, json=query) if response.status_code == 200: result = response.json() print("ChatGML3:", result['result']) else: print("Error occurred while communicating with the server.") ``` 以上脚本向运行于 localhost 上监听端口号为 8060 的服务器发起 POST 请求,并附带了一条问候消息作为测试样例;当收到成功状态码 (即 200 OK) 后解析返回的数据包提取有用信息打印出来供查看。 ### 注意事项 为了能够顺利运用这些技术手段,请务必确认以下几点前提条件均已满足: - 已经安装了所需的 Python 库(如 `requests`, 如果采用第二种方式的话) - 正确设置了环境变量或者提供了认证令牌等相关参数以便连接目标服务平台 - 对应版本的服务实例正在稳定运转当中
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值