How to Build an Advanced Conversational AI Chatbot with Google’s PaLM API 2 and React Native Expo

Rohit Kumar Thakur
4 min readAug 25, 2023
Conversational AI Chatbot | Google’s PaLM API 2 and React Native Expo

Hello guys, My name is Rohit, and I am a software Developer and a YouTube content creator. A few days ago, I integrated the Google’s PaLM model API into the React native expo and made a conversational AI chatbot. It’s pretty simple actually.

Before you start coding, visit the Google AI website: https://developers.generativeai.google/ and join the waitlist to get an API key for PaLM. I received my API key within 24 hours, so I’m confident you will too.

Once you get the access, you will see three prompts: text prompt, data prompt and chat prompt. We are going with the chat prompt because we will build a conversational AI chatbot.

For this project, we only need an external library to fetch the HTTP request. Yes! you guessed it right! Install the axios using npm

Now, we are all set!!! If you are new to the chatbot development field then I would recommend you to watch the step-by-step tutorial. Because this project is not for beginners but as a beginner you must build these types of projects to enhance your skills.

Inside your main function or according to your code, you can copy and paste the following code. Because this code will do the real magic. The rest will be UI parts so you can customize or use them as per your preference.

Complete Source Code & More: https://www.patreon.com/bugninza

const [messages, setMessages] = useState([]);
const [inputText, setInputText] = useState('');
const PALM_API_KEY = '######################'; // replace your API Key

const generateText = async () => {
if (inputText.trim() === '') {
return;
}

const apiUrl = `https://generativelanguage.googleapis.com/v1beta2/models/chat-bison-001:generateMessage`;

const requestData = {
prompt: {
context: '',
examples: [],
messages: [{ content: inputText }]
},
temperature: 0.25,
top_k: 40,
top_p: 0.95,
candidate_count: 1,
};

const headers = {
'Content-Type': 'application/json',
};

try {
const response = await axios.post(`${apiUrl}?key=${PALM_API_KEY}`, requestData, {
headers,
});

if (response.status === 200) {
if (response.data && response.data.candidates && response.data.candidates.length > 0) {
const botResponse = response.data.candidates[0].content;

// Add the user's input to the messages array
const newUserMessage = {
id: messages.length + 1,
text: inputText,
sender: 'user', // Set the sender as 'user'
timestamp: new Date().getTime(),
};

// Add the bot's response to the messages array
const newBotMessage = {
id: messages.length + 2,
content: botResponse,
sender: 'bot', // Set the sender as 'bot'
timestamp: new Date().getTime(),
};

setMessages([...messages, newUserMessage, newBotMessage]);
setInputText('');
} else {
console.error('Response structure is not as expected.');
}
} else {
console.error('Google Cloud API request failed with status:', response.status);
}
} catch (error) {
console.error('An error occurred while making the Google Cloud API request:', error);
}
};
  • Initialize the state using React’s useState hook. messages will store the conversation history, and inputText will hold the user’s input.
  • Create a function called generateText that’s triggered when the user taps the send button. Start by checking if the user’s input is not just empty spaces. If it is, Exit the function.
  • We’re preparing the data for our API request. We set up the API URL and create an object called requestData. This object includes the input text provided by the user and some configuration parameters like temperature, top_k, top_p, and candidate_count. These parameters affect the output of our ChatBot’s responses. We will follow the official documentation for the proper use of these parameters
  • Axios: We send a POST request to the API URL, passing along our API key and the requestData object in the request body. If everything goes smoothly, we receive a response from the API.
  • We check if the response status is 200 (which means success). If it is, we proceed to extract the bot’s response from the API response. We then create new message objects for both the user’s input and the bot’s response. These objects contain information like the sender’s ID, text, sender type (user or bot), and timestamp.
  • We update our messages state with the new messages using the setMessages function. This causes the UI to re-render and display the updated conversation history. We also clear the inputText so that the user can easily type another message.

If you feel lost somewhere in this project build then feel free to watch the step-by-step guide here:

That’s it!!!! Now if you are here then make sure to clap. It gonna help the medium algorithms to promote my article to a wider audience. Thanks for reading. Happy coding!!

Support My work

https://www.patreon.com/_ninza7

--

--