Streaming local LLM with FastAPI, Llama.cpp and Langchain

题意:

使用FastAPI、Llama.cpp和Langchain流式传输本地大型语言模型

问题背景:

I have setup FastAPI with Llama.cpp and Langchain. Now I want to enable streaming in the FastAPI responses. Streaming works with Llama.cpp in my terminal, but I wasn't able to implement it with a FastAPI response.

我已经使用Llama.cpp和Langchain设置了FastAPI。现在我想在FastAPI响应中启用流式传输。在我的终端中,流式传输与Llama.cpp一起工作正常,但我无法将其与FastAPI响应一起实现。

Most tutorials focused on enabling streaming with an OpenAI model, but I am using a local LLM (quantized Mistral) with llama.cpp. I think I have to modify the Callbackhandler, but no tutorial worked. Here is my code:

大多数教程都集中在如何使用OpenAI模型启用流式传输,但我正在使用带有llama.cpp的本地大型语言模型(量化的Mistral)。我认为我需要修改Callbackhandler,但我没有找到任何可行的教程。以下是我的代码:

from fastapi import FastAPI, Request, Response
from langchain_community.llms import LlamaCpp
from langchain.callbacks.manager import CallbackManager
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
import copy
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplatemodel_path = "../modelle/mixtral-8x7b-instruct-v0.1.Q5_K_M.gguf"prompt= """
<s> [INST] Im folgenden bekommst du eine Aufgabe. Erledige diese anhand des User Inputs.### Hier die Aufgabe: ###
{typescript_string}### Hier der User Input: ###
{input}Antwort: [/INST]
"""def model_response_prompt():return PromptTemplate(template=prompt, input_variables=['input', 'typescript_string'])def build_llm(model_path, callback=None):callback_manager = CallbackManager([StreamingStdOutCallbackHandler()])#callback_manager = CallbackManager(callback)n_gpu_layers = 1 # Metal set to 1 is enough. # ausprobiert mit mehrerenn_batch = 512#1024 # Should be between 1 and n_ctx, consider the amount of RAM of your Apple Silicon Chip.llm = LlamaCpp(max_tokens =1000,n_threads = 6,model_path=model_path,temperature= 0.8,f16_kv=True,n_ctx=28000, n_gpu_layers=n_gpu_layers,n_batch=n_batch,callback_manager=callback_manager, verbose=True,top_p=0.75,top_k=40,repeat_penalty = 1.1,streaming=True,model_kwargs={'mirostat': 2,},)return llm# caching LLM
@lru_cache(maxsize=100)
def get_cached_llm():chat = build_llm(model_path)return chatchat = get_cached_llm()app = FastAPI(title="Inference API for Mistral and Mixtral",description="A simple API that use Mistral or Mixtral",version="1.0",
)app.add_middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=True,allow_methods=["*"],allow_headers=["*"],
)def bullet_point_model():          llm = build_llm(model_path=model_path)llm_chain = LLMChain(llm=llm,prompt=model_response_prompt(),verbose=True,)return llm_chain@app.get('/model_response')
async def model(question : str, prompt: str):model = bullet_point_model()res = model({"typescript_string": prompt, "input": question})result = copy.deepcopy(res)return result

In a example notebook, I am calling FastAPI like this:

在一个示例笔记本中,我像这样调用FastAPI:

import  subprocess
import urllib.parse
import shlex
query = input("Insert your bullet points here: ")
task = input("Insert the task here: ")
#Safe Encode url string
encodedquery =  urllib.parse.quote(query)
encodedtask =  urllib.parse.quote(task)
#Join the curl command textx
command = f"curl -X 'GET' 'http://127.0.0.1:8000/model_response?question={encodedquery}&prompt={encodedtask}' -H 'accept: application/json'"
print(command)
args = shlex.split(command)
process = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
print(stdout)

