Skip to content

Instantly share code, notes, and snippets.

@wschella
Created July 5, 2023 09:50
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 wschella/e65214ab2bd877a7ea0529e923cffed3 to your computer and use it in GitHub Desktop.
Save wschella/e65214ab2bd877a7ea0529e923cffed3 to your computer and use it in GitHub Desktop.
API_KEY=YOUR_API_KEY

Azure OpenAI API Example

Dependencies

  • requests
  • python-dotenv
import os
from typing import *
import requests
import dotenv
def raise_(error: Exception):
raise error
# TODO: Fill in .env file
# Looks for a file named .env in the current directory
# whose contents simply look like API_KEY=YOUR_API_KEY.
# This way, you can .gitignore it and not push your private key to a GitHub repo.
dotenv.load_dotenv()
API_KEY: str = key if (key := os.getenv("API_KEY")) else \
raise_(ValueError("API_KEY not found in .env file"))
# TODO: Fill this in
API_BASE = "https://YOUR_RESOURCE_NAME.openai.azure.com"
def query_api(prompt, model: str = "gpt-4", max_tokens: int = 128, temperature: float = 0) -> Dict[str, Any]:
"""
Sources:
- https://learn.microsoft.com/en-us/azure/cognitive-services/openai/reference
- https://github.com/Azure/azure-rest-api-specs/blob/main/specification/cognitiveservices/data-plane/AzureOpenAI/inference/stable/2023-05-15/inference.json
- https://learn.microsoft.com/en-us/azure/cognitive-services/openai/how-to/switching-endpoints
"""
api_url = API_BASE + f"/openai/deployments/{model}/completions?api-version=2023-05-15"
r = requests.post(
api_url,
headers={
"content-type": "application/json",
"api-key": API_KEY,
},
json={
"prompt": prompt,
"max_tokens": max_tokens,
"temperature": temperature
# ... other parameters
}
)
return r.json()
if __name__ == "__main__":
print(query_api("Hello, world!"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment