Created
December 8, 2023 06:29
-
-
Save theoknock/9ea3805432d1baf54076efd4addbc445 to your computer and use it in GitHub Desktop.
ChatGTP Multiturn Conversation
This file contains hidden or 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 necessary libraries | |
from openai import OpenAI | |
import os | |
import time | |
# Storing OPENAI API KEY in an environment variable | |
os.environ["OPENAI_API_KEY"] = "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" | |
# Creating the OpenAI client by providing the API KEY | |
client = OpenAI(api_key=os.environ['OPENAI_API_KEY']) | |
# Creating an assistant | |
assistant = client.beta.assistants.create(name="PostgreSQL Expert", model="gpt-4") | |
# Creating a thread | |
thread = client.beta.threads.create() | |
# Adding a message to the thread | |
# Define an array to hold messages | |
messages = [] | |
# Adding messages to the array | |
messages.append("First number: 5") | |
messages.append("Second number: 3") | |
messages.append("Add them") | |
for m in messages: | |
message = client.beta.threads.messages.create(thread_id=thread.id, role="user", content=m) | |
# Function to check whether a Run is completed | |
def poll_run(run, thread): | |
while run.status != "completed": | |
run = client.beta.threads.runs.retrieve(thread_id=thread.id, run_id=run.id) | |
time.sleep(0.5) | |
return run | |
# Creating a Run and waiting for it to complete | |
run = client.beta.threads.runs.create(thread_id=thread.id, assistant_id=assistant.id) | |
run = poll_run(run, thread) | |
# Extracting messages from the thread | |
messages = client.beta.threads.messages.list(thread_id=thread.id) | |
for m in messages: | |
print(f"{m.role}: {m.content[0].text.value}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Console output (is backwards, I know):