To use the OpenAI API for streaming completions, use a POST method, set the Content-Type to application/json, and include stream: true in the body. Set pollingInterval: 0 to prevent the client from attempting to reconnect after the stream finishes.
import { useEffect, useState } from "react";
import { Text, View } from "react-native";
import EventSource from "react-native-sse";
const OpenAIToken = '[Your OpenAI token]';
export default function App() {
const [text, setText] = useState<string>("Loading...");
useEffect(() => {
const es = new EventSource(
"https://api.openai.com/v1/chat/completions",
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${OpenAIToken}`,
},
method: "POST",
body: JSON.stringify({
model: "gpt-3.5-turbo-0125",
messages: [{ role: "user", content: "What is the meaning of life?" }],
stream: true,
}),
pollingInterval: 0, // Disable reconnections
}
);
es.addEventListener("message", (event) => {
if (event.data !== "[DONE]") {
const data = JSON.parse(event.data);
if (data.choices[0].delta.content !== undefined) {
setText((prev) => prev + data.choices[0].delta.content);
}
}
});
return () => es.close();
}, []);
return (
<View><Text>{text}</Text></View>
);
}