diff --git a/README.md b/README.md index c11b903..3b4fc44 100644 --- a/README.md +++ b/README.md @@ -278,6 +278,80 @@ es.addEventListener('ping', pingListener); `MyCustomEvents` in `EventSourceEvent` is optional, but it's recommended to use it in order to have better type checking. +## 🚀 Usage with ChatGPT + +If you want to use ChatGPT with React Native, you can use the following example: + +```typescript +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("Loading..."); + + useEffect(() => { + const es = new EventSource( + "https://api.openai.com/v1/chat/completions", + { + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${OpenAIToken}`, + }, + method: "POST", + // Remember to read the OpenAI API documentation to set the correct body + body: JSON.stringify({ + model: "gpt-3.5-turbo-0125", + messages: [ + { + role: "system", + content: "You are a helpful assistant.", + }, + { + role: "user", + content: "What is the meaning of life?", + }, + ], + max_tokens: 600, + n: 1, + temperature: 0.7, + stream: true, + }), + pollingInterval: 0, // Remember to set pollingInterval to 0 to disable reconnections + } + ); + + es.addEventListener("open", () => { + setText(""); + }); + + es.addEventListener("message", (event) => { + if (event.data !== "[DONE]") { + const data = JSON.parse(event.data); + + if (data.choices[0].delta.content !== undefined) { + setText((text) => text + data.choices[0].delta.content); + } + } + }); + + return () => { + es.removeAllEventListeners(); + es.close(); + }; + }, []); + + return ( + + {text} + + ); +} +``` + + --- Custom events always emit result with following interface: diff --git a/package.json b/package.json index 7dbcf45..603a986 100644 --- a/package.json +++ b/package.json @@ -12,9 +12,12 @@ }, "keywords": [ "react-native", + "expo", "event-source", "sse", "server-sent-events", + "chatgpt", + "stream", "ios", "android" ], @@ -24,4 +27,4 @@ "url": "https://github.com/binaryminds/react-native-sse/issues" }, "homepage": "https://github.com/binaryminds/react-native-sse#readme" -} +} \ No newline at end of file