openai/openai-python
Publicmirrored from https://github.com/openai/openai-pythonAvailable
examples/responses/streaming.py
30lines · modeblame
2954945eRobert Craigie1 years ago | 1 | from typing import List |
| 2 | | |
| 3 | import rich | |
| 4 | from pydantic import BaseModel | |
| 5 | | |
| 6 | from openai import OpenAI | |
| 7 | | |
| 8 | | |
| 9 | class Step(BaseModel): | |
| 10 | explanation: str | |
| 11 | output: str | |
| 12 | | |
| 13 | | |
| 14 | class MathResponse(BaseModel): | |
| 15 | steps: List[Step] | |
| 16 | final_answer: str | |
| 17 | | |
| 18 | | |
| 19 | client = OpenAI() | |
| 20 | | |
| 21 | with client.responses.stream( | |
| 22 | input="solve 8x + 31 = 2", | |
| 23 | model="gpt-4o-2024-08-06", | |
| 24 | text_format=MathResponse, | |
| 25 | ) as stream: | |
| 26 | for event in stream: | |
| 27 | if "output_text" in event.type: | |
| 28 | rich.print(event) | |
| 29 | | |
| 30 | rich.print(stream.get_final_response()) |