@@ -278,6 +278,80 @@ es.addEventListener('ping', pingListener);
278278
279279` MyCustomEvents ` in ` EventSourceEvent ` is optional, but it's recommended to use it in order to have better type checking.
280280
281+ ## 🚀 Usage with ChatGPT
282+
283+ If you want to use ChatGPT with React Native, you can use the following example:
284+
285+ ``` typescript
286+ import { useEffect , useState } from " react" ;
287+ import { Text , View } from " react-native" ;
288+ import EventSource from " react-native-sse" ;
289+
290+ const OpenAIToken = ' [Your OpenAI token]' ;
291+
292+ export default function App() {
293+ const [text, setText] = useState <string >(" Loading..." );
294+
295+ useEffect (() => {
296+ const es = new EventSource (
297+ " https://api.openai.com/v1/chat/completions" ,
298+ {
299+ headers: {
300+ " Content-Type" : " application/json" ,
301+ Authorization: ` Bearer ${OpenAIToken } ` ,
302+ },
303+ method: " POST" ,
304+ // Remember to read the OpenAI API documentation to set the correct body
305+ body: JSON .stringify ({
306+ model: " gpt-3.5-turbo-0125" ,
307+ messages: [
308+ {
309+ role: " system" ,
310+ content: " You are a helpful assistant." ,
311+ },
312+ {
313+ role: " user" ,
314+ content: " What is the meaning of life?" ,
315+ },
316+ ],
317+ max_tokens: 600 ,
318+ n: 1 ,
319+ temperature: 0.7 ,
320+ stream: true ,
321+ }),
322+ pollingInterval: 0 , // Remember to set pollingInterval to 0 to disable reconnections
323+ }
324+ );
325+
326+ es .addEventListener (" open" , () => {
327+ setText (" " );
328+ });
329+
330+ es .addEventListener (" message" , (event ) => {
331+ if (event .data !== " [DONE]" ) {
332+ const data = JSON .parse (event .data );
333+
334+ if (data .choices [0 ].delta .content !== undefined ) {
335+ setText ((text ) => text + data .choices [0 ].delta .content );
336+ }
337+ }
338+ });
339+
340+ return () => {
341+ es .removeAllEventListeners ();
342+ es .close ();
343+ };
344+ }, []);
345+
346+ return (
347+ <View >
348+ <Text >{text }< / Text >
349+ < / View >
350+ );
351+ }
352+ ```
353+
354+
281355---
282356
283357Custom events always emit result with following interface:
0 commit comments