Serverless Computing & ML

Mastering Firebase Cloud Functions and OpenAI in a React App: A Step-by-Step Guide

Harry Bloch
Firebase Developers
4 min readMay 12, 2023

--

MidJourney prompt: software developer working on a laptop, code on monitor, sitting on beach chair, inside a volcano, synthwave style, space in the background with planets, super nova

In today’s world, serverless architectures and artificial intelligence (AI) are two transformative trends that have been gaining significant traction. As a developer, being able to integrate these advanced capabilities into your applications can open the door to an array of exciting possibilities. In this blog post, we’ll delve into how you can utilize Cloud Functions for Firebase and OpenAI to create an AI-powered text-generation application in React.

By implementing the text generation functionality in a Cloud Function, you can keep your API key on the backend, where it will be much harder for an attacker to steal it. This helps to secure your API key and protects your OpenAI resources from unauthorized access.

Setting Up Firebase Cloud Functions

Before we dive into the code, let’s begin with the initial setup of Cloud Functions for Firebase.

  1. Install the Firebase CLI: The Firebase Command Line Interface (CLI) is a must-have tool for Firebase development. Install it globally using npm by running npm install -g firebase-tools in your terminal.
  2. Initialize a Firebase Project: Navigate to your project directory and log in to Firebase with firebase login. Next, initialize Firebase in your project by running firebase init. In the series of prompts that follow, select Functions: Configure and deploy Cloud Functions, and choose your desired project. We'll be using TypeScript in this guide, so select TypeScript as your language when prompted.
  3. Install Dependencies: Navigate to the functions directory created during initialization (cd functions) and install the OpenAI package with npm install openai.
  4. Implement the Cloud Function: Now that your Firebase environment is ready, you can implement your Cloud Function. In our case, this function will be responsible for generating text using the OpenAI API. Let’s walk through the implementation:
import * as functions from "firebase-functions";
import { Configuration, OpenAIApi } from "openai";

const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});

const openai = new OpenAIApi(configuration);

exports.generateText = functions.https.onCall(async (prompt, context) => {

try {
const openAPIResponse = await openai.createCompletion({
model: 'text-davinci-003',
prompt,
max_tokens: 500,
n: 1,
stop: "{}",
});
console.log(openAPIResponse.data, 'response data');
if (openAPIResponse.data.choices.length > 0) {
const generatedText = openAPIResponse.data.choices[0].text?.trim();
console.log({generatedText})
return { text: generatedText };
} else {
throw new Error('No choices available');
}
} catch (error) {
console.error('OpenAI API request failed:', error);
throw new functions.https.HttpsError('internal', 'OpenAI API request failed');
}
});

Here, generateText is an asynchronous function that is exported for Firebase to use as a Cloud Function. This function is triggered when an HTTPS request is made to its URL. It takes a prompt and a context as arguments, with the prompt being the input for the OpenAI API.

5. Deploy the Function: Finally, deploy your function to Firebase using firebase deploy --only functions. Upon successful deployment, Firebase will provide a URL for your function, which you can use to make HTTPS requests.

Calling the Cloud Function from a React Application

With the Firebase Cloud Function in place, we can call it from our React application. Here’s how you can accomplish this using TypeScript:


import React, { useState } from 'react';
import firebase from 'firebase/app';
import 'firebase/functions';

// Define a type for our prompt
type Prompt = {
prompt: string;
};

const GenerateText: React.FC = () => {
const [generatedText, setGeneratedText] = useState<string | null>(null);

const generateTextFromPrompt = async (prompt: Prompt) => {
const generateTextFunction = firebase.functions().httpsCallable('generateText');

try {
const result = await generateTextFunction(prompt);
setGeneratedText(result.data.text);
} catch (error) {
console.error('Firebase function invocation failed:', error);
}
};

// Render the component
return (
<div>
<button onClick={() => generateTextFromPrompt({ prompt: "Once upon a time" })}>
Generate Story
</button>
{generatedText && <p>{generatedText}</p>}
</div>
);
};

export default GenerateText;

In the above code, we’ve defined a state variable generatedText to store the text generated by the OpenAI API. The generateTextFromPrompt function is responsible for calling the Firebase Cloud Function, passing the prompt as an argument. If the function call is successful, the generated text is stored in our state variable, which is then rendered in our component.

Conclusion

That’s it! You’ve successfully integrated Firebase Cloud Functions with OpenAI in a React application. By combining these technologies, you’ve created a powerful text-generating AI application, showcasing the capabilities of serverless computing and artificial intelligence.

While this guide specifically focuses on text-generation, the principles you’ve learned can be applied to a wide range of serverless and AI functionalities. Keep experimenting and pushing the boundaries of what’s possible!

--

--