Integrating AS3 with OpenAI API (ChatGPT) for Simple Querying


Share:

OpenAI offers developers an impressive tool with the ChatGPT model, capable of understanding context, answering queries, and even generating human-like text. While the official OpenAI website provides integration guides for several languages, ActionScript 3 (AS3) isn’t among them. This doesn’t mean AS3 developers are left out in the cold. Despite Adobe no longer supporting AS3, a significant number of developers continue to use it for Adobe Air applications, thanks to Harman’s dedicated maintenance of Adobe Air SDK.

Recognizing this need, we created a simple but powerful AS3 class to provide an easy bridge between AS3 applications and the OpenAI API. The objective here is to offer AS3 developers the means to make quick queries to the OpenAI API, specifically to the GPT-3 model, without the need to figure out the intricacies of the API. The class serves as a basic foundation that can be easily built upon or modified to suit the unique requirements of your application.

Remember, to use the OpenAI API, you’ll need a paid subscription from OpenAI, as per their usage policy. But with the subscription and our handy AS3 class, you’ll be ready to bring the power of GPT-3 (and later models) to your AS3 applications in no time. Happy coding!

 

The Class

package com.codeandvisual.integrations.gpt {
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestHeader;
	import flash.net.URLRequestMethod;
	
	public class OpenAIDemo {
		// Static variables to hold API configuration parameters
		public static var key:String
		public static var endpoint:String
		public static var model:String
		public static var temperature:Number
		public static var callback:Function
		
		// Constructor
		public function OpenAIDemo():void {
			//Intentionally blank		
		}
		
		// Function to initialize the API configuration parameters
		public static function init(thisKey:String, thisTemperature:Number = 0.7, thisEndPoint:String = "https://api.openai.com/v1/chat/completions", thisModel:String = "gpt-3.5-turbo"):void {
			key = thisKey
			temperature = thisTemperature
			endpoint = thisEndPoint
			model = thisModel
		}
		
		// Function to send a request to the API and handle the response
		public static function getResponse(thisInput:String ,thisCallback:Function, thisTemperature:Number = NaN, thisEndPoint:String = "", thisModel:String = ""):void {
			callback = thisCallback
			var myTemperature:Number = isNaN(thisTemperature) ? temperature : thisTemperature;
			var myEndPoint:String = thisEndPoint == "" ? endpoint : thisEndPoint;
			var myModel:String = thisModel == "" ? model : thisModel;
			var myHeaders:Array = [];
			myHeaders.push(new URLRequestHeader("Content-Type", "application/json"));
			myHeaders.push(new URLRequestHeader("Authorization", "Bearer " + key));
			
			// Variables to be sent in the API request
			var myVariables:Object = {}
			myVariables["model"] = model;
			myVariables["messages"] = [{"role": "user", "content": thisInput}];
			myVariables["temperature"] = myTemperature;
			var myLoader:URLLoader = post(myEndPoint, JSON.stringify(myVariables), myHeaders)
		}
		
		// Function to send a POST request to the API
		public static function post(thisPath:String, thisJSONData:String, thisHeaders:Array ):URLLoader {
			var myLoader:URLLoader =  new URLLoader();
			var myRequest:URLRequest
			myRequest = new URLRequest(thisPath);
			myRequest.method = URLRequestMethod.POST;
			myRequest.requestHeaders = thisHeaders
			myRequest.data = thisJSONData;
			
			// Add listeners to handle the API response
			myLoader.addEventListener(IOErrorEvent.IO_ERROR, doError);
			myLoader.addEventListener(Event.COMPLETE, doSuccess);
			
			// Send the API request
			myLoader.load(myRequest);
			return myLoader
		}
		
		// Callback function for successful API response
		public static function doSuccess(e:Event):void {
			var myLoader:URLLoader = e.currentTarget as URLLoader
			removeListeners(myLoader)
			var myData:String = myLoader.data
			var myObject:Object = JSON.parse(myData)
			trace("OpenAI - Response Success")
			callback(myObject);
			callback = null
		}
		
		// Callback function for unsuccessful API response
		public static function doError(e:IOErrorEvent):void {
			var myLoader:URLLoader = e.currentTarget as URLLoader
			removeListeners(myLoader)
			trace("OpenAI - Response Fail: " + myLoader.data)
			callback = null
		}
		// Function to remove listeners after a response is received
		public static function removeListeners(thisLoader:URLLoader):void {
			thisLoader.removeEventListener(IOErrorEvent.IO_ERROR, doError);
			thisLoader.removeEventListener(Event.COMPLETE, doSuccess);
		}
	}
}

You can download it directly here: OpenAIDemo

 

Example Usage:

 

Using the OpenAIDemo class is designed to be straightforward and intuitive. Here’s how you can get started:

// Import our custom OpenAIDemo class
import com.codeandvisual.integrations.gpt.OpenAIDemo;

// Initialize with the required argument - OpenAI API Key
OpenAIDemo.init("YOUR_OPENAI_API_KEY");

// Define the callback function to handle the API's response
function handleResponse(response:Object):void {
	// Handle the API's response here.
	trace(response);
}

// Make a request to the API
OpenAIDemo.getResponse("Translate the following English text to French: 'Hello, world!'", handleResponse);

 

Example Usage Breakdown:

 

After saving the class to the appropriate folder in your src directory (your-src-path/com/codeandvisual/integrations/gpt) and importing it,  you can access the static functions directly. 

First, initialize your OpenAI API settings using the init() function. Replace “<your-openai-api-key>” with your actual OpenAI API key.

OpenAIDemo.init("<your-openai-api-key>", 0.7, "https://api.openai.com/v1/chat/completions", "gpt-3.5-turbo");

In the init() function, the parameters are your OpenAI key, the temperature for the API (which controls the randomness of the AI’s responses), the endpoint for OpenAI’s API, and the model you wish to use (in this case, gpt-3.5-turbo).

Only the first argument is required, you can leave the others blank to use defaults.

Next, define a callback function that will handle the response from the OpenAI API. This function should accept one argument, which will be the object returned by the API. In this example, we’ll simply trace the content of the response.

// Define the callback function to handle the API's response
function handleResponse(response:Object):void { // Handle the API's response here. trace(response); }

Now that the callback function is set up, you can use the getResponse() function to send a message to the API.

OpenAIDemo.getResponse("Translate the following English text to French: '{\"text\": \"Hello, world!\"}'", handleResponse);

In this example, we’re asking the API to translate “Hello, world!” from English to French. The getResponse() function sends this message to the API and then uses the handleResponse() function to handle the response. For now, the response from the OpenAI API will be traced in the console.

 

Have fun!

 

And that’s it! You’ve just made a request to the OpenAI API from your AS3 codebase. With this simple setup, you can now start leveraging the power of OpenAI’s models in your application.

Share:

    Leave a Reply


    Creative Digital Agency

    Code and Visual works with clients around Australia to create and build outstanding and accessible digital services. If you want to discus a project contact us now for an initial consultation.


    Categories

    Recent Posts