openai/openai-python
Publicmirrored fromhttps://github.com/openai/openai-pythonAvailable
examples/async_demo.py
30lines · modecode
| 1 | #!/usr/bin/env -S poetry run python |
| 2 | |
| 3 | import asyncio |
| 4 | |
| 5 | from openai import AsyncOpenAI |
| 6 | |
| 7 | # gets API Key from environment variable OPENAI_API_KEY |
| 8 | client = AsyncOpenAI() |
| 9 | |
| 10 | |
| 11 | async def main() -> None: |
| 12 | stream = await client.chat.completions.create( |
| 13 | model="gpt-5.5", |
| 14 | messages=[ |
| 15 | { |
| 16 | "role": "user", |
| 17 | "content": "Say this is a test", |
| 18 | }, |
| 19 | ], |
| 20 | stream=True, |
| 21 | ) |
| 22 | async for chunk in stream: |
| 23 | if not chunk.choices: |
| 24 | continue |
| 25 | |
| 26 | print(chunk.choices[0].delta.content, end="") |
| 27 | print() |
| 28 | |
| 29 | |
| 30 | asyncio.run(main()) |
| 31 | |