openai/openai-python

Public

mirrored from https://github.com/openai/openai-pythonAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v2.31.0

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

examples/responses/background_async.py

52lines · modeblame

f588695fstainless-app[bot]1 years ago1import asyncio
2from typing import List
3
4import rich
5from pydantic import BaseModel
6
7from openai._client import AsyncOpenAI
8
9
10class Step(BaseModel):
11explanation: str
12output: str
13
14
15class MathResponse(BaseModel):
16steps: List[Step]
17final_answer: str
18
19
20async def main() -> None:
21client = AsyncOpenAI()
22id = None
23
24async with await client.responses.create(
25input="solve 8x + 31 = 2",
26model="gpt-4o-2024-08-06",
27background=True,
28stream=True,
29) as stream:
30async for event in stream:
31if event.type == "response.created":
32id = event.response.id
33if "output_text" in event.type:
34rich.print(event)
35if event.sequence_number == 10:
36break
37
38print("Interrupted. Continuing...")
39
40assert id is not None
41async with await client.responses.retrieve(
42response_id=id,
43stream=True,
44starting_after=10,
45) as stream:
46async for event in stream:
47if "output_text" in event.type:
48rich.print(event)
49
50
51if __name__ == "__main__":
52asyncio.run(main())