Integrating ChatGPT and Gemini into React Native: A Complete Guide

By integrating ChatGpt and Gemini models into your React Native apps, you can create engaging chatbots, personalize content, and automate web interactions. This guide explores how to leverage the strengths of ChatGPT and Gemini within your React Native projects.

Introduction to ChatGPT and Gemini

ChatGPT: It was developed by OpenAI and released in November 2022. ChatGPT is a state-of-the-art conversational AI model capable of generating human-like responses in natural language. It can be fine-tuned for specific tasks, such as customer support, content creation, or personal assistants.

Gemini: It was developed by Google and released in February 2023. Initially, it’s called Bard but later Google rebranded it and upgraded it to Gemini in December 2023. It’s an advanced AI model specifically designed for generating web browsing interactions. It can simulate a user’s browsing behavior and generate realistic sequences of clicks and queries, making it ideal for applications that require automated web browsing capabilities.

Integrating ChatGPT

Step 1: Install the Axios package for ChatGpt API calls.

npm install axios

Step 2: Create a new API Key from here.

Step 3: From the OpenAI platform, get API documentation to use API.

ChatGPT Integration Example

import React, {useState, useRef} from 'react';
import {
View,
Text,
TouchableOpacity,
SafeAreaView,
TextInput,
ScrollView,
StyleSheet,
ActivityIndicator,
Alert,
Image,
} from 'react-native';
import axios from 'axios';

const API_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX';

export default function Chatgpt({handleBackPress}) {
const scrollRef = useRef();
const [messages, setMessages] = useState([]);
const [query, setQuery] = useState('');
const [loading, setLoading] = useState(false);

const handleTextCompletion = async () => {
const userMessage = {role: 'user', content: query};
setMessages([...messages, userMessage]);
try {
const response = await axios.post(
'https://api.openai.com/v1/chat/completions',
{
model: 'gpt-3.5-turbo',
messages: [...messages, userMessage],
},
{
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + API_KEY,
},
},
);
const botMessage = {
role: 'bot',
content: response.data.choices[0].message.content,
};
setQuery('');
setMessages([...messages, userMessage, botMessage]);
setLoading(false);
} catch (error) {
setLoading(false);
Alert.alert('Error', error);
}
};

const handleSend = async () => {
setLoading(true);
handleTextCompletion();
};

return (
<SafeAreaView style={styles.mainContainer}>
<View style={styles.container1}>
<View style={styles.header}>
<TouchableOpacity
style={styles.backIconContainer}
onPress={handleBackPress}>
<Image
source={require('./back.png')}
style={styles.backIcon}
resizeMode="contain"
/>
</TouchableOpacity>
<View style={styles.headingContainer}>
<Text style={styles.heading}>Chatgpt</Text>
</View>
</View>

<ScrollView ref={scrollRef}>
{messages.length > 0 &&
messages.map((msg, index) => {
return (
<View key={index} style={styles.listWrapper}>
{msg.role === 'user' ? (
<View style={styles.listQuestionStyle}>
<Text style={styles.listTextStyle}>{msg.content}</Text>
</View>
) : (
<View style={styles.listStyle}>
<Text style={styles.listTextStyle}>{msg.content}</Text>
</View>
)}
</View>
);
})}
</ScrollView>
</View>
<View style={styles.container2}>
<View style={styles.bottomWrapper}>
<TextInput
style={styles.bottomTextInput}
placeholder="Type message here"
multiline={true}
editable={loading ? false : true}
value={query}
onChangeText={text => setQuery(text)}></TextInput>
{loading ? (
<View style={styles.bottomWrapperButton}>
<ActivityIndicator size={'small'} color={'#33CEFF'} />
</View>
) : (
<TouchableOpacity
style={styles.bottomWrapperButton}
onPress={handleSend}>
<Text>Send</Text>
</TouchableOpacity>
)}
</View>
</View>
</SafeAreaView>
);
}

const styles = StyleSheet.create({
mainContainer: {
flex: 1,
paddingVertical: 10,
},
container1: {
flex: 0.93,
paddingBottom: 5,
},
container2: {
flex: 0.08,
},
bottomWrapper: {
width: '95%',
height: 55,
borderWidth: 1,
borderRadius: 50,
alignSelf: 'center',
flexDirection: 'row',
paddingHorizontal: 10,
alignItems: 'center',
justifyContent: 'center',
},
bottomTextInput: {
width: '80%',
},
bottomWrapperButton: {
width: '15%',
paddingTop: 5,
},
listWrapper: {
justifyContent: ‘center’
},
listQuestionStyle: {
width: '90%',
alignSelf: 'center',
backgroundColor: '#FF0000',
borderTopLeftRadius: 5,
borderTopRightRadius: 5,
},
listStyle: {
width: '90%',
alignSelf: 'center',
backgroundColor: '#33CEFF',
borderBottomLeftRadius: 5,
borderBottomRightRadius: 5,
marginBottom:10
},
listTextStyle: {
padding: 10,
},
icon: {
width: 200,
height: 60,
},
backIcon: {
width: 20,
height: 20,
paddingLeft: 40,
},
heading: {
fontSize: 20,
color: '#000',
paddingRight: 40,
},
headingContainer: {
width: '90%',
alignItems: 'center',
},
backIconContainer: {
width: '10%',
justifyContent: 'center',
},
header: {
flexDirection: 'row',
justifyContent: 'center',
marginBottom: 20,
},
generatedImage:{
width:300,
height:150,
alignSelf:'center'
}
});

