openai/openai-python
Publicmirrored from https://github.com/openai/openai-pythonAvailable
examples/responses/background.py
46lines · modeblame
f588695fstainless-app[bot]1 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 | id = None | |
| 21 | | |
| 22 | with client.responses.create( | |
| 23 | input="solve 8x + 31 = 2", | |
| 24 | model="gpt-4o-2024-08-06", | |
| 25 | background=True, | |
| 26 | stream=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.retrieve( | |
| 40 | response_id=id, | |
| 41 | stream=True, | |
| 42 | starting_after=10, | |
| 43 | ) as stream: | |
| 44 | for event in stream: | |
| 45 | if "output_text" in event.type: | |
| 46 | rich.print(event) |