-
-
Save tuki0918/21b03f0d345453fb89692ed50cade0b7 to your computer and use it in GitHub Desktop.
openai chat bot base
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
OPENAI_API_KEY="dummy" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import openai | |
import dotenv | |
import os | |
from typing import Literal | |
dotenv.load_dotenv() | |
openai.api_key = os.getenv("OPENAI_API_KEY") | |
def create_message(role: Literal["user", "assistant", "system"], content: str): | |
return { | |
"role": role, | |
"content": content | |
} | |
def openai_chat(messages: list): | |
res = openai.ChatCompletion.create( | |
# model="gpt-3.5-turbo", | |
# model="gpt-4-turbo", | |
model="gpt-4o", | |
messages=messages, | |
) | |
return res["choices"][0]["message"]["content"] | |
def user_interaction(): | |
return input("You: ") | |
def print_interaction(name: str, message: str): | |
print(f"{name}: {message}") | |
if __name__ == "__main__": | |
# read system prompt | |
system_prompt = "!!!INPUT SYSTEM PROMPT HERE!!!" | |
with open("system_prompt.txt", "r") as f: | |
system_prompt = f.read() | |
# initial setting | |
messages = [ | |
create_message("system", system_prompt), | |
create_message("user", "Please introduce yourself."), | |
] | |
while True: | |
# request to AI | |
msg = openai_chat(messages) | |
messages.append(create_message("assistant", msg)) | |
print_interaction("AI", msg) | |
# user input | |
msg = user_interaction() | |
if msg == "exit": | |
break | |
messages.append(create_message("user", msg)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment