You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
52 lines
1.6 KiB
52 lines
1.6 KiB
from openai import OpenAI as OAI |
|
|
|
class OpenAI: |
|
""" |
|
A class that interacts with the OpenAI API for generating chat-based responses. |
|
|
|
Attributes: |
|
chat (bool): Indicates whether the chat mode is enabled. |
|
client: An instance of the OpenAI API client. |
|
messages (list): A list of messages exchanged between the user and the assistant. |
|
""" |
|
|
|
def __init__(self, chat=False, system_prompt=None): |
|
""" |
|
Initializes a new instance of the OpenAI class. |
|
|
|
Args: |
|
chat (bool, optional): Indicates whether the chat mode is enabled. Defaults to False. |
|
""" |
|
self.chat = chat |
|
self.system_prompt = system_prompt |
|
self.client = OAI( |
|
# This is the default and can be omitted |
|
api_key="sk-proj-5WJ1DIQfXdAHJQ0izfa1T3BlbkFJuWBpyJWJKal4MIMk3kbZ", |
|
) |
|
self.messages = [] |
|
|
|
if self.system_prompt: |
|
self.messages.append({"role": "system", "content": self.system_prompt}) |
|
|
|
def generate(self, prompt): |
|
""" |
|
Generates a chat-based response using the OpenAI API. |
|
|
|
Args: |
|
prompt (str): The user's input prompt. |
|
|
|
Returns: |
|
str: The generated response from the OpenAI model. |
|
""" |
|
self.messages.append({"role": "user", "content": prompt}) |
|
|
|
chat_completion = self.client.chat.completions.create( |
|
messages=self.messages, |
|
model="gpt-4o", |
|
) |
|
answer = chat_completion.choices[0].message.content |
|
if self.chat: |
|
self.messages.append({"role": "assistant", "content": answer}) |
|
|
|
return answer |
|
|