openai/openai-python

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v1.1.1

Branches

Tags

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

Clone

HTTPS

Download ZIP

examples/streaming.py

56lines · modeblame

08b8179aDavid Schnurr2 years ago1#!/usr/bin/env -S poetry run python
2
3import asyncio
4
5from openai import OpenAI, AsyncOpenAI
6
7# This script assumes you have the OPENAI_API_KEY environment variable set to a valid OpenAI API key.
8#
9# You can run this script from the root directory like so:
10# `python examples/streaming.py`
11
12
13def sync_main() -> None:
14client = OpenAI()
15response = client.completions.create(
16model="text-davinci-002",
17prompt="1,2,3,",
18max_tokens=5,
19temperature=0,
20stream=True,
21)
22
23# You can manually control iteration over the response
24first = next(response)
25print(f"got response data: {first.model_dump_json(indent=2)}")
26
27# Or you could automatically iterate through all of data.
28# Note that the for loop will not exit until *all* of the data has been processed.
29for data in response:
30print(data.model_dump_json())
31
32
33async def async_main() -> None:
34client = AsyncOpenAI()
35response = await client.completions.create(
36model="text-davinci-002",
37prompt="1,2,3,",
38max_tokens=5,
39temperature=0,
40stream=True,
41)
42
43# You can manually control iteration over the response.
44# In Python 3.10+ you can also use the `await anext(response)` builtin instead
45first = await response.__anext__()
46print(f"got response data: {first.model_dump_json(indent=2)}")
47
48# Or you could automatically iterate through all of data.
49# Note that the for loop will not exit until *all* of the data has been processed.
50async for data in response:
51print(data.model_dump_json())
52
53
54sync_main()
55
56asyncio.run(async_main())