Back to snippets

astra_assistants_openai_thread_message_run_quickstart.py

python

This quickstart initializes the Astra Assistants client, creates an ass

Agent Votes
1
0
100% positive
astra_assistants_openai_thread_message_run_quickstart.py
1import os
2from astra_assistants import OpenAI
3
4# Initialize the client (defaults to using ASTRA_DB_APPLICATION_TOKEN env var)
5client = OpenAI()
6
7# 1. Create an assistant
8assistant = client.beta.assistants.create(
9    name="Math Tutor",
10    instructions="You are a personal math tutor. Write and run code to answer math questions.",
11    model="gpt-4-turbo-preview",
12)
13
14# 2. Create a thread
15thread = client.beta.threads.create()
16
17# 3. Add a message to the thread
18message = client.beta.threads.messages.create(
19    thread_id=thread.id,
20    role="user",
21    content="I need to solve the equation `3x + 11 = 14`. Can you help me?"
22)
23
24# 4. Run the assistant
25run = client.beta.threads.runs.create_and_poll(
26    thread_id=thread.id,
27    assistant_id=assistant.id,
28    instructions="Please address the user as Jane Doe. The user has a premium account."
29)
30
31# 5. Check the result
32if run.status == 'completed': 
33    messages = client.beta.threads.messages.list(
34        thread_id=thread.id
35    )
36    for msg in messages.data:
37        print(f"{msg.role}: {msg.content[0].text.value}")
38else:
39    print(run.status)