Handling API Keys in Firebase Functions with OpenAI's Node.js Package

Publié le 3 Juin 2024

Handling API Keys in Firebase Functions with OpenAI's Node.js Package

When working with Firebase Functions and integrating with the OpenAI API, I found that the authentication part were not clearly documented. Many resources online provide outdated methods, so this guide aims to clarify a way to manage authentication using the .env methodology. We will be using the openai node package, version 4.0.0 or later.

Setting Up the Environment

1. Install the Required Packages

Ensure you have the necessary npm packages installed in your project. You can do this by running:

npm install dotenv --save
npm install openai@^4.0.0

2. Create a .env File

Create a .env file in the root of your project directory and add your OpenAI API key:

OPENAI_API_KEY=<copy your API key here>

 

3. Update .gitignore

To prevent your .env file from being committed to your git repository, add it to your .gitignore file:

.env

 

Implementing the Firebase Function

Below is the complete code to create a Firebase Function that interacts with OpenAI's API. This function generates a "Hello World" message followed by a random string of 6 characters.

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const OpenAI = require('openai');
require('dotenv').config();

admin.initializeApp();

const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

exports.generateHelloWorld = functions.https.onRequest(async (req, res) => {
  try {
    const prompt = "Write 'Hello World' followed by a random string of 6 characters.";

    const openAIResponse = await openai.chat.completions.create({
      model: "gpt-4o",
      messages: [{ role: "user", content: prompt }],
    });

    const responseMessage = openAIResponse.choices[0].message.content;

    res.status(200).send(responseMessage);
  } catch (error) {
    console.error('Error communicating with OpenAI:', error);
    res.status(500).send('Internal Server Error');
  }
});

 

Testing Your Function

You can test your Firebase function either on Firebase or locally:

On Firebase

Deploy your function to Firebase with the following command:

firebase deploy --only function
Locally

To test the function locally, use Firebase emulators. Navigate to the functions directory in your terminal and start the emulators with:

firebase emulators:star

You will be able to connect to a localhost URL and validate your code, including the authentication with your API key.

Summary

In this guide, we've shown how to correctly handle API keys when using Firebase Functions with the OpenAI Node.js package using the env methodology. While valid for test, this methodology should be used with caution and other more secure approach such as Google secrets should be preffered for Prod environment.

#ArticleWrittenWithTheSupportOfChatgpt