openai/openai-python
Publicmirrored from https://github.com/openai/openai-pythonAvailable
examples/demo.py
38lines · modeblame
08b8179aDavid Schnurr2 years ago | 1 | #!/usr/bin/env -S poetry run python |
| 2 | | |
| 3 | from openai import OpenAI | |
| 4 | | |
| 5 | # gets API Key from environment variable OPENAI_API_KEY | |
| 6 | client = OpenAI() | |
| 7 | | |
| 8 | # Non-streaming: | |
| 9 | print("----- standard request -----") | |
| 10 | completion = client.chat.completions.create( | |
| 11 | model="gpt-4", | |
| 12 | messages=[ | |
| 13 | { | |
| 14 | "role": "user", | |
| 15 | "content": "Say this is a test", | |
| 16 | }, | |
| 17 | ], | |
| 18 | ) | |
| 19 | print(completion.choices[0].message.content) | |
| 20 | | |
| 21 | # Streaming: | |
| 22 | print("----- streaming request -----") | |
| 23 | stream = client.chat.completions.create( | |
| 24 | model="gpt-4", | |
| 25 | messages=[ | |
| 26 | { | |
| 27 | "role": "user", | |
| 28 | "content": "How do I output all files in a directory using Python?", | |
| 29 | }, | |
| 30 | ], | |
| 31 | stream=True, | |
| 32 | ) | |
| 33 | for chunk in stream: | |
| 34 | if not chunk.choices: | |
| 35 | continue | |
| 36 | | |
| 37 | print(chunk.choices[0].delta.content, end="") | |
| 38 | print() |