我正在开发一个React Native聊天应用程序,我想使用openai api来实现自动回复。
openai 的 api 提供了流,但它使用 SSE,这在 React Native 中似乎效果不佳。
有什么方法可以在我的项目中使用文本流吗?
我已经尝试了here提到的大部分建议和其他解决方案,但它们没有按预期工作。
openai-streams
、react-chat-stream
、openai-streaming-hooks
等库。然而,这些库不能在 React Native 中工作。@async-util/fetch
、react-native-fetch-api
等库。但他们也没有工作。react-native-event-source
、react-native-sse
等套餐。但是,我仍然遇到功能无法按预期工作的问题。我不确定问题是否出在我的实施或软件包上。我现在很困惑。是否有任何指导或工作示例来实现流响应?
这里有两个我认为最合适的解决方案,并将继续尝试,请告诉我是否有任何我应该考虑的替代方法或对这些方法的改进,我将非常感谢您的建议。
感谢您的宝贵时间。
回复zoran404:
是的,我已经尝试过。添加
react-native-polyfill-globals/auto
是因为没有它会引发错误 Property 'TextEncoder' doesn't exist
。这是我的方法,我真的不确定。
import 'react-native-polyfill-globals/auto'
import { fetch } from 'react-native-fetch-api'
async function fetchStreamMessage() {
const url = 'https://api.openai.com/v1/chat/completions'
fetch(url, {
reactNative: { textStreaming: true },
method: 'POST',
headers: {
Authorization: `Bearer ${OPENAI_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
messages: [{ role: 'user', content: 'Tell me a joke' }],
model: 'gpt-4',
stream: true
})
})
.then((response: Response) => response.body)
.then((body: ReadableStream) => {
const reader = body.getReader()
console.log(reader)
})
}
一旦从 body.getReader() 获得了读取器,您就需要一个循环来读取流块。之后
const reader = body.getReader()
const reader = body.getReader();
let done, value;
while (!done) {
({ done, value } = await reader.read());
if (!done) {
const chunk = new TextDecoder().decode(value);
console.log(chunk);
}
}
console.log('Streaming complete.');