openai/openai-python
Publicmirrored from https://github.com/openai/openai-pythonAvailable
examples/assistant.py
38lines · modeblame
f6c2aedfMuhammed Al-Dulaimi2 years ago | 1 | |
2343e630Stainless Bot2 years ago | 2 | import openai |
| 3 | | |
f6c2aedfMuhammed Al-Dulaimi2 years ago | 4 | # gets API Key from environment variable OPENAI_API_KEY |
| 5 | client = openai.OpenAI() | |
| 6 | | |
| 7 | assistant = client.beta.assistants.create( | |
| 8 | name="Math Tutor", | |
| 9 | instructions="You are a personal math tutor. Write and run code to answer math questions.", | |
| 10 | tools=[{"type": "code_interpreter"}], | |
| 11 | model="gpt-4-1106-preview", | |
| 12 | ) | |
| 13 | | |
| 14 | thread = client.beta.threads.create() | |
| 15 | | |
| 16 | message = client.beta.threads.messages.create( | |
| 17 | thread_id=thread.id, | |
| 18 | role="user", | |
2343e630Stainless Bot2 years ago | 19 | content="I need to solve the equation `3x + 11 = 14`. Can you help me?", |
f6c2aedfMuhammed Al-Dulaimi2 years ago | 20 | ) |
| 21 | | |
595f3b36Stainless Bot2 years ago | 22 | run = client.beta.threads.runs.create_and_poll( |
2343e630Stainless Bot2 years ago | 23 | thread_id=thread.id, |
| 24 | assistant_id=assistant.id, | |
| 25 | instructions="Please address the user as Jane Doe. The user has a premium account.", | |
f6c2aedfMuhammed Al-Dulaimi2 years ago | 26 | ) |
| 27 | | |
595f3b36Stainless Bot2 years ago | 28 | print("Run completed with status: " + run.status) |
f6c2aedfMuhammed Al-Dulaimi2 years ago | 29 | |
595f3b36Stainless Bot2 years ago | 30 | if run.status == "completed": |
| 31 | messages = client.beta.threads.messages.list(thread_id=thread.id) | |
f6c2aedfMuhammed Al-Dulaimi2 years ago | 32 | |
595f3b36Stainless Bot2 years ago | 33 | print("messages: ") |
| 34 | for message in messages: | |
| 35 | assert message.content[0].type == "text" | |
| 36 | print({"role": message.role, "message": message.content[0].text.value}) | |
f6c2aedfMuhammed Al-Dulaimi2 years ago | 37 | |
595f3b36Stainless Bot2 years ago | 38 | client.beta.assistants.delete(assistant.id) |