openai/openai-python
Publicmirrored fromhttps://github.com/openai/openai-pythonAvailable
examples/assistant.py
53lines · modecode
| 1 | import openai |
| 2 | import time |
| 3 | |
| 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", |
| 19 | content="I need to solve the equation `3x + 11 = 14`. Can you help me?" |
| 20 | ) |
| 21 | |
| 22 | run = client.beta.threads.runs.create( |
| 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." |
| 26 | ) |
| 27 | |
| 28 | print("checking assistant status. ") |
| 29 | while True: |
| 30 | run = client.beta.threads.runs.retrieve( |
| 31 | thread_id=thread.id, |
| 32 | run_id=run.id |
| 33 | ) |
| 34 | |
| 35 | if run.status == "completed": |
| 36 | print("done!") |
| 37 | messages = client.beta.threads.messages.list( |
| 38 | thread_id=thread.id |
| 39 | ) |
| 40 | |
| 41 | print("messages: ") |
| 42 | for message in messages: |
| 43 | print({ |
| 44 | "role": message.role, |
| 45 | "message": message.content[0].text.value |
| 46 | }) |
| 47 | |
| 48 | client.beta.assistants.delete(assistant.id) |
| 49 | |
| 50 | break |
| 51 | else: |
| 52 | print("in progress...") |
| 53 | time.sleep(5) |