openai/openai-python
Publicmirrored fromhttps://github.com/openai/openai-pythonAvailable
examples/responses/background_async.py
52lines · modecode
| 1 | import asyncio |
| 2 | from typing import List |
| 3 | |
| 4 | import rich |
| 5 | from pydantic import BaseModel |
| 6 | |
| 7 | from openai._client import AsyncOpenAI |
| 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 | async def main() -> None: |
| 21 | client = AsyncOpenAI() |
| 22 | id = None |
| 23 | |
| 24 | async with await client.responses.create( |
| 25 | input="solve 8x + 31 = 2", |
| 26 | model="gpt-4o-2024-08-06", |
| 27 | background=True, |
| 28 | stream=True, |
| 29 | ) as stream: |
| 30 | async for event in stream: |
| 31 | if event.type == "response.created": |
| 32 | id = event.response.id |
| 33 | if "output_text" in event.type: |
| 34 | rich.print(event) |
| 35 | if event.sequence_number == 10: |
| 36 | break |
| 37 | |
| 38 | print("Interrupted. Continuing...") |
| 39 | |
| 40 | assert id is not None |
| 41 | async with await client.responses.retrieve( |
| 42 | response_id=id, |
| 43 | stream=True, |
| 44 | starting_after=10, |
| 45 | ) as stream: |
| 46 | async for event in stream: |
| 47 | if "output_text" in event.type: |
| 48 | rich.print(event) |
| 49 | |
| 50 | |
| 51 | if __name__ == "__main__": |
| 52 | asyncio.run(main()) |