Repository navigation
Expand file tree
/
Copy pathstreaming.py
More file actions
executable file
·62 lines (48 loc) · 1.67 KB
/
Copy pathstreaming.py
File metadata and controls
executable file
·62 lines (48 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/usr/bin/env -S uv run python
import asyncio
from openai import OpenAI, AsyncOpenAI
# This script assumes you have the OPENAI_API_KEY environment variable set to a valid OpenAI API key.
#
# You can run this script from the root directory like so:
# `python examples/streaming.py`
def sync_main() -> None:
client = OpenAI()
response = client.chat.completions.create(
model="gpt-5.5",
messages=[
{
"role": "user",
"content": "Count from 1 to 5.",
},
],
stream=True,
)
# You can manually control iteration over the response
first = next(response)
print(f"got response data: {first.to_json()}")
# Or you could automatically iterate through all of data.
# Note that the for loop will not exit until *all* of the data has been processed.
for data in response:
print(data.to_json())
async def async_main() -> None:
client = AsyncOpenAI()
response = await client.chat.completions.create(
model="gpt-5.5",
messages=[
{
"role": "user",
"content": "Count from 1 to 5.",
},
],
stream=True,
)
# You can manually control iteration over the response.
# In Python 3.10+ you can also use the `await anext(response)` builtin instead
first = await response.__anext__()
print(f"got response data: {first.to_json()}")
# Or you could automatically iterate through all of data.
# Note that the for loop will not exit until *all* of the data has been processed.
async for data in response:
print(data.to_json())
sync_main()
asyncio.run(async_main())