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