chatglm llm实时流api接口及post访问

news2024/10/6 5:58:22

参考:
https://github.com/THUDM/ChatGLM-6B/pull/573/commits/02947052eefe392fd9f9632894e9551a805c6109
https://github.com/THUDM/ChatGLM-6B/pull/573

1、代码:

提前安装:
sse_starlette、fastapi

python  stream_api.py

stream_api.py

from fastapi import FastAPI
from pydantic import BaseModel
from typing import Optional
from sse_starlette.sse import EventSourceResponse
from transformers import AutoTokenizer, AutoModel
import uvicorn
import torch

'''
 此脚本实现模型响应结果的流式传输,让用户无需等待完整内容的响应。
 This script implements the streaming transmission of model response results, eliminating the need for users to wait for a complete response of the content.
 访问接口时它将返回event-stream流,你需要在客户端接收并处理它。
 When accessing the interface, it will return an 'event-stream' stream, which you need to receive and process on the client.
 POST http://127.0.0.1:8010
 { "input": "你好ChatGLM" }
 input: 输入内容
 max_length: 最大长度
 top_p: 采样阈值
 temperature: 抽样随机性
 history: 二维历史消息数组,eg: [["你好ChatGLM","你好,我是ChatGLM,一个基于语言模型的人工智能助手。很高兴见到你,欢迎问我任何问题。"]]
 html_entities: 开启HTML字符实体转换
'''

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

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


app = FastAPI()

def parse_text(text):
    lines = text.split("\n")
    lines = [line for line in lines if line != ""]
    count = 0
    for i, line in enumerate(lines):
        if "```" in line:
            count += 1
            items = line.split('`')
            if count % 2 == 1:
                lines[i] = f'<pre><code class="language-{items[-1]}">'
            else:
                lines[i] = f'<br></code></pre>'
        else:
            if i > 0:
                if count % 2 == 1:
                    line = line.replace("`", "\`")
                    line = line.replace("<", "&lt;")
                    line = line.replace(">", "&gt;")
                    line = line.replace(" ", "&nbsp;")
                    line = line.replace("*", "&ast;")
                    line = line.replace("_", "&lowbar;")
                    line = line.replace("-", "&#45;")
                    line = line.replace(".", "&#46;")
                    line = line.replace("!", "&#33;")
                    line = line.replace("(", "&#40;")
                    line = line.replace(")", "&#41;")
                    line = line.replace("$", "&#36;")
                lines[i] = "<br>"+line
    text = "".join(lines)
    return text

async def predict(input, max_length, top_p, temperature, history, html_entities):
    global model, tokenizer
    for response, history in model.stream_chat(tokenizer, input, history, max_length=max_length, top_p=top_p,
                                               temperature=temperature):
        yield parse_text(response) if html_entities else response
    torch_gc()

class ConversationsParams(BaseModel):
    input: str
    max_length: Optional[int] = 2048
    top_p: Optional[float] = 0.7
    temperature: Optional[float] = 0.95
    history: Optional[list] = []
    html_entities: Optional[bool] = True

@app.post('/')
async def conversations(params: ConversationsParams):
    history = list(map(tuple, params.history))
    predictGenerator = predict(params.input, params.max_length, params.top_p, params.temperature, history, params.html_entities)
    return EventSourceResponse(predictGenerator)

if __name__ == '__main__':
    tokenizer = AutoTokenizer.from_pretrained("/mnt***atglm2-6b-int4"", trust_remote_code=True)
    model = AutoModel.from_pretrained("/mnt***hatglm2-6b-int4"", trust_remote_code=True).half().cuda()
    model.eval()
    uvicorn.run(app, host='19*****4', port=8000, workers=1)

2、api访问

1)curl

curl -X POST “http://127.0.0.1:8010”
-H ‘Content-Type: application/json’
-d ‘{“input”: “你好”}’

2)http post访问

因为requests库不支持处理服务器发送事件(SSE)响应。您需要使用另一个库,如httpx或aiohttp,它们支持异步请求和处理SSE响应。
在这里插入图片描述

例如,您可以使用httpx库。首先,安装httpx:

fetch_data()的异步函数中。函数中使用httpx.AsyncClient来创建一个异步客户端,并通过client.stream方法发送POST请求,并使用异步迭代器response.aiter_lines()逐行获取响应数据进行打印。

最后,我使用asyncio.run()来执行异步函数

pip install httpx


import httpx
import asyncio

