当前位置: 首页 > news >正文

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)

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 【vueUse库Component模块各函数简介及使用方法--上篇】
  • 中英双语介绍英国伟大的作家:查尔斯·狄更斯(Charles Dickens)
  • A61 STM32_HAL库函数 之 TIM扩展驱动 -- C -- 所有函数的介绍及使用
  • ClickHouse 介绍:深度解析高性能列式数据库的核心优势
  • 微信小程序:图片转icon
  • Zabbix钉钉机器人告警
  • 微信小程序订单发货管理接入
  • 跨越语言的界限:Vue I18n 国际化指南
  • 在x86/amd64的机器上使用Docker运行arm64v8/ubuntu并安装ROS1
  • Unity游戏帧率查看软件Fraps
  • taoCMS v3.0.2 任意文件读取漏洞(CVE-2022-23316)
  • 绝区贰--及时优化降低 LLM 成本和延迟
  • 计算机网络面试常见题目(一)
  • vue3使用pinia中的actions,需要调用接口的话
  • 第三十章 方法大全(Python)
  • __proto__ 和 prototype的关系
  • Cumulo 的 ClojureScript 模块已经成型
  • iOS仿今日头条、壁纸应用、筛选分类、三方微博、颜色填充等源码
  • JavaScript设计模式之工厂模式
  • java中具有继承关系的类及其对象初始化顺序
  • JDK9: 集成 Jshell 和 Maven 项目.
  • Meteor的表单提交:Form
  • Netty 框架总结「ChannelHandler 及 EventLoop」
  • Promise面试题,控制异步流程
  • Terraform入门 - 1. 安装Terraform
  • WordPress 获取当前文章下的所有附件/获取指定ID文章的附件(图片、文件、视频)...
  • 安卓应用性能调试和优化经验分享
  • 飞驰在Mesos的涡轮引擎上
  • 简析gRPC client 连接管理
  • 快速构建spring-cloud+sleuth+rabbit+ zipkin+es+kibana+grafana日志跟踪平台
  • 那些年我们用过的显示性能指标
  • 盘点那些不知名却常用的 Git 操作
  • 如何打造100亿SDK累计覆盖量的大数据系统
  • 小程序、APP Store 需要的 SSL 证书是个什么东西?
  • 一个完整Java Web项目背后的密码
  • 由插件封装引出的一丢丢思考
  • 带你开发类似Pokemon Go的AR游戏
  • 专访Pony.ai 楼天城:自动驾驶已经走过了“从0到1”,“规模”是行业的分水岭| 自动驾驶这十年 ...
  • ​RecSys 2022 | 面向人岗匹配的双向选择偏好建模
  • "无招胜有招"nbsp;史上最全的互…
  • # C++之functional库用法整理
  • # 详解 JS 中的事件循环、宏/微任务、Primise对象、定时器函数,以及其在工作中的应用和注意事项
  • #if #elif #endif
  • (21)起落架/可伸缩相机支架
  • (6)添加vue-cookie
  • (a /b)*c的值
  • (javascript)再说document.body.scrollTop的使用问题
  • (NO.00004)iOS实现打砖块游戏(十二):伸缩自如,我是如意金箍棒(上)!
  • (Repost) Getting Genode with TrustZone on the i.MX
  • (附源码)ssm教材管理系统 毕业设计 011229
  • (函数)颠倒字符串顺序(C语言)
  • (机器学习的矩阵)(向量、矩阵与多元线性回归)
  • (论文阅读32/100)Flowing convnets for human pose estimation in videos
  • (每日持续更新)信息系统项目管理(第四版)(高级项目管理)考试重点整理 第13章 项目资源管理(七)
  • (七)理解angular中的module和injector,即依赖注入