openai/openai-python
Publicmirrored fromhttps://github.com/openai/openai-pythonAvailable
examples/demo.py
53lines · modecode
| 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() |
| 39 | |
| 40 | # Response headers: |
| 41 | print("----- custom response headers test -----") |
| 42 | response = client.chat.completions.with_raw_response.create( |
| 43 | model="gpt-4", |
| 44 | messages=[ |
| 45 | { |
| 46 | "role": "user", |
| 47 | "content": "Say this is a test", |
| 48 | } |
| 49 | ], |
| 50 | ) |
| 51 | completion = response.parse() |
| 52 | print(response.request_id) |
| 53 | print(completion.choices[0].message.content) |
| 54 | |