openai/openai-python
Publicmirrored fromhttps://github.com/openai/openai-pythonAvailable
examples/assistant_stream_helpers.py
78lines · modecode
| 1 | from __future__ import annotations |
| 2 | |
| 3 | from typing_extensions import override |
| 4 | |
| 5 | import openai |
| 6 | from openai import AssistantEventHandler |
| 7 | from openai.types.beta import AssistantStreamEvent |
| 8 | from openai.types.beta.threads import Text, TextDelta |
| 9 | from openai.types.beta.threads.runs import RunStep, RunStepDelta |
| 10 | |
| 11 | |
| 12 | class EventHandler(AssistantEventHandler): |
| 13 | @override |
| 14 | def on_event(self, event: AssistantStreamEvent) -> None: |
| 15 | if event.event == "thread.run.step.created": |
| 16 | details = event.data.step_details |
| 17 | if details.type == "tool_calls": |
| 18 | print("Generating code to interpret:\n\n```py") |
| 19 | elif event.event == "thread.message.created": |
| 20 | print("\nResponse:\n") |
| 21 | |
| 22 | @override |
| 23 | def on_text_delta(self, delta: TextDelta, snapshot: Text) -> None: |
| 24 | print(delta.value, end="", flush=True) |
| 25 | |
| 26 | @override |
| 27 | def on_run_step_done(self, run_step: RunStep) -> None: |
| 28 | details = run_step.step_details |
| 29 | if details.type == "tool_calls": |
| 30 | for tool in details.tool_calls: |
| 31 | if tool.type == "code_interpreter": |
| 32 | print("\n```\nExecuting code...") |
| 33 | |
| 34 | @override |
| 35 | def on_run_step_delta(self, delta: RunStepDelta, snapshot: RunStep) -> None: |
| 36 | details = delta.step_details |
| 37 | if details is not None and details.type == "tool_calls": |
| 38 | for tool in details.tool_calls or []: |
| 39 | if tool.type == "code_interpreter" and tool.code_interpreter and tool.code_interpreter.input: |
| 40 | print(tool.code_interpreter.input, end="", flush=True) |
| 41 | |
| 42 | |
| 43 | def main() -> None: |
| 44 | client = openai.OpenAI() |
| 45 | |
| 46 | assistant = client.beta.assistants.create( |
| 47 | name="Math Tutor", |
| 48 | instructions="You are a personal math tutor. Write and run code to answer math questions.", |
| 49 | tools=[{"type": "code_interpreter"}], |
| 50 | model="gpt-4-1106-preview", |
| 51 | ) |
| 52 | |
| 53 | try: |
| 54 | question = "I need to solve the equation `3x + 11 = 14`. Can you help me?" |
| 55 | |
| 56 | thread = client.beta.threads.create( |
| 57 | messages=[ |
| 58 | { |
| 59 | "role": "user", |
| 60 | "content": question, |
| 61 | }, |
| 62 | ] |
| 63 | ) |
| 64 | print(f"Question: {question}\n") |
| 65 | |
| 66 | with client.beta.threads.runs.stream( |
| 67 | thread_id=thread.id, |
| 68 | assistant_id=assistant.id, |
| 69 | instructions="Please address the user as Jane Doe. The user has a premium account.", |
| 70 | event_handler=EventHandler(), |
| 71 | ) as stream: |
| 72 | stream.until_done() |
| 73 | print() |
| 74 | finally: |
| 75 | client.beta.assistants.delete(assistant.id) |
| 76 | |
| 77 | |
| 78 | main() |
| 79 | |