Litestar GET function blocks OpenAI

embedded/2024/9/24 6:09:51/
aidu_pl">

题意:Litestar GET 函数阻塞 OpenAI

问题背景:

When I transfer function to litestar, it suddenly stops OpenAI from returning a completion. I can print to console every declared variable except answer:

当我将函数传递给 litestar 时,它突然阻止了 OpenAI 返回完成结果。我可以打印到控制台中声明的每个变量,除了答案之外。

python">from dotenv import load_dotenv
from litestar import Controller, Litestar, get
from litestar.types import ControllerRouterHandlerimport os
import pinecone
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.vectorstores import Pinecone
from dotenv import load_dotenv
import openai__all__ = ("index","support",
)load_dotenv()embeddings = OpenAIEmbeddings()@get("/")
async def index() -> str:return "Тестовый запрос выполнен. Чтобы получить ответ, воспользуйтесь командой /support/{вопрос%20вопрос}."@get("/support/{question:str}")
async def get_answer(question: str) -> str:pinecone.init(api_key=os.getenv("PINECONE_API_KEY"),environment=os.environ.get('PINECONE_ENVIRONMENT'),)index_name = os.environ.get('PINECONE_INDEX_NAME')k = 2docsearch = Pinecone.from_existing_index(index_name, embeddings)res = docsearch.similarity_search_with_score(question, k=k)prompt = f'''Use text below to compile an answer:{[x for x in res]}'''completion = openai.Completion.create(model="text-davinci-003",prompt=prompt,max_tokens = 1000)answer = completion.choices[0].textreturn {"answer": answer}routes: list[ControllerRouterHandler] = [get_answer
]app = Litestar([index, get_answer])

Though bare OpenAI script works fine:        尽管纯 OpenAI 脚本工作正常

python">import os
import pinecone
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.vectorstores import Pinecone
from dotenv import load_dotenv
import openaiload_dotenv()# Подготовим эмбеддинги
embeddings = OpenAIEmbeddings()pinecone.init(api_key=os.getenv("PINECONE_API_KEY"),environment=os.environ.get('PINECONE_ENVIRONMENT'),
)index_name = os.environ.get('PINECONE_INDEX_NAME')query = input("Enter your question: ")
k = 2docsearch = Pinecone.from_existing_index(index_name, embeddings)
res = docsearch.similarity_search_with_score(query, k=k)prompt = f'''
Use text below to compile an answer:
{[x for x in res]}
'''completion = openai.Completion.create(model="text-davinci-003",prompt=prompt,max_tokens = 1000
)print(completion.choices[0].text)

pip freeze:        pip freeze 命令得到的结果

python">litestar==2.2.1
openai==0.27.8
pinecone-client==2.2.2

Litestar keeps showing 500 Internal Server Error without details. index() works fine. What can I do to resolve this issue?

Litestar 一直显示 500 内部服务器错误但没有详细信息。index() 函数工作正常。我该如何解决这个问题?

问题解决:

Here is a minimal example using Litestar that has the same problem you would face.

这是一个使用 Litestar 的最小示例,它会遇到与你相同的问题。

python">from litestar import Litestar, get@get()
async def get_answer() -> str:return {'hello': 'world'}app = Litestar([get_answer])

Making a GET request to localhost:8000 returns

向 localhost:8000 发送 GET 请求返回...

python">{"status_code":500,"detail":"Internal Server Error"}

If you turn on debug mode like so app = Litestar([get_answer], debug=True) the following error is shown when you make the same request.

如果你像这样开启调试模式 app = Litestar([get_answer], debug=True),当你发送相同的请求时,会显示以下错误。

python">500: Unable to serialize response content

This is because you have mentioned the return type as str in async def get_answer(question: str) -> str: but in your actual code you are returning a dict. Litestar uses the return type of the function to serialize the data. Converting a str to dict fails.

这是因为你在 async def get_answer(question: str) -> str: 中将返回类型指定为 str,但在你的实际代码中你却返回了一个 dict。Litestar 使用函数的返回类型来序列化数据。将 str 转换为 dict 失败了。

