openai/openai-python

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v1.103.0

Branches

Tags

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

Clone

HTTPS

Download ZIP

examples/demo.py

53lines · modeblame

08b8179aDavid Schnurr2 years ago1#!/usr/bin/env -S poetry run python
2
3from openai import OpenAI
4
5# gets API Key from environment variable OPENAI_API_KEY
6client = OpenAI()
7
8# Non-streaming:
9print("----- standard request -----")
10completion = client.chat.completions.create(
11model="gpt-4",
12messages=[
13{
14"role": "user",
15"content": "Say this is a test",
16},
17],
18)
19print(completion.choices[0].message.content)
20
21# Streaming:
22print("----- streaming request -----")
23stream = client.chat.completions.create(
24model="gpt-4",
25messages=[
26{
27"role": "user",
28"content": "How do I output all files in a directory using Python?",
29},
30],
31stream=True,
32)
33for chunk in stream:
34if not chunk.choices:
35continue
36
37print(chunk.choices[0].delta.content, end="")
38print()
0311d6b5Stainless Bot2 years ago39
40# Response headers:
41print("----- custom response headers test -----")
42response = client.chat.completions.with_raw_response.create(
43model="gpt-4",
44messages=[
45{
46"role": "user",
47"content": "Say this is a test",
48}
49],
50)
51completion = response.parse()
52print(response.request_id)
53print(completion.choices[0].message.content)