openai/openai-python

Public

mirrored from https://github.com/openai/openai-pythonAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v1.14.1

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

examples/assistant_stream_helpers.py

78lines · modeblame

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