url = "http://192*****4:8000"
data = {
    "input": "你能做什么",
    "max_length": 2048,
    "top_p": 0.7,
    "temperature": 0.95,
    "history": [["你名字叫杰*******安全;每次回答请都简要回答不超过30个字","好的,****为你服务"]],


    "html_entities": True,
}

async def fetch_data():
    async with httpx.AsyncClient() as client:
        async with client.stream("POST", url, json=data) as response:
            async for line in response.aiter_lines():
                print(line)

# 调用异步函数
asyncio.run(fetch_data())

在这里插入图片描述

如果需要实时播报
import httpx
import asyncio

import pyttsx3

async def fetch_data():
    text_len = 0
    async with httpx.AsyncClient() as client:
        async with client.stream("POST", url, json=data) as response:
            async for line in response.aiter_lines():
                print(line)
                line = line[6:]
                if text_len == 0:
                    if "," in line or ":" in line or "。" in line or  "、" in line or "!" in line or "," in line:
                        pyttsx3.speak(line)
                        text_len += len(line)

                else:
                    new_line = line[text_len:]
                    if "," in new_line or ":" in new_line or "。" in new_line or  "、" in new_line or "!" in new_line or "," in new_line:
                        
                        pyttsx3.speak(new_line)
                        text_len += len(new_line)

# 调用异步函数
asyncio.run(fetch_data())

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/893670.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Linux:如何挂载Window的共享目录

本文介绍的方法操作简单快捷&#xff0c;实用性强。下面就让小编来带大家学习“Linux下怎么挂载Window中的共享目录”吧! 一、在Window下创建共享目录 1、首先&#xff0c;在Window下创建一个目录作为共享目录&#xff0c;此处创建的目录名为ShareDir 2、右键目录&#xff0c…

创建密码库/创建用户帐户/更新 Ansible 库的密钥/ 配置cron作业

目录 创建密码库 创建用户帐户 更新 Ansible 库的密钥 配置cron作业 创建密码库 按照下方所述&#xff0c;创建一个 Ansible 库来存储用户密码&#xff1a; 库名称为 /home/curtis/ansible/locker.yml 库中含有两个变量&#xff0c;名称如下&#xff1a; pw_developer&#…

LiveCharts 直方图详解,安装和使用,以及常用属性的说明

LiveCharts 直方图详解 LiveCharts 概述安装 LiveCharts 及 如何使用直方图 LineSeries 属性说明综合直方图小例子 LiveCharts 概述 LiveCharts是一个比较漂亮的WPF图表控件&#xff0c;在数据变化时还会有动画切换的效果&#xff0c;并且样式也可以控制。 安装 LiveCharts 及…

mysql 插入数据锁等待超时报错:Lock wait timeout exceeded; try restarting transaction

报错信息 Lock wait timeout exceeded; try restarting transaction 锁等待超时 Lock wait timeout exceeded; try restarting transaction&#xff0c;是当前事务在等待其它事务释放锁资源造成的 解决办法 1、数据库中执行如下sql&#xff0c;查看当前数据库的线程情况&…

【数据结构OJ题】环形链表II

原题链接&#xff1a;https://leetcode.cn/problems/linked-list-cycle-ii/description/ 1. 题目描述 2. 思路分析 如果链表存在环&#xff0c;则fast和slow会在环内相遇&#xff0c;定义相遇点到入口点的距离为X&#xff0c;定义环的长度为C&#xff0c;定义头到入口的距离为…

Swin Transformer: Hierarchical Vision Transformer using Shifted Windows

Swin Transformer: Hierarchical Vision Transformer using Shifted Windows 摘要当前的检测sota模型网络架构swin Transformer和Vision Transformer的不同之处整体架构Patch Partition结构Linear Embedding结构Swin Transformer Block结构 Patch MergingW-MSAMSA模块计算量W-M…

学术论文翻译攻略:哪家公司最靠谱?

学术论文是针对科学领域中的学术问题进行研究的理论文章&#xff0c;其目的是表述科研成果。在权威平台上发布学术论文通常要求翻译为英文文稿。那么&#xff0c;如何翻译学术论文&#xff0c;以及哪家公司在翻译学术性论文方面表现最好&#xff1f; 业内人士指出&#xff0c;学…

PSP - 扩散生成模型 (Diffusion Generative Model) 预测蛋白质结构 EigenFold 算法与环境配置

欢迎关注我的CSDN&#xff1a;https://spike.blog.csdn.net/ 本文地址&#xff1a;https://spike.blog.csdn.net/article/details/132357976 Paper: EigenFold: Generative Protein Structure Prediction with Diffusion Models EigenFold 是用于蛋白质结构预测的扩散生成模型…

