openai/openai-python
Publicmirrored from https://github.com/openai/openai-pythonAvailable
examples/responses/background_streaming.py
48lines · modeblame
f588695fstainless-app[bot]1 years ago | 1 | #!/usr/bin/env -S rye run python |
| 2 | from typing import List | |
| 3 | | |
| 4 | import rich | |
| 5 | from pydantic import BaseModel | |
| 6 | | |
| 7 | from openai import OpenAI | |
| 8 | | |
| 9 | | |
| 10 | class Step(BaseModel): | |
| 11 | explanation: str | |
| 12 | output: str | |
| 13 | | |
| 14 | | |
| 15 | class MathResponse(BaseModel): | |
| 16 | steps: List[Step] | |
| 17 | final_answer: str | |
| 18 | | |
| 19 | | |
| 20 | client = OpenAI() | |
| 21 | id = None | |
| 22 | with client.responses.stream( | |
| 23 | input="solve 8x + 31 = 2", | |
| 24 | model="gpt-4o-2024-08-06", | |
| 25 | text_format=MathResponse, | |
| 26 | background=True, | |
| 27 | ) as stream: | |
| 28 | for event in stream: | |
| 29 | if event.type == "response.created": | |
| 30 | id = event.response.id | |
| 31 | if "output_text" in event.type: | |
| 32 | rich.print(event) | |
| 33 | if event.sequence_number == 10: | |
| 34 | break | |
| 35 | | |
| 36 | print("Interrupted. Continuing...") | |
| 37 | | |
| 38 | assert id is not None | |
| 39 | with client.responses.stream( | |
| 40 | response_id=id, | |
| 41 | starting_after=10, | |
| 42 | text_format=MathResponse, | |
| 43 | ) as stream: | |
| 44 | for event in stream: | |
| 45 | if "output_text" in event.type: | |
| 46 | rich.print(event) | |
| 47 | | |
| 48 | rich.print(stream.get_final_response()) |