Skip to content

Commit

Permalink
Existing resources, tenant id, codespaces/linux support (Azure-Sample…
Browse files Browse the repository at this point in the history
…s#25)

* Update prepdocs hook to use AzureDeveloperCliCredential
* Using tenant id as argument for prepdocs
* Allow existing resources
* Update readme and add roles.ps1
* Add links to roles
* remove comment
* Initial codespaces support
* Add linux scripts, update azure.yaml
* Create venv for backend
* Readme updates
* Add az cli to devcotnainer for roles script
* Add codespaces option to readme
* Minor readme and script updates
* Fix up prepdocs.sh
* Remove python detection and update .sh env load
* Add troubleshooting
* Update scripts to use pip/python from venv
* Update ps to use -m
* Add azd login
* Readme update with screenshots
* Add gitattributes
* Make .sh impls consistent
* Removing second tenant id
* support lin/win from prepdocs hook
* Update template version
* unwanted
* update start.ps1
* windows
* windows
* py3 fix
* patch
* win
* Tweak pre-reqs

---------

Co-authored-by: Victor Vazquez <[email protected]>
  • Loading branch information
jongio and vhvb1989 authored Mar 21, 2023
1 parent 443ff95 commit ffc416c
Show file tree
Hide file tree
Showing 22 changed files with 450 additions and 132 deletions.
6 changes: 6 additions & 0 deletions .devcontainer/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
ARG VARIANT=bullseye
FROM --platform=amd64 mcr.microsoft.com/vscode/devcontainers/base:0-${VARIANT}
RUN export DEBIAN_FRONTEND=noninteractive \
&& apt-get update && apt-get install -y xdg-utils \
&& apt-get clean -y && rm -rf /var/lib/apt/lists/*
RUN curl -fsSL https://aka.ms/install-azd.sh | bash
37 changes: 37 additions & 0 deletions .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{
"name": "Azure Developer CLI",
"build": {
"dockerfile": "Dockerfile",
"args": {
"VARIANT": "bullseye"
}
},
"features": {
"ghcr.io/devcontainers/features/python:1": {
"version": "os-provided"
},
"ghcr.io/devcontainers/features/node:1": {
"version": "16",
"nodeGypDependencies": false
},
"ghcr.io/devcontainers/features/powershell:1.1.0": {},
"ghcr.io/devcontainers/features/azure-cli:1.0.8": {}
},
"customizations": {
"vscode": {
"extensions": [
"ms-azuretools.azure-dev",
"ms-azuretools.vscode-bicep",
"ms-python.python"
]
}
},
"forwardPorts": [
5000
],
"postCreateCommand": "",
"remoteUser": "vscode",
"hostRequirements": {
"memory": "8gb"
}
}
1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
*.sh text eol=lf
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# Azure az webapp deployment details
.azure
*_env

# Byte-compiled / optimized / DLL files
__pycache__/
Expand Down
5 changes: 4 additions & 1 deletion .vscode/tasks.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@
{
"label": "Start App (Script)",
"type": "shell",
"command": "start.cmd",
"command": "${workspaceFolder}/app/start.sh",
"windows": {
"command": "pwsh ${workspaceFolder}/app/start.ps1"
},
"presentation": {
"reveal": "silent"
},
Expand Down
82 changes: 67 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# ChatGPT + Enterprise data with Azure OpenAI and Cognitive Search

[![Open in GitHub Codespaces](https://img.shields.io/static/v1?style=for-the-badge&label=GitHub+Codespaces&message=Open&color=brightgreen&logo=github)](https://github.com/codespaces/new?hide_repo_select=true&ref=main&repo=599293758&machine=standardLinux32gb&devcontainer_path=.devcontainer%2Fdevcontainer.json&location=WestUs2)
[![Open in Remote - Containers](https://img.shields.io/static/v1?style=for-the-badge&label=Remote%20-%20Containers&message=Open&color=blue&logo=visualstudiocode)](https://vscode.dev/redirect?url=vscode://ms-vscode-remote.remote-containers/cloneInVolume?url=https://github.com/azure-samples/azure-search-openai-demo)

This sample demonstrates a few approaches for creating ChatGPT-like experiences over your own data using the Retrieval Augmented Generation pattern. It uses Azure OpenAI Service to access the ChatGPT model (gpt-35-turbo), and Azure Cognitive Search for data indexing and retrieval.

The repo includes sample data so it's ready to try end to end. In this sample application we use a fictitious company called Contoso Electronics, and the experience allows its employees to ask questions about the benefits, internal policies, as well as job descriptions and roles.
Expand All @@ -19,30 +22,76 @@ The repo includes sample data so it's ready to try end to end. In this sample ap

> **IMPORTANT:** In order to deploy and run this example, you'll need an **Azure subscription with access enabled for the Azure OpenAI service**. You can request access [here](https://aka.ms/oaiapply). You can also visit [here](https://azure.microsoft.com/free/cognitive-search/) to get some free Azure credits to get you started.
> **AZURE RESOURCE COSTS** by default this sample will create Azure App Service and Azure Cognitive Search resources that have a monthly cost. You can switch them to free versions of each of them if you want to avoid this cost by changing the parameters file under the infra folder (though there are some limits to consider; for example, you can have up to 1 free Cognitive Search resource per subscription.)
### Prerequisites

- Azure Developer CLI (install from [here](https://aka.ms/azure-dev/install))
- Python (install from [here](https://www.python.org/downloads/))
- **Imporant**: Python and the pip package manager must be in the path in Windows for the setup scripts to work.
- Node.js (install from [here](https://nodejs.org/en/download/))
- Git (install from [here](https://git-scm.com/downloads))
- Powershell (pwsh) (install from [here](https://github.com/powershell/powershell))
- **Imporant**: Ensure you can run pwsh.exe from a PowerShell command. If this fails, you likely need to upgrade PowerShell.
#### To Run Locally
- [Azure Developer CLI](https://aka.ms/azure-dev/install)
- [Python 3+](https://www.python.org/downloads/)
- **Important**: Python and the pip package manager must be in the path in Windows for the setup scripts to work.
- [Node.js](https://nodejs.org/en/download/)
- [Git](https://git-scm.com/downloads)
- [Powershell 7+ (pwsh)](https://github.com/powershell/powershell) - For Windows users only.
- **Important**: Ensure you can run `pwsh.exe` from a PowerShell command. If this fails, you likely need to upgrade PowerShell.

>NOTE: Your Azure Account must have `Microsoft.Authorization/roleAssignments/write` permissions, such as [User Access Administrator](https://learn.microsoft.com/azure/role-based-access-control/built-in-roles#user-access-administrator) or [Owner](https://learn.microsoft.com/azure/role-based-access-control/built-in-roles#owner).
#### To Run in GitHub Codespaces or VS Code Remote Containers

You can run this repo virtually by using GitHub Codespaces or VS Code Remote Containers. Click on one of the buttons below to open this repo in one of those options.

[![Open in GitHub Codespaces](https://img.shields.io/static/v1?style=for-the-badge&label=GitHub+Codespaces&message=Open&color=brightgreen&logo=github)](https://github.com/codespaces/new?hide_repo_select=true&ref=main&repo=599293758&machine=standardLinux32gb&devcontainer_path=.devcontainer%2Fdevcontainer.json&location=WestUs2)
[![Open in Remote - Containers](https://img.shields.io/static/v1?style=for-the-badge&label=Remote%20-%20Containers&message=Open&color=blue&logo=visualstudiocode)](https://vscode.dev/redirect?url=vscode://ms-vscode-remote.remote-containers/cloneInVolume?url=https://github.com/azure-samples/azure-search-openai-demo)

### Installation

Starting from scratch:
#### Project Initialization

1. Create a new folder and switch to it in the terminal
2. Run "azd up -t azure-search-openai-demo"
* For the target location, the regions that currently support the models used in this sample are East US or South Central US. For an up-to-date list of regions and models, check [here](https://learn.microsoft.com/en-us/azure/cognitive-services/openai/concepts/models)
1. Run `azd login`
1. Run `azd init -t azure-search-openai-demo`
* For the target location, the regions that currently support the models used in this sample are **East US** or **South Central US**. For an up-to-date list of regions and models, check [here](https://learn.microsoft.com/en-us/azure/cognitive-services/openai/concepts/models)

#### Starting from scratch:

Execute the following command, if you don't have any pre-existing Azure services and want to start from a fresh deployment.

Deploying or re-deploying a local clone of the repo:
* Simply run "azd up"
1. Run `azd up` - This will provision Azure resources and deploy this sample to those resources, including building the search index based on the files found in the `./data` folder.
1. After the application has been successfully deployed you will see a URL printed to the console. Click that URL to interact with the application in your browser.

Running locally:
* Run `./app/start.cmd` or run the "VS Code Task: Start App" to start the project locally.
It will look like the following:

** AZURE RESOURCE COSTS ** by default this sample will create Azure App Service and Azure Cognitive Search resources that have a monthly cost. You can switch them to free versions of each of them if you want to avoid this cost by changing the parameters file under the infra folder (though there are some limits to consider; for example, you can have up to 1 free Cognitive Search resource per subscription.)
!['Output from running azd up'](assets/endpoint.png)

> NOTE: It may take a minute for the application to be fully deployed. If you see a "Python Developer" welcome screen, then wait a minute and refresh the page.
#### Use existing resources:

1. Run `azd env set AZURE_OPENAI_SERVICE {Name of existing OpenAI service}`
1. Run `azd env set AZURE_OPENAI_RESOURCE_GROUP {Name of existing resource group that OpenAI service is provisioned to}`
1. Run `azd env set AZURE_OPENAI_CHATGPT_DEPLOYMENT {Name of existing ChatGPT deployment}`. Only needed if your ChatGPT deployment is not the default 'chat'.
1. Run `azd env set AZURE_OPENAI_GPT_DEPLOYMENT {Name of existing GPT deployment}`. Only needed if your ChatGPT deployment is not the default 'davinci'.
1. Run `azd up`

> NOTE: You can also use existing Search and Storage Accounts. See `./infra/main.parameters.json` for list of environment variables to pass to `azd env set` to configure those existing resources.
#### Deploying or re-deploying a local clone of the repo:
* Simply run `azd up`

#### Running locally:
1. Run `azd login`
2. Change dir to `app`
3. Run `./start.ps1` or `./start.sh` or run the "VS Code Task: Start App" to start the project locally.

#### Sharing Environments

Run the following if you want to give someone else access to completely deployed and existing environment.

1. Install the [Azure CLI](https://learn.microsoft.com/cli/azure/install-azure-cli)
1. Run `azd init -t azure-search-openai-demo`
1. Run `azd env refresh` - Note that they will need the azd environment name, subscription Id, and location to run this command - you can find those values in your `./azure/{env name}/.env` file. This will populate their azd environment's .env file with all the settings needed to run the app locally.
1. Run `pwsh ./scripts/roles.ps1` - This will assign all of the necessary roles to the user so they can run the app locally. If they do not have the necessary permission to create roles in the subscription, then you may need to run this script for them. Just be sure to set the `AZURE_PRINCIPAL_ID` environment variable in the azd .env file or in the active shell to their Azure Id, which they can get with `az account show`.

### Quickstart

Expand All @@ -69,3 +118,6 @@ Once in the web app:

***Answer***: Chunking allows us to limit the amount of information we send to OpenAI due to token limits. By breaking up the content, it allows us to easily find potential chunks of text that we can inject into OpenAI. The method of chunking we use leverages a sliding window of text such that sentences that end one chunk will start the next. This allows us to reduce the chance of losing the context of the text.

### Troubleshooting

If you see this error while running `azd deploy`: `read /tmp/azd1992237260/backend_env/lib64: is a directory`, then delete the `./app/backend/backend_env folder` and re-run the `azd deploy` command. This issue is being tracked here: https://github.com/Azure/azure-dev/issues/1237
8 changes: 4 additions & 4 deletions app/backend/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
from azure.storage.blob import BlobServiceClient

# Replace these with your own values, either in environment variables or directly here
AZURE_BLOB_STORAGE_ACCOUNT = os.environ.get("AZURE_BLOB_STORAGE_ACCOUNT") or "mystorageaccount"
AZURE_BLOB_STORAGE_CONTAINER = os.environ.get("AZURE_BLOB_STORAGE_CONTAINER") or "content"
AZURE_STORAGE_ACCOUNT = os.environ.get("AZURE_STORAGE_ACCOUNT") or "mystorageaccount"
AZURE_STORAGE_CONTAINER = os.environ.get("AZURE_STORAGE_CONTAINER") or "content"
AZURE_SEARCH_SERVICE = os.environ.get("AZURE_SEARCH_SERVICE") or "gptkb"
AZURE_SEARCH_INDEX = os.environ.get("AZURE_SEARCH_INDEX") or "gptkbindex"
AZURE_OPENAI_SERVICE = os.environ.get("AZURE_OPENAI_SERVICE") or "myopenai"
Expand Down Expand Up @@ -47,9 +47,9 @@
index_name=AZURE_SEARCH_INDEX,
credential=azure_credential)
blob_client = BlobServiceClient(
account_url=f"https://{AZURE_BLOB_STORAGE_ACCOUNT}.blob.core.windows.net",
account_url=f"https://{AZURE_STORAGE_ACCOUNT}.blob.core.windows.net",
credential=azure_credential)
blob_container = blob_client.get_container_client(AZURE_BLOB_STORAGE_CONTAINER)
blob_container = blob_client.get_container_client(AZURE_STORAGE_CONTAINER)

# Various approaches to integrate GPT and external knowledge, most applications will use a single one of these patterns
# or some derivative, here we include several for exploration purposes
Expand Down
2 changes: 1 addition & 1 deletion app/backend/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
azure-identity==1.12.0
azure-identity==1.13.0b3
Flask==2.2.2
langchain==0.0.78
openai==0.26.4
Expand Down
56 changes: 0 additions & 56 deletions app/start.cmd

This file was deleted.

74 changes: 74 additions & 0 deletions app/start.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
Write-Host ""
Write-Host "Loading azd .env file from current environment"
Write-Host ""

foreach ($line in (& azd env get-values)) {
if ($line -match "([^=]+)=(.*)") {
$key = $matches[1]
$value = $matches[2] -replace '^"|"$'
Set-Item -Path "env:\$key" -Value $value
}
}

if ($LASTEXITCODE -ne 0) {
Write-Host "Failed to load environment variables from azd environment"
exit $LASTEXITCODE
}


Write-Host 'Creating python virtual environment "backend/backend_env"'
$pythonCmd = Get-Command python -ErrorAction SilentlyContinue
if (-not $pythonCmd) {
# fallback to python3 if python not found
$pythonCmd = Get-Command python3 -ErrorAction SilentlyContinue
}
Start-Process -FilePath ($pythonCmd).Source -ArgumentList "-m venv ./backend/backend_env" -Wait -NoNewWindow

Write-Host ""
Write-Host "Restoring backend python packages"
Write-Host ""

Set-Location backend
$venvPythonPath = "./backend_env/scripts/python.exe"
if (Test-Path -Path "/usr") {
# fallback to Linux venv path
$venvPythonPath = "./backend_env/bin/python"
}

Start-Process -FilePath $venvPythonPath -ArgumentList "-m pip install -r requirements.txt" -Wait -NoNewWindow
if ($LASTEXITCODE -ne 0) {
Write-Host "Failed to restore backend python packages"
exit $LASTEXITCODE
}

Write-Host ""
Write-Host "Restoring frontend npm packages"
Write-Host ""
Set-Location ../frontend
npm install
if ($LASTEXITCODE -ne 0) {
Write-Host "Failed to restore frontend npm packages"
exit $LASTEXITCODE
}

Write-Host ""
Write-Host "Building frontend"
Write-Host ""
npm run build
if ($LASTEXITCODE -ne 0) {
Write-Host "Failed to build frontend"
exit $LASTEXITCODE
}

Write-Host ""
Write-Host "Starting backend"
Write-Host ""
Set-Location ../backend
Start-Process http://127.0.0.1:5000

Start-Process -FilePath $venvPythonPath -ArgumentList "./app.py" -Wait -NoNewWindow

if ($LASTEXITCODE -ne 0) {
Write-Host "Failed to start backend"
exit $LASTEXITCODE
}
Loading

0 comments on commit ffc416c

Please sign in to comment.