Skip to content

Instantly share code, notes, and snippets.

@clemlesne
Last active November 10, 2023 10:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clemlesne/312a7f1fc07ec36302935b6a1687710e to your computer and use it in GitHub Desktop.
Save clemlesne/312a7f1fc07ec36302935b6a1687710e to your computer and use it in GitHub Desktop.
OpenAI SDK wrapper for Azure AD authentications
from azure.identity import DefaultAzureCredential
from typing import Awaitable
import asyncio
import openai
# Set up the Azure credential
credential = DefaultAzureCredential()
def openai_refresh() -> None:
"""
Refreshes the OpenAI API key using the Azure credential.
"""
openai.api_key = credential.get_token().token
# First refresh
openai_refresh()
async def completion_wrapper(prompt: str) -> Awaitable[str]:
"""
Execute the OpenAI completion API.
"""
return openai.Completion.acreate(
engine="davinci",
max_tokens=5,
prompt=prompt,
)
async def completion(prompt: str):
"""
Wrapper around the OpenAI completion API that handles authentication errors and rotates the API key if necessary.
"""
try:
return await completion_wrapper(prompt)
except openai.error.AuthenticationError:
openai_refresh()
return await completion_wrapper(prompt)
async def main():
"""
Main function that runs the bot.
"""
completion("Write me a poem about a cat sitting on a chair.")
if __name__ == "__main__":
asyncio.run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment