Skip to content

castle-engine/castle-openai

Repository files navigation

Castle Game Engine - Querying OpenAI

Use OpenAI API from Caste Game Engine. Ask a question, it gets an answer using OpenAI "assistant".

Screenshot

Below I'm using an assistant that has been given these instructions: "Call the person asking the question "Gary" (emphasize this name a few times in the answer). Also, add a cat joke to every answer."

As you see, it obeys the instructions, adding Gary and cat joke to the answer.

Screenshot

Platforms

Successfully tested on Windows, Linux and Android with Castle Game Engine with FPC.

It is responsive on all platforms -- utilizing the fact that TCastleDownload is asynchronous, it starts a HTTP request and then UI remains responsive.

Should run on all Castle Game Engine platforms where our TCastleDownload class (see https://castle-engine.io/manual_network.php#section_castle_download) has all the necessary capabilities. The TCastleDownload is our class for asynchronous HTTP requests.

How it works and how to compile it

Using OpenAI API terminology, each press of "Send" is doing this:

  • Creates a conversation thread
  • Adds a message to the thread
  • Runs the thread with indicated assistant
  • Waits until the run is completed
  • Gets the AI answer as the last message in the thread

Before compiling, first create code/openai_config.inc file with the following content (you can use code/openai_config.inc.template as starting point):

{%MainUnit gameviewmain.pas}
OpenAIApiKey = '...';
OpenAIAssistantId = 'asst_...';

Fill the above constants with your OpenAI API key and assistant ID. You need to

Using Castle Game Engine.

Limitations

We display ? in case of missing glyphs, in particular e.g. emoticons that some assistants like to add (e.g. our "cat joke making assistant" often adds a cat emoticon).

Building

Compile by:

  • CGE editor. Just use menu items "Compile" or "Compile And Run".

  • Or use CGE command-line build tool. Run castle-engine compile in this directory.

  • Or use Lazarus. Open in Lazarus castle_openai_standalone.lpi file and compile / run from Lazarus. Make sure to first register CGE Lazarus packages.

  • Or use Delphi. Open in Delphi castle_openai_standalone.dproj file and compile / run from Delphi. See CGE and Delphi documentation for details.