Easy ChatGPT API

Davide Carpini
3 min readJul 10, 2024

--

OpenAIHelper for Seamless ChatGPT API Interactions

In this article, we’ll explore a custom helper class for interacting with OpenAI’s API using TypeScript. The OpenAIHelper class simplifies making requests to the OpenAI API, including prompt and image inputs.

Introduction to OpenAIHelper

The OpenAIHelper class is designed to streamline the process of interacting with OpenAI's API. It handles API initialization, parameter validation, and response parsing, making it easier to integrate OpenAI's powerful models into your applications.

Implementation

First, let’s look at the implementation of the OpenAIHelper class.

// file: OpenAIHelper.ts
import OpenAI, { ClientOptions } from "openai";

/**
* Parameters for the OpenAIHelper class.
*/
export type OpenAIHelperParams = {
prompt: string;
maxTokens?: number;
images?: string[];
model?: string;
};

/**
* Helper class for interacting with the OpenAI API.
*/
export class OpenAIHelper {
private openai: OpenAI;

/**
* Constructs a new instance of the OpenAIHelper class.
* @param options The client options for the OpenAI API.
* @throws Error if apiKey is not provided in the options.
*/
constructor(options: ClientOptions) {
if (!options.apiKey) {
throw new Error("apiKey is required");
}
this.openai = new OpenAI(options);
}

/**
* Sends a chat-based prompt to the OpenAI API and retrieves the response.
* @param params The parameters for the chat prompt.
* @returns The response from the OpenAI API.
*/
public askChatGPT = async ({
prompt,
maxTokens,
images,
model = "gpt-4o",
}: OpenAIHelperParams) => {
const response = await this.openai.chat.completions.create({
model,
max_tokens: maxTokens,
messages: [
{
role: "user",
content: [
{
type: "text",
text: prompt,
},
...(images?.map((image: string) => ({
type: "image_url" as any,
image_url: {
url: image,
},
})) || []),
],
},
],
response_format: {
type: "json_object",
},
});
const data = JSON.parse(response.choices[0]?.message.content || "{}");
return { ...response, data };
};
}

How to Use OpenAIHelper

Now, let’s go through a couple of examples to demonstrate how to use the OpenAIHelper class in your projects.

Example 1: Identifying a Dog in an Image

In this example, we’ll ask the model to identify if a given image is a dog.

import { OpenAIHelper } from "./OpenAIHelper";
const askChatGpt = async (prompt: string) => {
const openAIHelper = new OpenAIHelper({
apiKey: process.env.OPENAI_API_KEY as string,
dangerouslyAllowBrowser: true,
});
const { data } = await openAIHelper.askChatGPT({
prompt,
images: [
"https://cdn.pixabay.com/photo/2023/08/18/15/02/dog-8198719_640.jpg", // dog image
],
});
console.log("data", data);
};

askChatGpt(
`tell me with a json if this image represents dog, json format: { "isDog": boolean }`
);
// output: { isDog: true }

Example 2: Generating Translations

In this example, we’ll ask the model to generate translations for given text values.

// file: generateTranslations.ts
import { OpenAIHelper } from "./OpenAIHelper";

const askChatGpt = async (prompt: string) => {
const openAIHelper = new OpenAIHelper({
apiKey: process.env.OPENAI_API_KEY as string,
dangerouslyAllowBrowser: true,
});
const { data } = await openAIHelper.askChatGPT({
prompt,
});
console.log("data", data);
};

askChatGpt(
`generate a json with values translated in italian { "Welcome": "Welcome", "Bye": "Bye" }`
);
// output: { "Welcome": "Benvenuto", "Bye": "Arrivederci" }

In this script, we use the askChatGPT method with a prompt to translate text values into Italian. The model returns a JSON object with the translated values.

Conclusion

The OpenAIHelper class simplifies the process of interacting with OpenAI's API, allowing you to focus on building your application's logic. By handling the intricacies of API requests and responses, this helper class makes it easier to integrate OpenAI's powerful models into your projects. Use the examples provided as a starting point to explore the capabilities of the OpenAIHelper and enhance your applications with AI-driven features.

--

--