OpenAI

Wrapper for the OpenAI Chat Completion API using the official openai SDK.

This class integrates OpenAI’s chat models (like GPT-4o) into the EazyML GenAI framework. It handles environment-based API key configuration and provides a unified interface for message-based chat completion.

class OpenAIGM(model='gpt-4.1', api_key=None)

Bases: GenerativeModel

Wrapper for the OpenAI Chat Completion API using the official openai SDK. This class integrates OpenAI’s chat models (like GPT-4o) into the EazyML GenAI framework. It handles environment-based API key configuration and provides a unified interface for message-based chat completion.

Args:

model (str, optional): The name of the OpenAI model to use. Defaults to ‘gpt-4o’.

api_key (str, optional): OpenAI API key. If not provided, will attempt to read from the ‘OPENAI_API_KEY’ environment variable.

Raises:

Exception: If no API key is provided and the environment variable is not set.

Example:
from eazyml_genai.components import OpenAIGM
# initialize openai generative model
openai_gm = OpenAIGM(model="gpt-4o",
         api_key=os.getenv('OPENAI_API_KEY'))

# response from generative model given question and retrieved documents
response, input_tokens, output_tokens = openai_gm.predict(question=question,
                            payloads=payloads,
                            show_token_details=True
                            )

# parse openai response to simple text format
parsed_response = openai_gm.parse(response=response)
predict(question, payloads, show_token_details=False)

Sends a chat completion request to the OpenAI API using the provided messages.

Args:

messages (list): A list of message dicts as per OpenAI’s chat format (role/content pairs).

kwargs (dict):
  • tools (list or dict, optional): Tool definitions for function calling. Can be a single tool (as dict) or a list of tools.

Returns:

openai.types.chat.ChatCompletion: The OpenAI API response object.

parse(response)

Extracts the text content from the first candidate and part of the response.

Args:
response (openai.types.chat.ChatCompletion):

The response object, assumed to have a structure containing candidates, content, and parts. The exact type of ‘response’ is not specified, but it should behave like a nested list/object as shown in the return description.

Returns:

str: The text content located at response.candidates[0].content.parts[0].text. Returns the extracted text as a string.