So with this code, getting responses from the API works. But I only see streaming in my terminal (I think this is because of the StreamingStdOutCallbackHandler. After the streaming in the terminal is complete, I am getting my FastAPI response.

所以,使用这段代码,从API获取响应是可行的。但我只能在终端中看到流式传输(我认为这是因为使用了StreamingStdOutCallbackHandler)。在终端中的流式传输完成后,我才能收到FastAPI的响应。

What do I have to change now that I can stream token by token with FastAPI and a local llama.cpp model?

我现在可以使用FastAPI和本地的llama.cpp模型逐令牌(token-by-token)地进行流式传输,那么我还需要改变什么?

问题解决:

I was doing the same and hit similar issue that FastAPI was not streaming the response even I am using the StreamingResponse API and eventually I got the following code work. There are three important part:

我之前也做了同样的事情,并遇到了类似的问题,即即使我使用了StreamingResponse API,FastAPI也没有流式传输响应。但最终我得到了以下可以工作的代码。这里有三个重要的部分:

  • Make sure using StreamingResponse to wrap an Iterator.

确保使用StreamingResponse来包装一个迭代器

  • Make sure the Iterator sends newline character \n in each streaming response.

确保迭代器在每个流式响应中发送换行符 \n

  • Make sure using streaming APIs to connect to your LLMs. For example, _client.chat function in my example is using httpx to connect to REST APIs for LLMs. If you use requests package, it won't work as it doesn't support streaming.

确保使用流式API来连接您的大型语言模型(LLMs)。例如,在我的示例中,_client.chat 函数使用 httpx 来连接到LLMs的REST API。如果您使用 requests 包,那么它将无法工作,因为 requests 不支持流式传输。

async def chat(self, request: Request):
"""
Generate a chat response using the requested model.
"""# Passing request body JSON to parameters of function _chat
# Request body follows ollama API's chat request format for now.
params = await request.json()
self.logger.debug("Request data: %s", params)chat_response = self._client.chat(**params)# Always return as streaming
if isinstance(chat_response, Iterator):def generate_response():for response in chat_response:yield json.dumps(response) + "\n"return StreamingResponse(generate_response(), media_type="application/x-ndjson")
elif chat_response is not None:return json.dumps(chat_response)

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

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

相关文章

首个“可控”人物视频生成大模型--商汤Vimi:一张照片生成一分钟视频

商汤科技又整大活了&#xff0c;只需一张照片就能生成一分钟视频&#xff01; 7月4日&#xff0c;商汤发布了业内首个面向C端用户的、“可控”人物视频生成大模型产品Vimi&#xff0c;毫不夸张的说&#xff0c;视频制作者的福音来了&#xff01; Vimi有什么特别之处&#xff1…

在postman中调试supabase的API接口

文章目录 在supabase中获取API地址和key知道它的restfull风格在postman中进行的设置1、get请求调试2、post新增用户调试3、使用patch更新数据&#xff0c;不用put&#xff01;4、delete删除数据 总结 在supabase中获取API地址和key 首先登录dashboard后台&#xff0c;首页- 右…

特征缩放介绍

目录 一、引入特征缩放&#xff1a;二、特征缩放介绍&#xff1a;三、如何实现特征缩放&#xff1a;1.分别除特征中最大值缩放到0—1&#xff1a;2.均值归一化缩放到-1—1&#xff1a;3.Z-Score归一化&#xff1a; 四、特征缩放合理范围&#xff1a; 一、引入特征缩放&#xff…

postman工具介绍

近有很多朋友表示还不太清楚postman工具有什么功能?那么接下来小编就为大家带来了postman工具的功能介绍&#xff0c;还不太清楚的朋友可以来看看哦&#xff0c;希望可以帮助大家更好地了解postman这款软件。 postman功能介绍&#xff1a; 请求调试 代理抓包 环境变量设置 导入…

Zabbix 配置 VMware 监控

Zabbix监控VMware 官方文档&#xff1a;https://www.zabbix.com/documentation/current/en/manual/vm_monitoring Zabbix 可以使用低级发现规则自动发现 VMware 虚拟机管理程序和虚拟机&#xff0c;并根据预定义的主机原型创建主机来监控它们。Zabbix 还包括用于监控 VMware …

python多线程与多进程开发实践及填坑记(2)

1. 前言 1.1. 概述 基于Flask、Pika、Multiprocessing、Thread搭建一个架构&#xff0c;完成多线程、多进程工作。具体需求如下&#xff1a; 并行计算任务&#xff1a;使用multiprocessing模块实现并行计算任务&#xff0c;提高计算效率、计算能力。消息侦听任务&#xff1a…

精准调整:数控切割机导轨的水平与垂直度校准!

滚柱导轨因其具有高承载、高精度、高稳定性和长寿命等特点&#xff0c;被广泛应用在重型设备、精密设备、自动化生产线、航空航天和半导体设备等领域。尤其是在数控切割机中的应用&#xff0c;最为广泛。 对于数控切割机来说&#xff0c;滚柱导轨的调整非常重要&#xff0c;是数…

文本编辑新境界!轻松一键,从表格中提取特定列并保存为TXT文本

在数字化办公的时代&#xff0c;表格数据的处理是每位职场人士必须面对的任务。然而&#xff0c;面对繁杂的表格数据和海量的信息&#xff0c;如何快速准确地提取我们所需的特定列内容&#xff0c;成为了许多人头疼的问题。今天&#xff0c;就让我来为大家分享一个高效编辑的新…

一对一服务,定制化小程序:NetFarmer助力企业精准触达用户

在当今这个日新月异的数字化时代&#xff0c;小程序以其独特的魅力和广泛的应用场景&#xff0c;正逐步成为企业出海战略中的璀璨明星。NetFarmer&#xff0c;作为业界领先的数字化出海服务商&#xff0c;不仅深谙HubSpot营销自动化的精髓&#xff0c;更在小程序领域展现了卓越…

mysql 字符集(character set)和排序规则(collation)

文章目录 概念1、字符集1.1、举例1.2、常见字符集 utf8 和 utf8mb4 区别1.3、字符集 使用 2、排序规则2.1、举例2.2、常见的排序规则 utf8mb4_bin 、utf8mb4_general_ci、utf8mb4_unicode_ci2.3、使用 概念 在 MySQL 中&#xff0c;字符集&#xff08;character set&#xff0…

ubuntu ceph部署

ubuntu ceph部署 参考文档&#xff1a;http://docs.ceph.org.cn/start/ 节点配置 1个mon节点&#xff0c;3个osd节点 安装前准备 安装ceph-deploy 添加 release key wget -q -O- https://download.ceph.com/keys/release.asc | sudo apt-key add -添加Ceph软件包源&…

JAVA 对象存储OSS工具类(腾讯云)

对象存储OSS工具类 import com.qcloud.cos.COSClient; import com.qcloud.cos.ClientConfig; import com.qcloud.cos.auth.BasicCOSCredentials; import com.qcloud.cos.auth.COSCredentials; import com.qcloud.cos.model.ObjectMetadata; import com.qcloud.cos.model.PutObj…

vscode 工程中 c_cpp_properties.json文件作用

在 Visual Studio Code&#xff08;VSCode&#xff09;开发C或C项目时&#xff0c;c_cpp_properties.json 文件是一个非常重要的配置文件&#xff0c;主要由微软提供的 C/C 扩展&#xff08;C/C extension from Microsoft&#xff09;使用。它主要用于配置 IntelliSense&#x…

postgrelDB的订阅的暂停 启用 强制同步 重新初始化订阅的介绍

在 PostgreSQL 中,如果你使用的是逻辑复制(Logical Replication)来实现数据库A的表1发布,数据库C订阅表1的场景,那么你可以通过以下步骤来强制同步数据库A的表1到数据库C的表1。 步骤 暂停订阅:首先暂停数据库C上的订阅,以确保在你手动修改数据时不会有新的数据同步过…

SpringBoot的在线教育平台-计算机毕业设计源码68562

摘要 在数字化时代&#xff0c;随着信息技术的飞速发展&#xff0c;在线教育已成为教育领域的重要趋势。为了满足广大学习者对于灵活、高效学习方式的需求&#xff0c;基于Spring Boot的在线教育平台应运而生。Spring Boot以其快速开发、简便部署以及良好的可扩展性&#xff0c…

LeetCode 算法:二叉树的最近公共祖先 III c++

原题链接&#x1f517;&#xff1a;二叉树的最近公共祖先 难度&#xff1a;中等⭐️⭐️ 题目 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。 百度百科中最近公共祖先的定义为&#xff1a;“对于有根树 T 的两个节点 p、q&#xff0c;最近公共祖先表示为一个节点…

扫地机器人如何利用图算法来进行避障策略和优化清扫路径的?

前言 扫地机器人是现代家庭中最常见的智能设备。其基本的核心组件由主控系统&#xff08;大脑&#xff09;、传感器等控制系统&#xff08;感知系统&#xff09;、动力供应系统&#xff08;心脏&#xff09;、清扫系统&#xff08;四肢&#xff09;组成。 扫地机器人的智能、高…

嵌入式UI开发-lvgl+wsl2+vscode系列:6、布局(Layouts)

一、前言 这节总结一下整体页面的布局方式&#xff0c;lvgl的布局方式比较少&#xff0c;目前只有flex和grid两大类布局&#xff0c;即弹性布局和网格布局&#xff0c;弹性布局一般就是指定相对位置&#xff0c;网格布局就是将整个页面划分为网格状&#xff0c;我们做其它的UI…

Typescript window.localStorage 存储 Obj Value区别

window.localStorage.setItem(UserC, JSON.stringify(userC)) const userC JSON.parse(window.localStorage.getItem(UserC) || {}) 不能获得UserC&#xff0c;所有保存的时候需要存储value&#xff0c;而不是对象。 {"__v_isShallow":false, "__v_isRef&quo…

2-3 图像分类数据集

MNIST数据集是图像分类任务中广泛使用的数据集之一&#xff0c;但作为基准数据集过于简单&#xff0c;我们将使用类似但更复杂的Fashion-MNIST数据集。 %matplotlib inline import torch import torchvision # pytorch模型关于计算机视觉模型实现的一个库 from torch.utils i…