Skip to content

Add ChatCompletions and Audio endpoints #237

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 38 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ pip install openai[datalib]

## Usage

The 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:
The library needs to be configured with your account's secret key which is available on the [website](https://platform.openai.com/account/api-keys). Either set it as the `OPENAI_API_KEY` environment variable before using the library:

```bash
export OPENAI_API_KEY='sk-...'
Expand All @@ -57,14 +57,14 @@ Or set `openai.api_key` to its value:
import openai
openai.api_key = "sk-..."

# list engines
engines = openai.Engine.list()
# list models
models = openai.Model.list()

# print the first engine's id
print(engines.data[0].id)
# print the first model's id
print(models.data[0].id)

# create a completion
completion = openai.Completion.create(engine="ada", prompt="Hello world")
completion = openai.Completion.create(model="ada", prompt="Hello world")

# print the completion
print(completion.choices[0].text)
Expand Down Expand Up @@ -127,11 +127,14 @@ which makes it easy to interact with the API from your terminal. Run
`openai api -h` for usage.

```sh
# list engines
openai api engines.list
# list models
openai api models.list

# create a completion
openai api completions.create -e ada -p "Hello world"
openai api completions.create -m ada -p "Hello world"

# create a chat completion
openai api chat_completions.create -m gpt-3.5-turbo -g user "Hello world"

# generate images via DALL·E API
openai api image.create -p "two dogs playing chess, cartoon" -n 1
Expand All @@ -152,6 +155,18 @@ Examples of how to use this Python library to accomplish various tasks can be fo

Prior 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/).

### Chat

Conversational models such as `gpt-3.5-turbo` can be called using the chat completions endpoint.

```python
import openai
openai.api_key = "sk-..." # supply your API key however you choose

completion = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Hello world!"}])
print(completion.choices[0].message.content)
```

### Embeddings

In 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.
Expand All @@ -169,7 +184,7 @@ text_string = "sample text"
model_id = "text-similarity-davinci-001"

# compute the embedding of the text
embedding = openai.Embedding.create(input=text_string, engine=model_id)['data'][0]['embedding']
embedding = openai.Embedding.create(input=text_string, model=model_id)['data'][0]['embedding']
```

An 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).
Expand Down Expand Up @@ -208,7 +223,7 @@ For more information on fine-tuning, read the [fine-tuning guide](https://beta.o

### Moderation

OpenAI 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)
OpenAI provides a Moderation endpoint that can be used to check whether content complies with the OpenAI [content policy](https://platform.openai.com/docs/usage-policies)

```python
import openai
Expand All @@ -217,7 +232,7 @@ openai.api_key = "sk-..." # supply your API key however you choose
moderation_resp = openai.Moderation.create(input="Here is some perfectly innocuous text that follows all OpenAI content policies.")
```

See the [moderation guide](https://beta.openai.com/docs/guides/moderation) for more details.
See the [moderation guide](https://platform.openai.com/docs/guides/moderation) for more details.

## Image generation (DALL·E)

Expand All @@ -229,6 +244,15 @@ image_resp = openai.Image.create(prompt="two dogs playing chess, oil painting",

```

## Audio transcription (Whisper)
```python
import openai
openai.api_key = "sk-..." # supply your API key however you choose
f = open("path/to/file.mp3", "rb")
transcript = openai.Audio.transcribe("whisper-1", f)

```

## Async API

Async support is available in the API by prepending `a` to a network-bound method:
Expand All @@ -238,7 +262,7 @@ import openai
openai.api_key = "sk-..." # supply your API key however you choose

async def create_completion():
completion_resp = await openai.Completion.acreate(prompt="This is a test", engine="davinci")
completion_resp = await openai.Completion.acreate(prompt="This is a test", model="davinci")

```

Expand All @@ -255,7 +279,7 @@ openai.aiosession.set(ClientSession())
await openai.aiosession.get().close()
```

