openai/openai-python

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
3c00e856ad71fa69ac40a228a070b59688dfdee2

Branches

Tags

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

Clone

HTTPS

Download ZIP

README.md

231lines · modecode

1# OpenAI Python Library
2
3The OpenAI Python library provides convenient access to the OpenAI API
4from applications written in the Python language. It includes a
5pre-defined set of classes for API resources that initialize
6themselves dynamically from API responses which makes it compatible
7with a wide range of versions of the OpenAI API.
8
9## Documentation
10
11See the [OpenAI API docs](https://beta.openai.com/docs/api-reference?lang=python).
12
13## Installation
14
15You don't need this source code unless you want to modify the package. If you just
16want to use the package, just run:
17
18```sh
19pip install --upgrade openai
20```
21
22Install from source with:
23
24```sh
25python setup.py install
26```
27
28## Usage
29
30The library needs to be configured with your account's secret key which is available on the [website](https://beta.openai.com/account/api-keys). Either set it as the `OPENAI_API_KEY` environment variable before using the library:
31
32```bash
33export OPENAI_API_KEY='sk-...'
34```
35
36Or set `openai.api_key` to its value:
37
38```python
39import openai
40openai.api_key = "sk-..."
41
42# list engines
43engines = openai.Engine.list()
44
45# print the first engine's id
46print(engines.data[0].id)
47
48# create a completion
49completion = openai.Completion.create(engine="ada", prompt="Hello world")
50
51# print the completion
52print(completion.choices[0].text)
53```
54
55
56### Params
57All endpoints have a `.create` method that support a `request_timeout` param. This param takes a `Union[float, Tuple[float, float]]` and will raise a `openai.error.TimeoutError` error if the request exceeds that time in seconds (See: https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts).
58
59### Microsoft Azure Endpoints
60
61In order to use the library with Microsoft Azure endpoints, you need to set the api_type, api_base and api_version in addition to the api_key. The api_type must be set to 'azure' and the others correspond to the properties of your endpoint.
62In addition, the deployment name must be passed as the engine parameter.
63
64```python
65import openai
66openai.api_type = "azure"
67openai.api_key = "..."
68openai.api_base = "https://example-endpoint.openai.azure.com"
69openai.api_version = "2021-11-01-preview"
70
71# create a completion
72completion = openai.Completion.create(engine="deployment-name", prompt="Hello world")
73
74# print the completion
75print(completion.choices[0].text)
76
77# create a search and pass the deployment-name as the engine Id.
78search = openai.Engine(id="deployment-name").search(documents=["White House", "hospital", "school"], query ="the president")
79
80# print the search
81print(search)
82```
83
84Please note that for the moment, the Microsoft Azure endpoints can only be used for completion, search and fine-tuning operations.
85For a detailed example on how to use fine-tuning and other operations using Azure endpoints, please check out the following Jupyter notebooks:
86* [Using Azure fine-tuning](https://github.com/openai/openai-cookbook/tree/main/examples/azure/finetuning.ipynb)
87* [Using Azure embeddings](https://github.com/openai/openai-cookbook/blob/main/examples/azure/embeddings.ipynb)
88
89### Microsoft Azure Active Directory Authentication
90
91In order to use Microsoft Active Directory to authenticate to your Azure endpoint, you need to set the api_type to "azure_ad" and pass the acquired credential token to api_key. The rest of the parameters need to be set as specified in the previous section.
92
93
94```python
95from azure.identity import DefaultAzureCredential
96import openai
97
98# Request credential
99default_credential = DefaultAzureCredential()
100token = default_credential.get_token("https://cognitiveservices.azure.com")
101
102# Setup parameters
103openai.api_type = "azure_ad"
104openai.api_key = token.token
105openai.api_base = "https://example-endpoint.openai.azure.com/"
106openai.api_version = "2022-03-01-preview"
107
108# ...
109```
110### Command-line interface
111
112This library additionally provides an `openai` command-line utility
113which makes it easy to interact with the API from your terminal. Run
114`openai api -h` for usage.
115
116```sh
117# list engines
118openai api engines.list
119
120# create a completion
121openai api completions.create -e ada -p "Hello world"
122
123# generate images via DALL·E API
124openai api image.create -p "two dogs playing chess, cartoon" -n 1
125```
126
127## Example code
128
129Examples of how to use this Python library to accomplish various tasks can be found in the [OpenAI Cookbook](https://github.com/openai/openai-cookbook/). It contains code examples for:
130
131* Classification using fine-tuning
132* Clustering
133* Code search
134* Customizing embeddings
135* Question answering from a corpus of documents
136* Recommendations
137* Visualization of embeddings
138* And more
139
140Prior to July 2022, this OpenAI Python library hosted code examples in its examples folder, but since then all examples have been migrated to the [OpenAI Cookbook](https://github.com/openai/openai-cookbook/).
141
142### Embeddings
143
144In the OpenAI Python library, an embedding represents a text string as a fixed-length vector of floating point numbers. Embeddings are designed to measure the similarity or relevance between text strings.
145
146To get an embedding for a text string, you can use the embeddings method as follows in Python:
147
148```python
149import openai
150openai.api_key = "sk-..." # supply your API key however you choose
151
152# choose text to embed
153text_string = "sample text"
154
155# choose an embedding
156model_id = "text-similarity-davinci-001"
157
158# compute the embedding of the text
159embedding = openai.Embedding.create(input=text_string, engine=model_id)['data'][0]['embedding']
160```
161
162An example of how to call the embeddings method is shown in this [get embeddings notebook](https://github.com/openai/openai-cookbook/blob/main/examples/Get_embeddings.ipynb).
163
164Examples of how to use embeddings are shared in the following Jupyter notebooks:
165
166- [Classification using embeddings](https://github.com/openai/openai-cookbook/blob/main/examples/Classification_using_embeddings.ipynb)
167- [Clustering using embeddings](https://github.com/openai/openai-cookbook/blob/main/examples/Clustering.ipynb)
168- [Code search using embeddings](https://github.com/openai/openai-cookbook/blob/main/examples/Code_search.ipynb)
169- [Semantic text search using embeddings](https://github.com/openai/openai-cookbook/blob/main/examples/Semantic_text_search_using_embeddings.ipynb)
170- [User and product embeddings](https://github.com/openai/openai-cookbook/blob/main/examples/User_and_product_embeddings.ipynb)
171- [Zero-shot classification using embeddings](https://github.com/openai/openai-cookbook/blob/main/examples/Zero-shot_classification_with_embeddings.ipynb)
172- [Recommendation using embeddings](https://github.com/openai/openai-cookbook/blob/main/examples/Recommendation_using_embeddings.ipynb)
173
174For more information on embeddings and the types of embeddings OpenAI offers, read the [embeddings guide](https://beta.openai.com/docs/guides/embeddings) in the OpenAI documentation.
175
176### Fine tuning
177
178Fine tuning a model on training data can both improve the results (by giving the model more examples to learn from) and reduce the cost/latency of API calls (chiefly through reducing the need to include training examples in prompts).
179
180Examples of fine tuning are shared in the following Jupyter notebooks:
181
182- [Classification with fine tuning](https://github.com/openai/openai-cookbook/blob/main/examples/Fine-tuned_classification.ipynb) (a simple notebook that shows the steps required for fine tuning)
183- Fine tuning a model that answers questions about the 2020 Olympics
184 - [Step 1: Collecting data](https://github.com/openai/openai-cookbook/blob/main/examples/fine-tuned_qa/olympics-1-collect-data.ipynb)
185 - [Step 2: Creating a synthetic Q&A dataset](https://github.com/openai/openai-cookbook/blob/main/examples/fine-tuned_qa/olympics-2-create-qa.ipynb)
186 - [Step 3: Train a fine-tuning model specialized for Q&A](https://github.com/openai/openai-cookbook/blob/main/examples/fine-tuned_qa/olympics-3-train-qa.ipynb)
187
188Sync your fine-tunes to [Weights & Biases](https://wandb.me/openai-docs) to track experiments, models, and datasets in your central dashboard with:
189
190```bash
191openai wandb sync
192```
193
194For more information on fine tuning, read the [fine-tuning guide](https://beta.openai.com/docs/guides/fine-tuning) in the OpenAI documentation.
195
196### Moderation
197
198OpenAI provides a Moderation endpoint that can be used to check whether content complies with the OpenAI [content policy](https://beta.openai.com/docs/usage-policies)
199
200```python
201import openai
202openai.api_key = "sk-..." # supply your API key however you choose
203
204moderation_resp = openai.Moderation.create(input="Here is some perfectly innocuous text that follows all OpenAI content policies.")
205```
206
207See the [moderation guide](https://beta.openai.com/docs/guides/moderation) for more details.
208
209## Image generation (DALL·E)
210
211```python
212import openai
213openai.api_key = "sk-..." # supply your API key however you choose
214
215image_resp = openai.Image.create(prompt="two dogs playing chess, oil painting", n=4, size="512x512")
216
217```
218
219See the [usage guide](https://beta.openai.com/docs/guides/images) for more details.
220
221## Requirements
222
223- Python 3.7.1+
224
225In general, we want to support the versions of Python that our
226customers are using. If you run into problems with any version
227issues, please let us know at support@openai.com.
228
229## Credit
230
231This library is forked from the [Stripe Python Library](https://github.com/stripe/stripe-python).