ESC
React Native Starter AI logo
Menu
On this page

Features > ChatGPT Integration

OpenAI with ChatGPT integration comes with React Native Starter AI out of the box for you! We are using ChatGPT in AI Chatbot and Image to Text generation flows. You can check how it is being used in AI App Screens and AI Services docs. Here in this document, we are going to cover how you can change the integration code depending on your needs!

Chat Completion

ChatGPT chat completion features is widely used for in cases of chat bot creation. You just need to proceed to react-native-starter-backend/functions/src/prompts folder and change however you want your chatbot to behave. In the default setup, the chat assistant comes as an expert dietician with the prompt below:


react-native-starter-backend/functions/src/prompts
1export const chatInitialSystemPrompt = 2`You are an helpful and expert dietitian named Lisa. We have created an user profile based on 3the user's body profile and dietary preferences and restrictions. Based on this profle, you will answer questions about the user's specific 4diet, health information.`; 5 6export const chatInitialPromptToCreateWelcome = (userProperties: JSON) => ` 7I want you to say a warm hello to the user by introducing yourself and also what type of questions you can answer for the user. The user's 8profile information is given as a JSON as this: ${JSON.stringify(userProperties)}. Please be specific about the examples of the questions that 9the user may ask. and also call the user as 'you'. And please also keep the word count under 150. 10`;

As mentioned in AI Services docs, your OpenAI API Key is stored securely on the Firebase backend; so you don't need to worry about any security issues such as OpenAI API Key being exposed etc.


After you change the prompts, you chatbot will instanly start to be in the role of what you described in your prompts. The chat endpoints are ready to use like below:

react-native-starter-backend/functions/src/index.ts
1const messages = [ 2 { role: "system", content: chatInitialSystemPrompt }, 3 { role: "user", content: chatInitialPromptToCreateWelcome(userInfo) }, 4];

react-native-starter-backend/functions/src/index.ts
1 2 .... 3 const body = JSON.stringify({ 4 model: "gpt-4", // gpt-4, gpt-3.5-turbo, etc 5 messages, // array of message objects with role and content. 6 max_tokens: max, // max tokens to generate in the response 7 temperature: temp, // temperature of the response, higher is more random 8 user: userId, // user id 9 }); 10 11 const options = { 12 headers: { 13 Authorization: `Bearer ${process.env.OPENAI_API_KEY}`, // place in your API key here or use environment variables 14 "Content-Type": "application/json", 15 }, 16 }; 17 18 try { 19 // Custom retry delay 20 axiosRetry(axios, { 21 retryDelay: (retryCount) => { 22 return retryCount * 1; 23 }, 24 retries: 15, 25 }); 26 27 const res = await axios.post(url, body, options); 28 29 const answer = res.data.choices[0].message.content; 30 const usage = res?.data?.usage; 31 32 console.log(">>> " + answer); 33 console.log( 34 "TOKENS USED: " + 35 usage?.total_tokens + 36 " (prompt: " + 37 usage?.prompt_tokens + 38 " / response: " + 39 usage?.completion_tokens + 40 ")" 41 ); 42 console.log(" 43"); 44 45 return answer; 46 } catch (e) { 47 console.error("GPT Error: " + e?.response?.status, e?.response?.data); 48 return null; 49 } 50}; 51 52

Getting JSON Output from ChatGpt

Getting JSON output from ChatGPT API can be needed in many scenarios such as React Native Starter AI's Image to Text AI Generation Flow. Here we are going to explain how you can achieve this result.


There are actually 2 ways of achieving JSON output from ChatGpt API. The first one is to write a prompt to force ChatGPT to give you JSON output and the second is to use function calling feature of ChatGPT. Both actually works but function calling feature is a better practice.


Using Prompt to get JSON output from ChatGPT

As you can imagine, we are (politely) asking ChatGPT to give us a JSON output by giving a JSON example that we wish for in the prompt like below:

react-native-starter-backend/functions/src/index.ts
1[ 2 { 3 role: "user", 4 content: [ 5 { 6 type: "text", 7 text: `tell me the nutrition info in this food. The output should be as below strictly without any additional text: 8 9 { 10 "carbohydrates": "10", 11 "calories": "100", 12 "protein": "100", 13 "fats": "100" 14 } 15 `, 16 }, 17 { 18 type: "image_url", 19 image_url: { 20 url: `data:image/png;base64,${inputImg}`, 21 }, 22 }, 23 ], 24 }, 25],

And right after that, we are checking if the output is a valid JSON and execute it again if it is not by the code below:


react-native-starter-backend/functions/src/index.ts
1// Check if the returned object can be converted into JSON; if not retry the request again. 2const hitGptForJson: () => any = async () => { 3 const result = await axios.request(getOpenAIBodyConfig(aiRequestBody)); 4 try { 5 const convertedJson = JSON.parse( 6 result?.data?.choices?.[0]?.message?.content 7 ); 8 return convertedJson; 9 } catch (e) { 10 return hitGptForJson(); 11 } 12};

Using Function Calling of ChatGPT to get JSON Output

OpenAI announced a new feature called function calling to prevent the approach of trying to get JSON output by prompting. This can be explored further from the Official Docs of ChatGPT. Here in React Native Starter AI, we will also show how to use that function calling feature to get JSON outputs for your mobile application. It is pretty straightforward like below:


react-native-starter-backend/functions/src/prompts
1 2 3 const tools = [ // List of available functions, called tools. 4 { 5 "type": "function", 6 "function": { 7 "name": "get_current_weather", 8 "description": "Get the current weather in a given location", 9 "parameters": { 10 "type": "object", 11 "properties": { 12 "location": { 13 "type": "string", 14 "description": "The city and state, e.g. San Francisco, CA", 15 }, 16 "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, 17 }, 18 "required": ["location"], 19 }, 20 } 21 } 22 ]; 23 24 const body = JSON.stringify({ 25 model: "gpt-3.5-turbo", // gpt-4, gpt-3.5-turbo, etc 26 messages, // array of message objects with role and content. e.g. [{role: "user", content: "What's the weather in San Francisco?"}] 27 max_tokens: max, // max tokens to generate in the response 28 temperature: temp, // temperature of the response, higher is more random 29 tools: tools, // array of available function objects 30 tool_choice: "auto", // let ChatGPT decide when and which function to call 31 }); 32 33 const options = { 34 headers: { 35 Authorization: `Bearer ${process.env.OPENAI_API_KEY}`, // place in your API key here or use environment variables 36 "Content-Type": "application/json", 37 }, 38 }; 39 40 try { 41 // Custom retry delay 42 axiosRetry(axios, { 43 retryDelay: (retryCount) => { 44 return retryCount * 1; 45 }, 46 retries: 15, 47 }); 48 49 const res = await axios.post(url, body, options); 50 51 const toolCalls = res.data.choices[0].message.tool_calls; 52 const usage = res?.data?.usage; 53 54 console.log( 55 "TOKENS USED: " + 56 usage?.total_tokens + 57 " (prompt: " + 58 usage?.prompt_tokens + 59 " / response: " + 60 usage?.completion_tokens + 61 ")" 62 ); 63 64 return toolCalls; 65 } catch (e) { 66 console.error("GPT Error: " + e?.response?.status, e?.response?.data); 67 return null; 68 } 69};