Related read: ChatGPT Integrations in React JS Using Django

Integrating Gemini

Step 1: Create a project on Google Developer Console.

Step 2: Go to Google AI Studio and create a new API key for that project.

Step 3: Install Dependencies.

npm install @google/generative-ai

Dive Into AI Integration Within React Native Apps. Start the Transformative Journey Today!

Gemini Integration Example

import React, {useState, useRef} from 'react';
import {
View,
Text,
TouchableOpacity,
SafeAreaView,
TextInput,
ScrollView,
StyleSheet,
ActivityIndicator,
Alert,
Image,
} from 'react-native';
import {GoogleGenerativeAI} from '@google/generative-ai';

const API_KEY = 'XXXXXXXXXXXXXXXX';
const genAI = new GoogleGenerativeAI(API_KEY);

export default function Gemini({handleBackPress}) {
const scrollRef = useRef();
const [messages, setMessages] = useState([]);
const [query, setQuery] = useState('');
const [loading, setLoading] = useState(false);

const handleSend = async () => {
try {
setLoading(true);
const model = genAI.getGenerativeModel({model: 'gemini-pro'});
const chat = model.startChat();
const result = await chat.sendMessage(query);
const response = result.response;
if (response) {
const text = await response?.text();
const newQuestion = {question: query, answer: text};
setMessages([...messages, newQuestion]);
scrollRef.current?.scrollToEnd({animated: true});
}
setQuery('');
setLoading(false);
} catch (err) {
setLoading(false);
setQuery('');
Alert.alert('Error', err);
}
};

return (
<SafeAreaView style={styles.mainContainer}>
<View style={styles.container1}>
<View style={styles.header}>
<TouchableOpacity
style={styles.backIconContainer}
onPress={handleBackPress}>
<Image
source={require('./back.png')}
style={styles.backIcon}
resizeMode="contain"
/>
</TouchableOpacity>
<View style={styles.headingContainer}>
<Text style={styles.heading}>Google Gemini</Text>
</View>
</View>
<ScrollView ref={scrollRef}>
{messages.length > 0 &&
messages.map((msg, index) => {
return (
<View key={index} style={styles.listWrapper}>
<View style={styles.listQuestionStyle}>
<Text style={styles.listTextStyle}>{msg.question}</Text>
</View>
<View style={styles.listStyle}>
<Text style={styles.listTextStyle}>{msg.answer}</Text>
</View>
</View>
);
})}
</ScrollView>
</View>
<View style={styles.container2}>
<View style={styles.bottomWrapper}>
<TextInput
style={styles.bottomTextInput}
placeholder="Type message here"
multiline={true}
editable={loading ? false : true}
value={query}
onChangeText={text => setQuery(text)}></TextInput>
{loading ? (
<View style={styles.bottomWrapperButton}>
<ActivityIndicator size={'small'} color={'#33CEFF'} />
</View>
) : (
<TouchableOpacity
style={styles.bottomWrapperButton}
onPress={handleSend}>
<Text>Send</Text>
</TouchableOpacity>
)}
</View>
</View>
</SafeAreaView>
);
}

const styles = StyleSheet.create({
mainContainer: {
flex: 1,
paddingVertical: 10,
},
container1: {
flex: 0.93,
paddingBottom: 5,
},
container2: {
flex: 0.08,
},
bottomWrapper: {
width: '95%',
height: 55,
borderWidth: 1,
borderRadius: 50,
alignSelf: 'center',
flexDirection: 'row',
paddingHorizontal: 10,
alignItems: 'center',
justifyContent: 'center',
},
bottomTextInput: {
width: '80%',
},
bottomWrapperButton: {
width: '15%',
paddingTop: 5,
},
listWrapper: {
marginTop: 10,
},
listQuestionStyle: {
width: '90%',
alignSelf: 'center',
backgroundColor: '#FF0000',
borderTopLeftRadius: 5,
borderTopRightRadius: 5,
},
listStyle: {
width: '90%',
alignSelf: 'center',
backgroundColor: '#33CEFF',
borderBottomLeftRadius: 5,
borderBottomRightRadius: 5,
},
listTextStyle: {
padding: 10,
},
icon: {
width: 200,
height: 60,
alignSelf: 'center',
},
backIcon: {
width: 20,
height: 20,
paddingLeft:40
},
heading:{
fontSize:20,
color:'#000',
paddingRight:40
},
headingContainer:{
width: '90%',
alignItems:'center'
},
backIconContainer:{
width: '10%',
justifyContent: 'center'
},
header:{
flexDirection: 'row',
justifyContent: 'center',
marginBottom:20
}
});
coma

Conclusion

In this guide, we’ve covered the integration of both ChatGPT and Gemini into a React Native project. These powerful AI models can enhance user experiences in mobile applications by providing natural language understanding and simulating realistic web browsing interactions. By following the steps outlined above and utilizing the provided examples, you can easily incorporate AI capabilities into your React Native apps.

Keep Reading

Keep Reading

  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?