Back to blog

Chat with your favorite fictional character using OpenAI and Appwrite Functions

Learn how you can use Appwrite Functions and OpenAI to chat with popular characters such as Batman.

Have you ever wondered what it would feel like to interact with your favorite fictional characters, such as Superman, Hermione Granger, Gandalf, or Snow White? As a part of an internal hackathon at Appwrite recently, my team developed an Appwrite Function that you can use to chat with any popular fictional character you like (we really wanted to talk to Batman!)

In this blog, let’s learn how you can build this Appwrite Function using OpenAI’s GPT-4 API.

Prototype of Bruce Wayne chat

Setting up the OpenAI platform

To develop this project, you first need an OpenAI API Key, for which you must create an account on the OpenAI platform. Once your account is set up, visit their API keys page and create an API Key. Ensure you copy and save this key in a safe place, as the OpenAI platform will not let you view the key after it is created.

OpenAI API Keys

Note: To use the GPT-4 API, your account must be upgraded to the Usage tier 1. To learn more, visit their Usage tiers documentation.

Initializing the Appwrite Function

Now that we have our OpenAI API Key, let us get the function ready on Appwrite. Head over to your Appwrite project and visit the Functions page. From there, we will use the Node.js starter template and create a function.

Appwrite Functions

Once the function is ready, we must visit the Settings tab on the Function page and add the following environment variables:

  • OPENAI_API_KEY: API Key from our OpenAI account

  • OPENAI_MAX_TOKENS: Maximum number of tokens that the OpenAI response should contain (we’ll set this as 512)

Once that is done, visit the function’s GitHub repository and clone the project.

Developing the function logic

To develop the function, we must first install the openai npm package. Open your terminal in the project directory and run the following command:

Bash
npm i openai

Once that is done, visit the src/main.js file and replace the entire code with the following:

JavaScript
import { OpenAI } from 'openai';

export default async ({ req, res, log, error }) => {
  try {
    const openai = new OpenAI({
      apiKey: process.env.OPENAI_API_KEY,
    });

    var prompt = `You are ${req.body.character}.\nRespond to the following question in first-person: ${req.body.question}\n${req.body.additionalPrompt}`

    const response = await openai.chat.completions.create({
      model: 'gpt-4',
      max_tokens: parseInt(process.env.OPENAI_MAX_TOKENS ?? '512'),
      messages: [{ role: 'user', content: prompt }],
    });
    const completion = response.choices[0].message?.content;
    log(completion);
    return res.json({ ok: true, answer: completion }, 200);
  } catch (err) {
    error(err.message);
    return res.json({ ok: false, error: err.message }, 500);
  }
};

This function will accept the name of a character, the question from a user, and any additional prompt you might optionally like to give. For example, in our hackathon project, we wanted to interact with Bruce Wayne and ensure that his Batman alter-ego was not directly given away, so here’s what our inputs looked like:

Character nameQuestionAdditional prompt
Bruce WayneAre you Batman?Ensure that you don't reveal your Batman alter-ego but you can tip-toe around it.

Testing the function

Once you’ve completed all the aforementioned steps, you can push the code to the generated GitHub repository, at which point Appwrite Cloud will automatically deploy the changes to your function.

You can test the function by sending it a cURL request from your terminal or any other API testing client.

Bash
curl --location '<YOUR_FUNCTION_URL>' \
--header 'Content-Type: application/json' \
--data '{
  "character": "Bruce Wayne",
  "question": "Are you Batman?",
  "additionalPrompt": "Ensure that you don'\''t reveal your Batman alter-ego but you can tip-toe around it."
}'

Thunder Client on VS Code

Next steps

And with that, our fictional character chat function is ready! If you liked this project and/or want to investigate the function code, visit the GitHub repository.

For more information about Appwrite Functions, visit the following resources:

  • Appwrite Function Docs: These documents provide more information on how to use Appwrite Functions.

  • Appwrite Discord: Connect with other developers and the Appwrite team for discussion, questions, and collaboration.

Subscribe to our newsletter

Sign up to our company blog and get the latest insights from Appwrite. Learn more about engineering, product design, building community, and tips & tricks for using Appwrite.