openai api behind Oauth2? #2425
Replies: 2 comments
-
|
You can do this without subclassing by using the Here's a clean approach: import httpx
from openai import OpenAI
class OAuth2Auth(httpx.Auth):
def __init__(self, token_url, client_id, client_secret):
self.token_url = token_url
self.client_id = client_id
self.client_secret = client_secret
self._token = None
def auth_flow(self, request):
if not self._token:
self._fetch_token()
request.headers["Authorization"] = f"Bearer {self._token}"
yield request
def _fetch_token(self):
resp = httpx.post(
self.token_url,
data={
"grant_type": "client_credentials",
"client_id": self.client_id,
"client_secret": self.client_secret,
},
)
resp.raise_for_status()
self._token = resp.json()["access_token"]
auth = OAuth2Auth(
token_url="https://your-idp.com/oauth/token",
client_id="your-client-id",
client_secret="your-client-secret",
)
http_client = httpx.Client(auth=auth)
client = OpenAI(
base_url="https://your-proxy-endpoint.com/v1",
api_key="unused", # set to any string; your proxy handles real auth
http_client=http_client,
)
# Now use it normally
response = client.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": "Hello"}],
)Key points:
If your proxy expects the OpenAI API key in addition to the OAuth2 token, keep |
Beta Was this translation helpful? Give feedback.
-
Using the OpenAI client with a custom OAuth2 proxyYou can achieve this with Approach 1: Custom
|
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I'm working on a project where we have openai protected behind a Oauth2 endpoint. Which works like a proxy, it recieves api calls we need to authenticate with oauth2 and then the requests are forwarded to I believe Azure openai.
I would like to use the official openai python client instead of writting my own httpx wrapper around the api. So I basically need to override the OpenAI class and implement my own authentication flow.
Can someone tell me how to do this? Which methods should I override? Are there examples of this I can use as reference? All help would be appreciated.
Beta Was this translation helpful? Give feedback.
All reactions