Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
pamelafox committed Apr 10, 2024
0 parents commit b07ca8e
Show file tree
Hide file tree
Showing 20 changed files with 2,069 additions and 0 deletions.
20 changes: 20 additions & 0 deletions .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "azure-openai-keyless",
"image": "mcr.microsoft.com/devcontainers/python:3.12-bullseye",
"features": {
"ghcr.io/azure/azure-dev/azd:latest": {}
},
"customizations": {
"vscode": {
"extensions": [
"ms-azuretools.azure-dev",
"ms-azuretools.vscode-bicep"
]
}
},
"postCreateCommand": "",
"remoteUser": "vscode",
"hostRequirements": {
"memory": "8gb"
}
}
149 changes: 149 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
# Azure az webapp deployment details
.azure
*_env

# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# NPM
npm-debug.log*
node_modules
static/

.DS_Store
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Azure Samples

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
53 changes: 53 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# Azure OpenAI Keyless Deployment

The purpose of this repository is to provision an Azure OpenAI account with an RBAC role permission for your user account to access,
so that you can use the OpenAI API SDKs with keyless (Entra) authentication. By default, the account will include a gpt-3.5 model, but you can modify `infra/main.bicep` to deploy other models instead.

## Prerequisites

1. Sign up for a [free Azure account](https://azure.microsoft.com/free/) and create an Azure Subscription.
2. Request access to Azure OpenAI Service by completing the form at [https://aka.ms/oai/access](https://aka.ms/oai/access) and awaiting approval.
3. Install the [Azure Developer CLI](https://learn.microsoft.com/azure/developer/azure-developer-cli/install-azd). (If you open this repository in Codespaces or with the VS Code Dev Containers extension, that part will be done for you.)

## Provisioning

1. Login to Azure:

```shell
azd auth login
```

2. Provision the OpenAI account:

```shell
azd provision
```

It will prompt you to provide an `azd` environment name (like "chat-app"), select a subscription from your Azure account, and select a [location where the OpenAI model is available](https://learn.microsoft.com/azure/ai-services/openai/concepts/models#standard-deployment-model-availability) (like "francecentral"). Then it will provision the resources in your account and deploy the latest code. If you get an error or timeout with deployment, changing the location can help, as there may be availability constraints for the OpenAI resource.

3. When `azd` has finished, you should have an OpenAI account you can use locally when logged into your Azure account. You can output the necessary environment variables into an `.env` file like so:

```shell
azd env get-values > .env
```

4. Then you can run the example code in this repository.


## Running the Python example

1. If you're not already running in a Codespace or Dev Container, create a Python virtual environment.
2. Install the requirements:
```shell
python -m pip install -r requirements.txt
```
3. Run the example:
```shell
python example.py
```
This will use the OpenAI API SDK to make a request to the OpenAI API and print the response.
13 changes: 13 additions & 0 deletions azure.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# yaml-language-server: $schema=https://raw.githubusercontent.com/Azure/azure-dev/main/schemas/v1.0/azure.yaml.json

name: ai-rag-chat-evaluator
metadata:
template: [email protected]
pipeline:
variables:
- OPENAI_HOST
- AZURE_OPENAI_SERVICE
- AZURE_OPENAI_RESOURCE_GROUP
- OPENAI_ORGANIZATION
secrets:
- OPENAI_API_KEY
30 changes: 30 additions & 0 deletions example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import os

import azure.identity
import openai
from dotenv import load_dotenv

load_dotenv()

token_provider = azure.identity.get_bearer_token_provider(
azure.identity.DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"
)
client = openai.AzureOpenAI(
api_version="2024-03-01-preview",
azure_endpoint=f"https://{os.getenv('AZURE_OPENAI_SERVICE')}.openai.azure.com",
azure_ad_token_provider=token_provider,
)

response = client.chat.completions.create(
# For Azure OpenAI, the model parameter must be set to the deployment name
model=os.getenv("AZURE_OPENAI_GPT_DEPLOYMENT"),
temperature=0.7,
n=1,
messages=[
{"role": "system", "content": "You are a helpful assistant that makes lots of cat references and uses emojis."},
{"role": "user", "content": "Write a haiku about a hungry cat who wants tuna"},
],
)

print("Response: ")
print(response.choices[0].message.content)
42 changes: 42 additions & 0 deletions infra/core/ai/cognitiveservices.bicep
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
metadata description = 'Creates an Azure Cognitive Services instance.'
param name string
param location string = resourceGroup().location
param tags object = {}
@description('The custom subdomain name used to access the API. Defaults to the value of the name parameter.')
param customSubDomainName string = name
param deployments array = []
param kind string = 'OpenAI'
param publicNetworkAccess string = 'Enabled'
param sku object = {
name: 'S0'
}

resource account 'Microsoft.CognitiveServices/accounts@2023-05-01' = {
name: name
location: location
tags: tags
kind: kind
properties: {
customSubDomainName: customSubDomainName
publicNetworkAccess: publicNetworkAccess
}
sku: sku
}

@batchSize(1)
resource deployment 'Microsoft.CognitiveServices/accounts/deployments@2023-05-01' = [for deployment in deployments: {
parent: account
name: deployment.name
properties: {
model: deployment.model
raiPolicyName: contains(deployment, 'raiPolicyName') ? deployment.raiPolicyName : null
}
sku: contains(deployment, 'sku') ? deployment.sku : {
name: 'Standard'
capacity: 20
}
}]

output endpoint string = account.properties.endpoint
output id string = account.id
output name string = account.name
17 changes: 17 additions & 0 deletions infra/core/host/appservice-appsettings.bicep
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
metadata description = 'Updates app settings for an Azure App Service.'
@description('The name of the app service resource within the current resource group scope')
param name string

@description('The app settings to be applied to the app service')
@secure()
param appSettings object

resource appService 'Microsoft.Web/sites@2022-03-01' existing = {
name: name
}

resource settings 'Microsoft.Web/sites/config@2022-03-01' = {
name: 'appsettings'
parent: appService
properties: appSettings
}
Loading

0 comments on commit b07ca8e

Please sign in to comment.