diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile new file mode 100644 index 0000000000..2751d6c30f --- /dev/null +++ b/.devcontainer/Dockerfile @@ -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 diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..7dbc508b0a --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -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" + } +} \ No newline at end of file diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000..526c8a38d4 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +*.sh text eol=lf \ No newline at end of file diff --git a/.gitignore b/.gitignore index 268d324174..02031bcda7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ # Azure az webapp deployment details .azure +*_env # Byte-compiled / optimized / DLL files __pycache__/ diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 61f56d7cc5..1ca7d896d4 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -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" }, diff --git a/README.md b/README.md index e84df3e12d..6e4c24e4dc 100644 --- a/README.md +++ b/README.md @@ -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. @@ -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). +> **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 @@ -67,5 +116,8 @@ Once in the web app: ***Question***: Why do we need to break up the PDFs into chunks when Azure Cognitive Search supports searching large documents? -***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 menthod 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. +***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 \ No newline at end of file diff --git a/app/backend/app.py b/app/backend/app.py index a64371577d..074f984125 100644 --- a/app/backend/app.py +++ b/app/backend/app.py @@ -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" @@ -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 diff --git a/app/backend/requirements.txt b/app/backend/requirements.txt index 1554a52ebb..49508fa697 100644 --- a/app/backend/requirements.txt +++ b/app/backend/requirements.txt @@ -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 diff --git a/app/start.cmd b/app/start.cmd deleted file mode 100644 index 030b30d778..0000000000 --- a/app/start.cmd +++ /dev/null @@ -1,56 +0,0 @@ -@echo off - - -echo. -echo Loading azd .env file from current environment -echo. - -@echo off -for /f "tokens=1* delims==" %%a in ('azd env get-values') do ( - set "%%a=%%~b" -) - -if "%errorlevel%" neq "0" ( - echo Failed to load environment varaiables from azd environment - exit /B %errorlevel% -) - -echo. -echo Restoring backend python packages -echo. -cd backend -call pip install -r requirements.txt -if "%errorlevel%" neq "0" ( - echo Failed to restore backend python packages - exit /B %errorlevel% -) - -echo. -echo Restoring frontend npm packages -echo. -cd ../frontend -call npm install -if "%errorlevel%" neq "0" ( - echo Failed to restore frontend npm packages - exit /B %errorlevel% -) - -echo. -echo Building frontend -echo. -call npm run build -if "%errorlevel%" neq "0" ( - echo Failed to build frontend - exit /B %errorlevel% -) - -echo. -echo Starting backend -echo. -cd ../backend -start http://127.0.0.1:5000 -call python ./app.py -if "%errorlevel%" neq "0" ( - echo Failed to start backend - exit /B %errorlevel% -) diff --git a/app/start.ps1 b/app/start.ps1 new file mode 100644 index 0000000000..c560486adf --- /dev/null +++ b/app/start.ps1 @@ -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 +} diff --git a/app/start.sh b/app/start.sh new file mode 100755 index 0000000000..7c121d887d --- /dev/null +++ b/app/start.sh @@ -0,0 +1,64 @@ +#!/bin/sh + +echo "" +echo "Loading azd .env file from current environment" +echo "" + +while IFS='=' read -r key value; do + value=$(echo "$value" | sed 's/^"//' | sed 's/"$//') + export "$key=$value" +done <