In your example index works fine because the return type and the actual return value are the same str.

在你的例子中,index 函数工作正常,因为返回类型和实际返回值都是相同的 str(字符串)。

The fix is to use the correct return type for get_answerdict[str, str] or even plaidict is enough.

修复方法是使用正确的返回类型给 get_answer。使用 dict[str, str] 或者简单的 dict 就足够了

python">from litestar import Litestar, get@get()
async def get_answer() -> dict[str, str]:return {'hello': 'world'}app = Litestar([get_answer])

If you are on 3.8, you can use typing.Dict instead of dict.

如果你使用的是 Python 3.8 或更高版本,你可以使用 typing.Dict 而不是 dict 来明确指定字典的键和值的类型

python">from typing import Dict
from litestar import Litestar, get@get()
async def get_answer() -> Dict:return {'hello': 'world'}app = Litestar([get_answer])

PS:

Though bare OpenAI script works fine:   尽管直接使用 OpenAI 的脚本也能正常工作

This is why I removed the OpenAI parts and only focused on the litestar ones. If you have an error in that you would still get a 500 error, you will have to fix that separately.

这就是为什么我去掉了 OpenAI 的部分,只专注于 litestar 的部分。如果你在那里有错误,你仍然会得到一个 500 错误,你需要单独修复它。


http://www.ppmy.cn/embedded/93653.html

相关文章

LabView多界面子VI同时运行

有朋友问我LabView如何调用多个界面VI同时工作,其实说穿了很简单,我们我们平时调用驱动、算法、控件等等时都相当于在同时调用多个子VI工作,只不过多了个界面而已。 只有几点需要注意: 1、每个子VI处于不同的线程; 2、…

【Docker】Docker Container(容器)

一、什么是容器 通俗地讲,容器是镜像的运行实体。镜像是静态的只读文件,而容器带有运行时需要的可写文件层,并且容器中的进程属于运行状态。即容器运行着真正的应用进程。容器有初建、运行、停止、暂停和删除五种状态。 虽然容器的本质是主…

[windows10]win10永久禁用系统自动更新操作方法

WinR打开运行 输入regedit打开注册表 点击确定打开注册表 按照如下路径找到UX 计算机\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WindowsUpdate\UX\Settings 在空白处点击鼠标右键,新建选择DWORD,然后重命名为FlightSettingsMaxPauseDays 双击FlightSet…

c++的类和对象(中):默认成员函数与运算符重载(重难点!!)

前言 Hello, 小伙伴们,我们今天继续c的学习,我们上期有介绍到c的部分特性,以及一些区别于c语言的地方,今天我们将继续深入了解c的类和对象,探索c的奥秘。 好,废话不多说,开始我们今天的学习。…

【深度学习】创建和训练Transformer神经网络模型,将葡萄牙语翻译成英语

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录 前言1. 安装2. 数据处理2.1 下载数据集2.2 设置标记器2.3 使用tf.data设置数据管道 3. 测试数据集4. 定义组件4.1 嵌入和位置编码层4.2 添加并规范化4.3 基础注意力…

cocospods 安装与迁移到离线打包机上

背景: 一个没有网络的window电脑上,window电脑上有mac的虚拟机,需要进行离线打包。 自己的mac上安装cocoapods 然后直接拷贝到没有网的mac虚拟机上 自己mac上正常安装 自己的mac电脑上安装cocoapod 下面是官网 https://cocoapods.org/ 官网…

Unity Audio

这章练习将介绍在unity中创建 audio(音频)的工具,培养的技能将帮助创建引人入胜的音频音景。完成本次学习后,能够使用 Unity 中的所有主要音频组件,为各种不同体验创建音频效果。 音频处理工具: Audacity…

2024年,最新前端趋势

随着技术的不断发展,前端开发领域在2024年迎来了新的趋势和挑战。对于开发者来说,紧跟这些趋势不仅能提升技术水平,还能在激烈的市场竞争中脱颖而出。今天,我想向大家介绍一款在这波趋势中脱颖而出的开发神器——MemFire Cloud。这…