DEV Community

parmarjatin4911@gmail.com
parmarjatin4911@gmail.com

Posted on

ChatGPT Assistants API Python

ChatGPT Assistants API Python

import openai

Initialize the client

client = openai.OpenAI()

Step 1: Create an Assistant

assistant = client.beta.assistants.create(
name="Math Tutor",
instructions="You are a personal math tutor. Write and run code to answer math questions.",
tools=[{"type": "code_interpreter"}],
model="gpt-4-1106-preview"
)

Step 2: Create a Thread

thread = client.beta.threads.create()

Step 3: Add a Message to a Thread

message = client.beta.threads.messages.create(
thread_id=thread.id,
role="user",
content="I need to solve the equation 3x + 11 = 14. Can you help me?"
)

Step 4: Run the Assistant

run = client.beta.threads.runs.create(
thread_id=thread.id,
assistant_id=assistant.id,
instructions="Please address the user as Jane Doe. The user has a premium account."
)

print(run.model_dump_json(indent=4))

while True:
# Wait for 5 seconds
time.sleep(5)

# Retrieve the run status
run_status = client.beta.threads.runs.retrieve(
    thread_id=thread.id,
    run_id=run.id
)
print(run_status.model_dump_json(indent=4))

# If run is completed, get messages
if run_status.status == 'completed':
    messages = client.beta.threads.messages.list(
        thread_id=thread.id
    )

    # Loop through messages and print content based on role
    for msg in messages.data:
        role = msg.role
        content = msg.content[0].text.value
        print(f"{role.capitalize()}: {content}")

    break
Enter fullscreen mode Exit fullscreen mode

Top comments (0)