Skip to content

Commit 99dd919

Browse files
committed
docs: Add ChatGPT example to README. Update keywords
1 parent 2473951 commit 99dd919

File tree

2 files changed

+78
-1
lines changed

2 files changed

+78
-1
lines changed

README.md

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

283357
Custom events always emit result with following interface:

package.json

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,12 @@
1212
},
1313
"keywords": [
1414
"react-native",
15+
"expo",
1516
"event-source",
1617
"sse",
1718
"server-sent-events",
19+
"chatgpt",
20+
"stream",
1821
"ios",
1922
"android"
2023
],
@@ -24,4 +27,4 @@
2427
"url": "https://github.com/binaryminds/react-native-sse/issues"
2528
},
2629
"homepage": "https://github.com/binaryminds/react-native-sse#readme"
27-
}
30+
}

0 commit comments

Comments
 (0)