Skip to content
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
4 changes: 4 additions & 0 deletions portkey_ai/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,8 @@
AsyncIntegrationsModels,
Providers,
AsyncProviders,
Webhooks,
AsyncWebhooks,
)

from portkey_ai.version import VERSION
Expand Down Expand Up @@ -281,4 +283,6 @@
"AsyncIntegrationsModels",
"Providers",
"AsyncProviders",
"Webhooks",
"AsyncWebhooks",
]
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
Metadata-Version: 2.3
Name: openai
Version: 1.86.0
Version: 1.99.6
Summary: The official Python library for the openai API
Project-URL: Homepage, https://github.com/openai/openai-python
Project-URL: Repository, https://github.com/openai/openai-python
Expand All @@ -18,6 +18,7 @@ Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.8
Expand All @@ -29,6 +30,9 @@ Requires-Dist: pydantic<3,>=1.9.0
Requires-Dist: sniffio
Requires-Dist: tqdm>4
Requires-Dist: typing-extensions<5,>=4.11
Provides-Extra: aiohttp
Requires-Dist: aiohttp; extra == 'aiohttp'
Requires-Dist: httpx-aiohttp>=0.1.8; extra == 'aiohttp'
Provides-Extra: datalib
Requires-Dist: numpy>=1; extra == 'datalib'
Requires-Dist: pandas-stubs>=1.1.0.11; extra == 'datalib'
Expand All @@ -42,7 +46,8 @@ Description-Content-Type: text/markdown

# OpenAI Python API library

[![PyPI version](https://img.shields.io/pypi/v/openai.svg)](https://pypi.org/project/openai/)
<!-- prettier-ignore -->
[![PyPI version](https://img.shields.io/pypi/v/openai.svg?label=pypi%20(stable))](https://pypi.org/project/openai/)

The OpenAI Python library provides convenient access to the OpenAI REST API from any Python 3.8+
application. The library includes type definitions for all request params and response fields,
Expand Down Expand Up @@ -187,6 +192,44 @@ asyncio.run(main())

Functionality between the synchronous and asynchronous clients is otherwise identical.

### With aiohttp

By default, the async client uses `httpx` for HTTP requests. However, for improved concurrency performance you may also use `aiohttp` as the HTTP backend.

You can enable this by installing `aiohttp`:

```sh
# install from PyPI
pip install openai[aiohttp]
```

Then you can enable it by instantiating the client with `http_client=DefaultAioHttpClient()`:

```python
import asyncio
from openai import DefaultAioHttpClient
from openai import AsyncOpenAI


async def main() -> None:
async with AsyncOpenAI(
api_key="My API Key",
http_client=DefaultAioHttpClient(),
) as client:
chat_completion = await client.chat.completions.create(
messages=[
{
"role": "user",
"content": "Say this is a test",
}
],
model="gpt-4o",
)


asyncio.run(main())
```

## Streaming responses

We provide support for streaming responses using Server Side Events (SSE).
Expand Down Expand Up @@ -409,6 +452,86 @@ client.files.create(

The async client uses the exact same interface. If you pass a [`PathLike`](https://docs.python.org/3/library/os.html#os.PathLike) instance, the file contents will be read asynchronously automatically.

## Webhook Verification

Verifying webhook signatures is _optional but encouraged_.

For more information about webhooks, see [the API docs](https://platform.openai.com/docs/guides/webhooks).

### Parsing webhook payloads

For most use cases, you will likely want to verify the webhook and parse the payload at the same time. To achieve this, we provide the method `client.webhooks.unwrap()`, which parses a webhook request and verifies that it was sent by OpenAI. This method will raise an error if the signature is invalid.

Note that the `body` parameter must be the raw JSON string sent from the server (do not parse it first). The `.unwrap()` method will parse this JSON for you into an event object after verifying the webhook was sent from OpenAI.

```python
from openai import OpenAI
from flask import Flask, request

app = Flask(__name__)
client = OpenAI() # OPENAI_WEBHOOK_SECRET environment variable is used by default


@app.route("/webhook", methods=["POST"])
def webhook():
request_body = request.get_data(as_text=True)

try:
event = client.webhooks.unwrap(request_body, request.headers)

if event.type == "response.completed":
print("Response completed:", event.data)
elif event.type == "response.failed":
print("Response failed:", event.data)
else:
print("Unhandled event type:", event.type)

return "ok"
except Exception as e:
print("Invalid signature:", e)
return "Invalid signature", 400


if __name__ == "__main__":
app.run(port=8000)
```

### Verifying webhook payloads directly

In some cases, you may want to verify the webhook separately from parsing the payload. If you prefer to handle these steps separately, we provide the method `client.webhooks.verify_signature()` to _only verify_ the signature of a webhook request. Like `.unwrap()`, this method will raise an error if the signature is invalid.

Note that the `body` parameter must be the raw JSON string sent from the server (do not parse it first). You will then need to parse the body after verifying the signature.

```python
import json
from openai import OpenAI
from flask import Flask, request

app = Flask(__name__)
client = OpenAI() # OPENAI_WEBHOOK_SECRET environment variable is used by default


@app.route("/webhook", methods=["POST"])
def webhook():
request_body = request.get_data(as_text=True)

try:
client.webhooks.verify_signature(request_body, request.headers)

# Parse the body after verification
event = json.loads(request_body)
print("Verified event:", event)

return "ok"
except Exception as e:
print("Invalid signature:", e)
return "Invalid signature", 400


if __name__ == "__main__":
app.run(port=8000)
```

## Handling errors

When the library is unable to connect to the API (for example, due to network connection problems or a timeout), a subclass of `openai.APIConnectionError` is raised.
Expand Down
Loading