Intel CPU E-core 和P-core 介绍

多年来&#xff0c;计算机 CPU 中的内核一直在以稳定的速度发展。我们最初有单核 CPU&#xff0c;但很快发展到多线程&#xff0c;然后从那里开始多核设置&#xff0c;从双核设计开始&#xff0c;然后推出四核、八核等。 英特尔的第 12 代 CPU 给我们带来了意想不到的惊喜&…

微信小程序拉起支付报: 调用支付JSAPI缺少参数: total_fee

1. 调用支付JSAPI缺少参数: total_fee 2. 检查返回给前端调起支付的参数是否正确 一开始是params.put("package", prepay_id); 回来改回params.put("package", "prepay_id"prepay_id);

LeetCode刷题——46.全排列

46. 全排列 给定一个不含重复数字的数组 nums &#xff0c;返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。 【递归实现】 func permute(nums []int) [][]int {var permutation func([]int, int, int)r : make([][]int,0)permutation func(arr []int, start int,…

【动态规划】两个数组问题

文章目录 动态规划&#xff08;两个数组问题&#xff09;1. 最长公共子序列2. 不相交的线3. 不同的子序列4. 交错字符串5. 两个字符串的最小ASCII和6. 最长重复子数组7. 通配符匹配 动态规划&#xff08;两个数组问题&#xff09; 1. 最长公共子序列 题目链接 状态表示 dp[i]…

爬虫小白也能玩转!Python爬虫中的异常处理与网络请求优化

大家好&#xff0c;我是来自爬虫世界的小编。今天&#xff0c;我要和大家分享一些关于Python爬虫中的异常处理和网络请求优化的经验。不论你是初学者还是有一定经验的爬虫程序员&#xff0c;我相信这些实用的技巧和代码示例都能为你在爬取数据的过程中带来方便和效率。 1.异常…

广告牌安全传感器,实时监测事故隐患尽在掌握

在现代城市中&#xff0c;广告牌作为商业宣传的重要媒介&#xff0c;已然成为城市中一道独特的风景线。然而&#xff0c;随着城市迅速发展&#xff0c;广告牌的安全问题也引起了大众关注。广告招牌一般悬挂于建筑物高处&#xff0c;量大面大。由于设计、材料、施工方法的缺陷&a…

VC2019调用pngquantDLL示例源码

pngquantDLL是大名鼎鼎的PNG图片压缩命令行程序pngquant的源码编译的一个DLL库文件&#xff0c;主要是方便第三方程序集成使用&#xff1b; pngquant是一个命令行实用程序和一个用于有损压缩PNG图像的库。 这种转换大大减少了文件大小(通常高达70%)&#xff0c;并保持了alpha透…

相机的位姿在地固坐标系ECEF和ENU坐标系的转换

在地球科学和导航领域&#xff0c;通常使用地心地固坐标系&#xff08;ECEF&#xff0c;Earth-Centered, Earth-Fixed&#xff09;和东北天坐标系&#xff08;ENU&#xff0c;East-North-Up&#xff09;来描述地球上的位置和姿态。如下图所示&#xff1a; ​地心地固坐标ecef和…

fastapi系列1-基础知识

学习资料 官网&#xff1a;https://fastapi.tiangolo.com/ github:https://github.com/tiangolo/fastapi 视频教程【独家新技术】从0到1学习 FastAPI 框架的所有知识点 依赖底层包&#xff1a;https://www.starlette.io/ 轻松上手Python的Web神器&#xff1a;FastAPI教程&…

ubuntu20.04共享文件夹—— /mnt/hgfs里没有共享文件夹

参考文章&#xff1a;https://blog.csdn.net/Edwinwzy/article/details/129580636 虚拟机启用共享文件夹后&#xff0c;/mnt/hgfs下面为空&#xff0c;使用 vmware-hgfsclient 查看设置的共享文件夹名字也是为空。 解决方法&#xff1a; 1. 重新安装vmware tools. 在菜单…

HarmonyOS/OpenHarmony应用开发-ArkTS语言渲染控制ForEach循环渲染

ForEach基于数组类型数据执行循环渲染。说明&#xff0c;从API version 9开始&#xff0c;该接口支持在ArkTS卡片中使用。 一、接口描述 ForEach(arr: any[], itemGenerator: (item: any, index?: number) > void,keyGenerator?: (item: any, index?: number) > stri…