Skip to content

Instantly share code, notes, and snippets.

@theoknock
Created December 8, 2023 06:29
Show Gist options
  • Save theoknock/9ea3805432d1baf54076efd4addbc445 to your computer and use it in GitHub Desktop.
Save theoknock/9ea3805432d1baf54076efd4addbc445 to your computer and use it in GitHub Desktop.
ChatGTP Multiturn Conversation
# 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}")
@theoknock
Copy link
Author

theoknock commented Dec 8, 2023

Console output (is backwards, I know):

assistant: The sum of 5 and 3 is 8.
user: Add them
assistant: Okay, the second number is 3. What would you like me to do with these numbers?
user: Second number: 3
assistant: Okay, the first number is 5. Please provide the second number.
user: First number: 5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment