5

I want to use Chat GPT Turbo api directly in react native (expo) with word by word stream here is working example without stream

  fetch(`https://api.openai.com/v1/chat/completions`, {
  body: JSON.stringify({
    model: 'gpt-3.5-turbo',
    messages: [{ role: 'user', content: 'hello' }],
    temperature: 0.3,
    max_tokens: 2000,
  }),
  method: 'POST',
  headers: {
    'content-type': 'application/json',
    Authorization: 'Bearer ' + API_KEY,
  },
}).then((response) => {
  console.log(response); //If you want to check the full response
  if (response.ok) {
    response.json().then((json) => {
      console.log(json); //If you want to check the response as JSON
      console.log(json.choices[0].message.content); //HERE'S THE CHATBOT'S RESPONSE
    });
  }
});

what can i change to stream data word by word

Ibad Ur Rehman
  • 696
  • 1
  • 9
  • 16

2 Answers2

2

OpenAI APIs rely on SSE (Server Side Events) to stream the response back to you. If you pass the stream parameter in your API request, you will receive chunks of data when they are calculated by OpenAI. This creates the illusion of a real-time response that mimics someone typing.

The hardest part to figure out might be how to connect your frontend with your backend. Every-time the backend receives a new chunk you want to display it in the frontend.

I created a simple NextJs project on Replit that demonstrates just that. Live demo

you will need to install better-sse package

npm install better-sse

Server side In an API route file

import {createSession} from "better-sse";

const session = await createSession(req, res);
      if (!session.isConnected) throw new Error('Not connected');

const { data } = await openai.createCompletion({
  model: 'text-davinci-003',
  n: 1,
  max_tokens: 2048,
  temperature: 0.3,
  stream: true,
  prompt: `CHANGE TO YOUR OWN PROMPTS`
}, {
  timeout: 1000 * 60 * 2,
  responseType: 'stream'
});

//what to do when receiving data from the API
data.on('data', text => {
  const lines = text.toString().split('\n').filter(line => line.trim() !== '');
  for (const line of lines) {
    const message = line.replace(/^data: /, '');
    if (message === '[DONE]') { //OpenAI sends [DONE] to say it's over
      session.push('DONE', 'error');
      return;
    }
    try {
      const { choices } = JSON.parse(message);
      session.push({text:choices[0].text});
    } catch (err) {
      console.log(err);
    }
  }
});

//connection is close
data.on('close', () => { 
  console.log("close")
  res.end();
});

data.on('error', (err) => {
  console.error(err);
});

On your front end you can now call this API route

let [result, setResult] = useState("");

//create the sse connection
const sse = new EventSource(`/api/completion?prompt=${inputPrompt}`);

//listen to incoming messages
sse.addEventListener("message", ({ data }) => {
  let msgObj = JSON.parse(data)
  setResult((r) => r + msgObj.text)
});

Hope this makes sense and help others with similar issue.

yname
  • 2,189
  • 13
  • 23
picsoung
  • 6,314
  • 1
  • 18
  • 35
  • I might change that to gpt3-turbo or gpt-4 if you have the access. But the request format would change for that. – Anshuman Kumar Apr 01 '23 at 10:54
  • The model currently set is for GPT3, not ChatGPT. – Anshuman Kumar Apr 01 '23 at 10:56
  • sse is not work in react native – Ibad Ur Rehman Apr 01 '23 at 12:19
  • This is a separate codebase that you can set up on any platform of your choice that will interact with ChatGPT for you and you can use it to stream responses to your server. – Anshuman Kumar Apr 02 '23 at 12:29
  • There are a few workarounds to support SSE in React Native. Did you try the following libraries? https://www.npmjs.com/package/react-native-sse there is also a discussion on the react-native repo https://github.com/facebook/react-native/issues/28835 with people that successfully implemented it. – picsoung Apr 03 '23 at 02:14
  • @AnshumanKumar if you implement it in react native can you share code? – Ibad Ur Rehman Apr 03 '23 at 09:46
  • You cant change model to gtp3 or gpt4 with this rest api. This is incorrect answer – rendom Apr 20 '23 at 06:04
  • @rendom you can change it on the server side part on that line `model: 'text-davinci-003` – picsoung Apr 26 '23 at 01:45
  • How to detect SSE in chrome dev tools? I don't see any entry for response in network tab when the response is being streamed to browser, even though i have selected 'All' in the network tab. – darKnight Aug 29 '23 at 17:56
0

Visit this GitHub repository: https://github.com/jonrhall/openai-streaming-hooks. I recommend exploring this library as it offers React hooks that function solely on the client-side, requiring no server support.

Royal_lobster
  • 117
  • 1
  • 7
  • Its not working in react native – Ibad Ur Rehman Apr 03 '23 at 09:47
  • I didn't downvote, but would it not be a security risk exposing the API key on the client side? The better approach IMO would be setting up a proxy like @picsoung has, but that wouldcome at the cost of some added latency. – Anshuman Kumar Apr 06 '23 at 01:42
  • True, for protecting API key request should be proxied from server. The better application with this library would be to processing info from user's open ai key where it is ok to expose API to client since it belongs to user – Royal_lobster Apr 07 '23 at 15:49
  • Yes, that depends on the needs of the application. In order to have the user's OpenAI key, you would need to connect with their OpenAI account. If you are trying to build a ChatGPT clone without any login (as some people are nowadays), then I wouldn't reccomend this. – Anshuman Kumar Apr 10 '23 at 09:48
  • 1
    Connecting OpenAI account only needs API key. True that there are many apps now a days which allows users to use their own API key so that they pay the least depending on their use. I am building a free chrome extension that allows users to use chat gpt in any website interacting with web content. my self using the library for this case so i don't have to set up infra to handle requests with open ai. – Royal_lobster Apr 12 '23 at 03:51
  • I think this library might be useful to you as well, its a very simple React hook, that does exactly what you're looking for: https://github.com/XD2Sketch/react-chat-stream – Kevin Goedecke Jul 15 '23 at 12:21