See the [usage guide](https://beta.openai.com/docs/guides/images) for more details.
See the [usage guide](https://platform.openai.com/docs/guides/images) for more details.

## Requirements

Expand Down
6 changes: 5 additions & 1 deletion openai/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
from typing import Optional, TYPE_CHECKING

from openai.api_resources import (
Audio,
ChatCompletion,
Completion,
Customer,
Edit,
Expand Down Expand Up @@ -52,6 +54,8 @@

__all__ = [
"APIError",
"Audio",
"ChatCompletion",
"Completion",
"Customer",
"Edit",
Expand All @@ -74,7 +78,7 @@
"app_info",
"ca_bundle_path",
"debug",
"enable_elemetry",
"enable_telemetry",
"log",
"organization",
"proxy",
Expand Down
4 changes: 2 additions & 2 deletions openai/api_requestor.py
Original file line number Diff line number Diff line change
Expand Up @@ -476,8 +476,8 @@ def _prepare_request_raw(
abs_url = _build_api_url(abs_url, encoded_params)
elif method in {"post", "put"}:
if params and files:
raise ValueError("At most one of params and files may be specified.")
if params:
data = params
if params and not files:
data = json.dumps(params).encode()
headers["Content-Type"] = "application/json"
else:
Expand Down
2 changes: 2 additions & 0 deletions openai/api_resources/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from openai.api_resources.audio import Audio # noqa: F401
from openai.api_resources.chat_completion import ChatCompletion # noqa: F401
from openai.api_resources.completion import Completion # noqa: F401
from openai.api_resources.customer import Customer # noqa: F401
from openai.api_resources.deployment import Deployment # noqa: F401
Expand Down
205 changes: 205 additions & 0 deletions openai/api_resources/audio.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
from typing import Any, List

import openai
from openai import api_requestor, util
from openai.api_resources.abstract import APIResource


class Audio(APIResource):
OBJECT_NAME = "audio"

@classmethod
def _get_url(cls, action):
return cls.class_url() + f"/{action}"

@classmethod
def _prepare_request(
cls,
file,
filename,
model,
api_key=None,
api_base=None,
api_type=None,
api_version=None,
organization=None,
**params,
):
requestor = api_requestor.APIRequestor(
api_key,
api_base=api_base or openai.api_base,
api_type=api_type,
api_version=api_version,
organization=organization,
)
files: List[Any] = []
data = {
"model": model,
**params,
}
files.append(("file", (filename, file, "application/octet-stream")))
return requestor, files, data

@classmethod
def transcribe(
cls,
model,
file,
api_key=None,
api_base=None,
api_type=None,
api_version=None,
organization=None,
**params,
):
requestor, files, data = cls._prepare_request(file, file.name, model, **params)
url = cls._get_url("transcriptions")
response, _, api_key = requestor.request("post", url, files=files, params=data)
return util.convert_to_openai_object(
response, api_key, api_version, organization
)

@classmethod
def translate(
cls,
model,
file,
api_key=None,
api_base=None,
api_type=None,
api_version=None,
organization=None,
**params,
):
requestor, files, data = cls._prepare_request(file, file.name, model, **params)
url = cls._get_url("translations")
response, _, api_key = requestor.request("post", url, files=files, params=data)
return util.convert_to_openai_object(
response, api_key, api_version, organization
)

@classmethod
def transcribe_raw(
cls,
model,
file,
filename,
api_key=None,
api_base=None,
api_type=None,
api_version=None,
organization=None,
**params,
):
requestor, files, data = cls._prepare_request(file, filename, model, **params)
url = cls._get_url("transcriptions")
response, _, api_key = requestor.request("post", url, files=files, params=data)
return util.convert_to_openai_object(
response, api_key, api_version, organization
)

@classmethod
def translate_raw(
cls,
model,
file,
filename,
api_key=None,
api_base=None,
api_type=None,
api_version=None,
organization=None,
**params,
):
requestor, files, data = cls._prepare_request(file, filename, model, **params)
url = cls._get_url("translations")
response, _, api_key = requestor.request("post", url, files=files, params=data)
return util.convert_to_openai_object(
response, api_key, api_version, organization
)

@classmethod
async def atranscribe(
cls,
model,
file,
api_key=None,
api_base=None,
api_type=None,
api_version=None,
organization=None,
**params,
):
requestor, files, data = cls._prepare_request(file, file.name, model, **params)
url = cls._get_url("transcriptions")
response, _, api_key = await requestor.arequest(
"post", url, files=files, params=data
)
return util.convert_to_openai_object(
response, api_key, api_version, organization
)

@classmethod
async def atranslate(
cls,
model,
file,
api_key=None,
api_base=None,
api_type=None,
api_version=None,
organization=None,
**params,
):
requestor, files, data = cls._prepare_request(file, file.name, model, **params)
url = cls._get_url("translations")
response, _, api_key = await requestor.arequest(
"post", url, files=files, params=data
)
return util.convert_to_openai_object(
response, api_key, api_version, organization
)

@classmethod
async def atranscribe_raw(
cls,
model,
file,
filename,
api_key=None,
api_base=None,
api_type=None,
api_version=None,
organization=None,
**params,
):
requestor, files, data = cls._prepare_request(file, filename, model, **params)
url = cls._get_url("transcriptions")
response, _, api_key = await requestor.arequest(
"post", url, files=files, params=data
)
return util.convert_to_openai_object(
response, api_key, api_version, organization
)

@classmethod
async def atranslate_raw(
cls,
model,
file,
filename,
api_key=None,
api_base=None,
api_type=None,
api_version=None,
organization=None,
**params,
):
requestor, files, data = cls._prepare_request(file, filename, model, **params)
url = cls._get_url("translations")
response, _, api_key = await requestor.arequest(
"post", url, files=files, params=data
)
return util.convert_to_openai_object(
response, api_key, api_version, organization
)
Loading