openai/openai-python

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v1.15.0

Branches

Tags

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

Clone

HTTPS

Download ZIP

helpers.md

215lines · modecode

1# Streaming Helpers
2
3OpenAI supports streaming responses when interacting with the [Assistant](#assistant-streaming-api) APIs.
4
5## Assistant Streaming API
6
7OpenAI supports streaming responses from Assistants. The SDK provides convenience wrappers around the API
8so you can subscribe to the types of events you are interested in as well as receive accumulated responses.
9
10More information can be found in the documentation: [Assistant Streaming](https://platform.openai.com/docs/assistants/overview?lang=python)
11
12#### An example of creating a run and subscribing to some events
13
14You can subscribe to events by creating an event handler class and overloading the relevant event handlers.
15
16```python
17from typing_extensions import override
18from openai import AssistantEventHandler, OpenAI
19from openai.types.beta.threads import Text, TextDelta
20from openai.types.beta.threads.runs import ToolCall, ToolCallDelta
21
22client = openai.OpenAI()
23
24# First, we create a EventHandler class to define
25# how we want to handle the events in the response stream.
26
27class EventHandler(AssistantEventHandler):
28 @override
29 def on_text_created(self, text: Text) -> None:
30 print(f"\nassistant > ", end="", flush=True)
31
32 @override
33 def on_text_delta(self, delta: TextDelta, snapshot: Text):
34 print(delta.value, end="", flush=True)
35
36 def on_tool_call_created(self, tool_call: ToolCall):
37 print(f"\nassistant > {tool_call.type}\n", flush=True)
38
39 def on_tool_call_delta(self, delta: ToolCallDelta, snapshot: ToolCall):
40 if delta.type == 'code_interpreter':
41 if delta.code_interpreter.input:
42 print(delta.code_interpreter.input, end="", flush=True)
43 if delta.code_interpreter.outputs:
44 print(f"\n\noutput >", flush=True)
45 for output in delta.code_interpreter.outputs:
46 if output.type == "logs":
47 print(f"\n{output.logs}", flush=True)
48
49# Then, we use the `create_and_stream` SDK helper
50# with the `EventHandler` class to create the Run
51# and stream the response.
52
53with client.beta.threads.runs.create_and_stream(
54 thread_id="thread_id",
55 assistant_id="assistant_id",
56 event_handler=EventHandler(),
57) as stream:
58 stream.until_done()
59```
60
61#### An example of iterating over events
62
63You can also iterate over all the streamed events.
64
65```python
66with client.beta.threads.runs.create_and_stream(
67 thread_id=thread.id,
68 assistant_id=assistant.id
69) as stream:
70 for event in stream:
71 # Print the text from text delta events
72 if event.type == "thread.message.delta" and event.data.delta.content:
73 print(event.data.delta.content[0].text)
74```
75
76#### An example of iterating over text
77
78You can also iterate over just the text deltas received
79
80```python
81with client.beta.threads.runs.create_and_stream(
82 thread_id=thread.id,
83 assistant_id=assistant.id
84) as stream:
85 for text in stream.text_deltas:
86 print(text)
87```
88
89### Creating Streams
90
91There are three helper methods for creating streams:
92
93```python
94client.beta.threads.runs.create_and_stream()
95```
96
97This method can be used to start and stream the response to an existing run with an associated thread
98that is already populated with messages.
99
100```python
101client.beta.threads.create_and_run_stream()
102```
103
104This method can be used to add a message to a thread, start a run and then stream the response.
105
106```python
107client.beta.threads.runs.submit_tool_outputs_stream()
108```
109
110This method can be used to submit a tool output to a run waiting on the output and start a stream.
111
112### Assistant Events
113
114The assistant API provides events you can subscribe to for the following events.
115
116```python
117def on_event(self, event: AssistantStreamEvent)
118```
119
120This allows you to subscribe to all the possible raw events sent by the OpenAI streaming API.
121In many cases it will be more convenient to subscribe to a more specific set of events for your use case.
122
123More information on the types of events can be found here: [Events](https://platform.openai.com/docs/api-reference/assistants-streaming/events)
124
125```python
126def on_run_step_created(self, run_step: RunStep)
127def on_run_step_delta(self, delta: RunStepDelta, snapshot: RunStep)
128def on_run_step_done(self, run_step: RunStep)
129```
130
131These events allow you to subscribe to the creation, delta and completion of a RunStep.
132
133For more information on how Runs and RunSteps work see the documentation [Runs and RunSteps](https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps)
134
135```python
136def on_message_created(self, message: Message)
137def on_message_delta(self, delta: MessageDelta, snapshot: Message)
138def on_message_done(self, message: Message)
139```
140
141This allows you to subscribe to Message creation, delta and completion events. Messages can contain
142different types of content that can be sent from a model (and events are available for specific content types).
143For convenience, the delta event includes both the incremental update and an accumulated snapshot of the content.
144
145More information on messages can be found
146on in the documentation page [Message](https://platform.openai.com/docs/api-reference/messages/object).
147
148```python
149def on_text_created(self, text: Text)
150def on_text_delta(self, delta: TextDelta, snapshot: Text)
151def on_text_done(self, text: Text)
152```
153
154These events allow you to subscribe to the creation, delta and completion of a Text content (a specific type of message).
155For convenience, the delta event includes both the incremental update and an accumulated snapshot of the content.
156
157```python
158def on_image_file_done(self, image_file: ImageFile)
159```
160
161Image files are not sent incrementally so an event is provided for when a image file is available.
162
163```python
164def on_tool_call_created(self, tool_call: ToolCall)
165def on_tool_call_delta(self, delta: ToolCallDelta, snapshot: ToolCall)
166def on_tool_call_done(self, tool_call: ToolCall)
167```
168
169These events allow you to subscribe to events for the creation, delta and completion of a ToolCall.
170
171More information on tools can be found here [Tools](https://platform.openai.com/docs/assistants/tools)
172
173```python
174def on_end(self)
175```
176
177The last event send when a stream ends.
178
179```python
180def on_timeout(self)
181```
182
183This event is triggered if the request times out.
184
185```python
186def on_exception(self, exception: Exception)
187```
188
189This event is triggered if an exception occurs during streaming.
190
191### Assistant Methods
192
193The assistant streaming object also provides a few methods for convenience:
194
195```python
196def current_event() -> AssistantStreamEvent | None
197def current_run() -> Run | None
198def current_message_snapshot() -> Message | None
199def current_run_step_snapshot() -> RunStep | None
200```
201
202These methods are provided to allow you to access additional context from within event handlers. In many cases
203the handlers should include all the information you need for processing, but if additional context is required it
204can be accessed.
205
206Note: There is not always a relevant context in certain situations (these will be `None` in those cases).
207
208```python
209def get_final_run(self) -> Run
210def get_final_run_steps(self) -> List[RunStep]
211def get_final_messages(self) -> List[Message]
212```
213
214These methods are provided for convenience to collect information at the end of a stream. Calling these events
215will trigger consumption of the stream until completion and then return the relevant accumulated objects.
216