openai/openai-python
Publicmirrored from https://github.com/openai/openai-pythonAvailable
helpers.md
215lines · modecode
| 1 | # Streaming Helpers |
| 2 | |
| 3 | OpenAI supports streaming responses when interacting with the [Assistant](#assistant-streaming-api) APIs. |
| 4 | |
| 5 | ## Assistant Streaming API |
| 6 | |
| 7 | OpenAI supports streaming responses from Assistants. The SDK provides convenience wrappers around the API |
| 8 | so you can subscribe to the types of events you are interested in as well as receive accumulated responses. |
| 9 | |
| 10 | More 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 | |
| 14 | You can subscribe to events by creating an event handler class and overloading the relevant event handlers. |
| 15 | |
| 16 | ```python |
| 17 | from typing_extensions import override |
| 18 | from openai import AssistantEventHandler, OpenAI |
| 19 | from openai.types.beta.threads import Text, TextDelta |
| 20 | from openai.types.beta.threads.runs import ToolCall, ToolCallDelta |
| 21 | |
| 22 | client = 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 | |
| 27 | class 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 | |
| 53 | with 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 | |
| 63 | You can also iterate over all the streamed events. |
| 64 | |
| 65 | ```python |
| 66 | with 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 | |
| 78 | You can also iterate over just the text deltas received |
| 79 | |
| 80 | ```python |
| 81 | with 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 | |
| 91 | There are three helper methods for creating streams: |
| 92 | |
| 93 | ```python |
| 94 | client.beta.threads.runs.create_and_stream() |
| 95 | ``` |
| 96 | |
| 97 | This method can be used to start and stream the response to an existing run with an associated thread |
| 98 | that is already populated with messages. |
| 99 | |
| 100 | ```python |
| 101 | client.beta.threads.create_and_run_stream() |
| 102 | ``` |
| 103 | |
| 104 | This method can be used to add a message to a thread, start a run and then stream the response. |
| 105 | |
| 106 | ```python |
| 107 | client.beta.threads.runs.submit_tool_outputs_stream() |
| 108 | ``` |
| 109 | |
| 110 | This 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 | |
| 114 | The assistant API provides events you can subscribe to for the following events. |
| 115 | |
| 116 | ```python |
| 117 | def on_event(self, event: AssistantStreamEvent) |
| 118 | ``` |
| 119 | |
| 120 | This allows you to subscribe to all the possible raw events sent by the OpenAI streaming API. |
| 121 | In many cases it will be more convenient to subscribe to a more specific set of events for your use case. |
| 122 | |
| 123 | More information on the types of events can be found here: [Events](https://platform.openai.com/docs/api-reference/assistants-streaming/events) |
| 124 | |
| 125 | ```python |
| 126 | def on_run_step_created(self, run_step: RunStep) |
| 127 | def on_run_step_delta(self, delta: RunStepDelta, snapshot: RunStep) |
| 128 | def on_run_step_done(self, run_step: RunStep) |
| 129 | ``` |
| 130 | |
| 131 | These events allow you to subscribe to the creation, delta and completion of a RunStep. |
| 132 | |
| 133 | For 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 |
| 136 | def on_message_created(self, message: Message) |
| 137 | def on_message_delta(self, delta: MessageDelta, snapshot: Message) |
| 138 | def on_message_done(self, message: Message) |
| 139 | ``` |
| 140 | |
| 141 | This allows you to subscribe to Message creation, delta and completion events. Messages can contain |
| 142 | different types of content that can be sent from a model (and events are available for specific content types). |
| 143 | For convenience, the delta event includes both the incremental update and an accumulated snapshot of the content. |
| 144 | |
| 145 | More information on messages can be found |
| 146 | on in the documentation page [Message](https://platform.openai.com/docs/api-reference/messages/object). |
| 147 | |
| 148 | ```python |
| 149 | def on_text_created(self, text: Text) |
| 150 | def on_text_delta(self, delta: TextDelta, snapshot: Text) |
| 151 | def on_text_done(self, text: Text) |
| 152 | ``` |
| 153 | |
| 154 | These events allow you to subscribe to the creation, delta and completion of a Text content (a specific type of message). |
| 155 | For convenience, the delta event includes both the incremental update and an accumulated snapshot of the content. |
| 156 | |
| 157 | ```python |
| 158 | def on_image_file_done(self, image_file: ImageFile) |
| 159 | ``` |
| 160 | |
| 161 | Image files are not sent incrementally so an event is provided for when a image file is available. |
| 162 | |
| 163 | ```python |
| 164 | def on_tool_call_created(self, tool_call: ToolCall) |
| 165 | def on_tool_call_delta(self, delta: ToolCallDelta, snapshot: ToolCall) |
| 166 | def on_tool_call_done(self, tool_call: ToolCall) |
| 167 | ``` |
| 168 | |
| 169 | These events allow you to subscribe to events for the creation, delta and completion of a ToolCall. |
| 170 | |
| 171 | More information on tools can be found here [Tools](https://platform.openai.com/docs/assistants/tools) |
| 172 | |
| 173 | ```python |
| 174 | def on_end(self) |
| 175 | ``` |
| 176 | |
| 177 | The last event send when a stream ends. |
| 178 | |
| 179 | ```python |
| 180 | def on_timeout(self) |
| 181 | ``` |
| 182 | |
| 183 | This event is triggered if the request times out. |
| 184 | |
| 185 | ```python |
| 186 | def on_exception(self, exception: Exception) |
| 187 | ``` |
| 188 | |
| 189 | This event is triggered if an exception occurs during streaming. |
| 190 | |
| 191 | ### Assistant Methods |
| 192 | |
| 193 | The assistant streaming object also provides a few methods for convenience: |
| 194 | |
| 195 | ```python |
| 196 | def current_event() -> AssistantStreamEvent | None |
| 197 | def current_run() -> Run | None |
| 198 | def current_message_snapshot() -> Message | None |
| 199 | def current_run_step_snapshot() -> RunStep | None |
| 200 | ``` |
| 201 | |
| 202 | These methods are provided to allow you to access additional context from within event handlers. In many cases |
| 203 | the handlers should include all the information you need for processing, but if additional context is required it |
| 204 | can be accessed. |
| 205 | |
| 206 | Note: There is not always a relevant context in certain situations (these will be `None` in those cases). |
| 207 | |
| 208 | ```python |
| 209 | def get_final_run(self) -> Run |
| 210 | def get_final_run_steps(self) -> List[RunStep] |
| 211 | def get_final_messages(self) -> List[Message] |
| 212 | ``` |
| 213 | |
| 214 | These methods are provided for convenience to collect information at the end of a stream. Calling these events |
| 215 | will trigger consumption of the stream until completion and then return the relevant accumulated objects. |
| 216 | |