├── .devcontainer ├── Dockerfile └── devcontainer.json ├── .gitattributes ├── .github ├── CODE_OF_CONDUCT.md ├── ISSUE_TEMPLATE.md └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── .vscode ├── extensions.json ├── launch.json ├── settings.json └── tasks.json ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE ├── LICENSE.md ├── README.md ├── app ├── backend │ ├── app.py │ ├── approaches │ │ ├── approach.py │ │ ├── chatreadretrieveread.py │ │ ├── readdecomposeask.py │ │ ├── readretrieveread.py │ │ └── retrievethenread.py │ ├── data │ │ └── employeeinfo.csv │ ├── langchainadapters.py │ ├── lookuptool.py │ ├── requirements.txt │ └── text.py ├── frontend │ ├── .prettierrc.json │ ├── index.html │ ├── package-lock.json │ ├── package.json │ ├── public │ │ └── favicon.ico │ ├── src │ │ ├── api │ │ │ ├── api.ts │ │ │ ├── index.ts │ │ │ └── models.ts │ │ ├── assets │ │ │ ├── github.svg │ │ │ └── search.svg │ │ ├── components │ │ │ ├── AnalysisPanel │ │ │ │ ├── AnalysisPanel.module.css │ │ │ │ ├── AnalysisPanel.tsx │ │ │ │ ├── AnalysisPanelTabs.tsx │ │ │ │ └── index.tsx │ │ │ ├── Answer │ │ │ │ ├── Answer.module.css │ │ │ │ ├── Answer.tsx │ │ │ │ ├── AnswerError.tsx │ │ │ │ ├── AnswerIcon.tsx │ │ │ │ ├── AnswerLoading.tsx │ │ │ │ ├── AnswerParser.tsx │ │ │ │ └── index.ts │ │ │ ├── ClearChatButton │ │ │ │ ├── ClearChatButton.module.css │ │ │ │ ├── ClearChatButton.tsx │ │ │ │ └── index.tsx │ │ │ ├── Example │ │ │ │ ├── Example.module.css │ │ │ │ ├── Example.tsx │ │ │ │ ├── ExampleList.tsx │ │ │ │ └── index.tsx │ │ │ ├── QuestionInput │ │ │ │ ├── QuestionInput.module.css │ │ │ │ ├── QuestionInput.tsx │ │ │ │ └── index.ts │ │ │ ├── SettingsButton │ │ │ │ ├── SettingsButton.module.css │ │ │ │ ├── SettingsButton.tsx │ │ │ │ └── index.tsx │ │ │ ├── SupportingContent │ │ │ │ ├── SupportingContent.module.css │ │ │ │ ├── SupportingContent.tsx │ │ │ │ ├── SupportingContentParser.ts │ │ │ │ └── index.ts │ │ │ └── UserChatMessage │ │ │ │ ├── UserChatMessage.module.css │ │ │ │ ├── UserChatMessage.tsx │ │ │ │ └── index.ts │ │ ├── index.css │ │ ├── index.tsx │ │ ├── pages │ │ │ ├── NoPage.tsx │ │ │ ├── chat │ │ │ │ ├── Chat.module.css │ │ │ │ └── Chat.tsx │ │ │ ├── layout │ │ │ │ ├── Layout.module.css │ │ │ │ └── Layout.tsx │ │ │ └── oneshot │ │ │ │ ├── OneShot.module.css │ │ │ │ └── OneShot.tsx │ │ └── vite-env.d.ts │ ├── tsconfig.json │ └── vite.config.ts ├── start.ps1 └── start.sh ├── assets ├── authentication_permissions.png └── endpoint.png ├── azure.yaml ├── data ├── Benefit_Options.pdf ├── Northwind_Health_Plus_Benefits_Details.pdf ├── Northwind_Standard_Benefits_Details.pdf ├── PerksPlus.pdf ├── employee_handbook.pdf └── role_library.pdf ├── docs ├── appcomponents.png └── chatscreen.png ├── indexapp ├── .gitignore ├── .vscode │ └── extensions.json ├── DocIndexer │ ├── __init__.py │ ├── function.json │ └── readme.md ├── RemoveDoc │ ├── __init__.py │ └── function.json ├── getting_started.md ├── host.json └── requirements.txt ├── infra ├── abbreviations.json ├── core │ ├── ai │ │ ├── cognitiveservices.bicep │ │ └── formrecognizer.bicep │ ├── azure-function │ │ └── af.bicep │ ├── host │ │ ├── appservice.bicep │ │ └── appserviceplan.bicep │ ├── search │ │ └── search-services.bicep │ ├── security │ │ └── role.bicep │ └── storage │ │ └── storage-account.bicep ├── main.bicep └── main.parameters.json ├── notebooks ├── chat-read-retrieve-read.ipynb ├── read-decompose-ask.ipynb └── requirements.txt └── scripts ├── create_index.py ├── delete_cogservices_accounts.ps1 ├── postprocess.ps1 ├── prepdocs.ps1 ├── prepdocs.py ├── prepdocs.sh ├── requirements.txt ├── roles.ps1 └── upload_data.py /.devcontainer/Dockerfile: -------------------------------------------------------------------------------- 1 | ARG VARIANT=bullseye 2 | FROM --platform=amd64 mcr.microsoft.com/vscode/devcontainers/base:0-${VARIANT} 3 | RUN export DEBIAN_FRONTEND=noninteractive \ 4 | && apt-get update && apt-get install -y xdg-utils \ 5 | && apt-get clean -y && rm -rf /var/lib/apt/lists/* 6 | RUN curl -fsSL https://aka.ms/install-azd.sh | bash 7 | -------------------------------------------------------------------------------- /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Azure Developer CLI", 3 | "build": { 4 | "dockerfile": "Dockerfile", 5 | "args": { 6 | "VARIANT": "bullseye" 7 | } 8 | }, 9 | "features": { 10 | "ghcr.io/devcontainers/features/python:1": { 11 | "version": "os-provided" 12 | }, 13 | "ghcr.io/devcontainers/features/node:1": { 14 | "version": "16", 15 | "nodeGypDependencies": false 16 | }, 17 | "ghcr.io/devcontainers/features/powershell:1.1.0": {}, 18 | "ghcr.io/devcontainers/features/azure-cli:1.0.8": {} 19 | }, 20 | "customizations": { 21 | "vscode": { 22 | "extensions": [ 23 | "ms-azuretools.azure-dev", 24 | "ms-azuretools.vscode-bicep", 25 | "ms-python.python" 26 | ] 27 | } 28 | }, 29 | "forwardPorts": [ 30 | 5000 31 | ], 32 | "postCreateCommand": "", 33 | "remoteUser": "vscode", 34 | "hostRequirements": { 35 | "memory": "8gb" 36 | } 37 | } -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.sh text eol=lf -------------------------------------------------------------------------------- /.github/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Microsoft Open Source Code of Conduct 2 | 3 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). 4 | 5 | Resources: 6 | 7 | - [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/) 8 | - [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) 9 | - Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns 10 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 4 | > Please provide us with the following information: 5 | > --------------------------------------------------------------- 6 | 7 | ### This issue is for a: (mark with an `x`) 8 | ``` 9 | - [ ] bug report -> please search issues before submitting 10 | - [ ] feature request 11 | - [ ] documentation issue or request 12 | - [ ] regression (a behavior that used to work and stopped in a new release) 13 | ``` 14 | 15 | ### Minimal steps to reproduce 16 | > 17 | 18 | ### Any log messages given by the failure 19 | > 20 | 21 | ### Expected/desired behavior 22 | > 23 | 24 | ### OS and Version? 25 | > Windows 7, 8 or 10. Linux (which distribution). macOS (Yosemite? El Capitan? Sierra?) 26 | 27 | ### Versions 28 | > 29 | 30 | ### Mention any other details that might be useful 31 | 32 | > --------------------------------------------------------------- 33 | > Thanks! We'll be in touch soon. 34 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## Purpose 2 | 3 | * ... 4 | 5 | ## Does this introduce a breaking change? 6 | 7 | ``` 8 | [ ] Yes 9 | [ ] No 10 | ``` 11 | 12 | ## Pull Request Type 13 | What kind of change does this Pull Request introduce? 14 | 15 | 16 | ``` 17 | [ ] Bugfix 18 | [ ] Feature 19 | [ ] Code style update (formatting, local variables) 20 | [ ] Refactoring (no functional changes, no api changes) 21 | [ ] Documentation content changes 22 | [ ] Other... Please describe: 23 | ``` 24 | 25 | ## How to Test 26 | * Get the code 27 | 28 | ``` 29 | git clone [repo-address] 30 | cd [repo-name] 31 | git checkout [branch-name] 32 | npm install 33 | ``` 34 | 35 | * Test the code 36 | 37 | ``` 38 | ``` 39 | 40 | ## What to Check 41 | Verify that the following are valid 42 | * ... 43 | 44 | ## Other Information 45 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Azure az webapp deployment details 2 | .azure 3 | *_env 4 | 5 | # Byte-compiled / optimized / DLL files 6 | __pycache__/ 7 | *.py[cod] 8 | *$py.class 9 | 10 | # C extensions 11 | *.so 12 | 13 | # Distribution / packaging 14 | .Python 15 | build/ 16 | develop-eggs/ 17 | dist/ 18 | downloads/ 19 | eggs/ 20 | .eggs/ 21 | lib/ 22 | lib64/ 23 | parts/ 24 | sdist/ 25 | var/ 26 | wheels/ 27 | share/python-wheels/ 28 | *.egg-info/ 29 | .installed.cfg 30 | *.egg 31 | MANIFEST 32 | 33 | # PyInstaller 34 | # Usually these files are written by a python script from a template 35 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 36 | *.manifest 37 | *.spec 38 | 39 | # Installer logs 40 | pip-log.txt 41 | pip-delete-this-directory.txt 42 | 43 | # Unit test / coverage reports 44 | htmlcov/ 45 | .tox/ 46 | .nox/ 47 | .coverage 48 | .coverage.* 49 | .cache 50 | nosetests.xml 51 | coverage.xml 52 | *.cover 53 | *.py,cover 54 | .hypothesis/ 55 | .pytest_cache/ 56 | cover/ 57 | 58 | # Translations 59 | *.mo 60 | *.pot 61 | 62 | # Django stuff: 63 | *.log 64 | local_settings.py 65 | db.sqlite3 66 | db.sqlite3-journal 67 | 68 | # Flask stuff: 69 | instance/ 70 | .webassets-cache 71 | 72 | # Scrapy stuff: 73 | .scrapy 74 | 75 | # Sphinx documentation 76 | docs/_build/ 77 | 78 | # PyBuilder 79 | .pybuilder/ 80 | target/ 81 | 82 | # Jupyter Notebook 83 | .ipynb_checkpoints 84 | 85 | # IPython 86 | profile_default/ 87 | ipython_config.py 88 | 89 | # pyenv 90 | # For a library or package, you might want to ignore these files since the code is 91 | # intended to run in multiple environments; otherwise, check them in: 92 | # .python-version 93 | 94 | # pipenv 95 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 96 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 97 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 98 | # install all needed dependencies. 99 | #Pipfile.lock 100 | 101 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 102 | __pypackages__/ 103 | 104 | # Celery stuff 105 | celerybeat-schedule 106 | celerybeat.pid 107 | 108 | # SageMath parsed files 109 | *.sage.py 110 | 111 | # Environments 112 | .env 113 | .venv 114 | env/ 115 | venv/ 116 | ENV/ 117 | env.bak/ 118 | venv.bak/ 119 | 120 | # Spyder project settings 121 | .spyderproject 122 | .spyproject 123 | 124 | # Rope project settings 125 | .ropeproject 126 | 127 | # mkdocs documentation 128 | /site 129 | 130 | # mypy 131 | .mypy_cache/ 132 | .dmypy.json 133 | dmypy.json 134 | 135 | # Pyre type checker 136 | .pyre/ 137 | 138 | # pytype static type analyzer 139 | .pytype/ 140 | 141 | # Cython debug symbols 142 | cython_debug/ 143 | 144 | # NPM 145 | npm-debug.log* 146 | node_modules 147 | static/ -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "esbenp.prettier-vscode", 4 | "ms-azuretools.azure-dev" 5 | ] 6 | } -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "Python: Flask", 9 | "type": "python", 10 | "request": "launch", 11 | "module": "flask", 12 | "cwd": "${workspaceFolder}/app/backend", 13 | "env": { 14 | "FLASK_APP": "app.py", 15 | "FLASK_ENV": "development", 16 | "FLASK_DEBUG": "0" 17 | }, 18 | "args": [ 19 | "run", 20 | "--no-debugger", 21 | "--no-reload", 22 | "-p 5000" 23 | ], 24 | "console": "integratedTerminal", 25 | "justMyCode": true, 26 | "envFile": "${input:dotEnvFilePath}", 27 | }, 28 | { 29 | "name": "Frontend: watch", 30 | "type": "node", 31 | "request": "launch", 32 | "cwd": "${workspaceFolder}/app/frontend", 33 | "runtimeExecutable": "npm", 34 | "runtimeArgs": [ 35 | "run-script", 36 | "watch" 37 | ], 38 | "console": "integratedTerminal", 39 | }, 40 | { 41 | "name": "Launch Chrome", 42 | "request": "launch", 43 | "type": "chrome", 44 | "url": "http://localhost:5000", 45 | "webRoot": "${workspaceFolder}/app/frontend/src" 46 | }, 47 | { 48 | "name": "Frontend: build", 49 | "type": "node", 50 | "request": "launch", 51 | "cwd": "${workspaceFolder}/app/frontend", 52 | "runtimeExecutable": "npm", 53 | "runtimeArgs": [ 54 | "run-script", 55 | "build" 56 | ], 57 | "console": "integratedTerminal", 58 | } 59 | ], 60 | "inputs": [ 61 | { 62 | "id": "dotEnvFilePath", 63 | "type": "command", 64 | "command": "azure-dev.commands.getDotEnvFilePath" 65 | } 66 | ] 67 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "[javascript]": { 3 | "editor.defaultFormatter": "esbenp.prettier-vscode", 4 | "editor.formatOnSave": true 5 | }, 6 | "[typescript]": { 7 | "editor.defaultFormatter": "esbenp.prettier-vscode", 8 | "editor.formatOnSave": true 9 | }, 10 | "[typescriptreact]": { 11 | "editor.defaultFormatter": "esbenp.prettier-vscode", 12 | "editor.formatOnSave": true 13 | }, 14 | "[css]": { 15 | "editor.defaultFormatter": "esbenp.prettier-vscode", 16 | "editor.formatOnSave": true 17 | }, 18 | "search.exclude": { 19 | "**/node_modules": true, 20 | "static": true 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "Start App", 6 | "type": "dotenv", 7 | "targetTasks": [ 8 | "Start App (Script)" 9 | ], 10 | "file": "${input:dotEnvFilePath}" 11 | }, 12 | { 13 | "label": "Start App (Script)", 14 | "type": "shell", 15 | "command": "${workspaceFolder}/app/start.sh", 16 | "windows": { 17 | "command": "pwsh ${workspaceFolder}/app/start.ps1" 18 | }, 19 | "presentation": { 20 | "reveal": "silent" 21 | }, 22 | "options": { 23 | "cwd": "${workspaceFolder}/app" 24 | }, 25 | "problemMatcher": [] 26 | } 27 | ], 28 | "inputs": [ 29 | { 30 | "id": "dotEnvFilePath", 31 | "type": "command", 32 | "command": "azure-dev.commands.getDotEnvFilePath" 33 | } 34 | ] 35 | } -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## [project-title] Changelog 2 | 3 | 4 | # x.y.z (yyyy-mm-dd) 5 | 6 | *Features* 7 | * ... 8 | 9 | *Bug Fixes* 10 | * ... 11 | 12 | *Breaking Changes* 13 | * ... 14 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to [project-title] 2 | 3 | This project welcomes contributions and suggestions. Most contributions require you to agree to a 4 | Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us 5 | the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com. 6 | 7 | When you submit a pull request, a CLA bot will automatically determine whether you need to provide 8 | a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions 9 | provided by the bot. You will only need to do this once across all repos using our CLA. 10 | 11 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). 12 | For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or 13 | contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. 14 | 15 | - [Code of Conduct](#coc) 16 | - [Issues and Bugs](#issue) 17 | - [Feature Requests](#feature) 18 | - [Submission Guidelines](#submit) 19 | 20 | ## Code of Conduct 21 | Help us keep this project open and inclusive. Please read and follow our [Code of Conduct](https://opensource.microsoft.com/codeofconduct/). 22 | 23 | ## Found an Issue? 24 | If you find a bug in the source code or a mistake in the documentation, you can help us by 25 | [submitting an issue](#submit-issue) to the GitHub Repository. Even better, you can 26 | [submit a Pull Request](#submit-pr) with a fix. 27 | 28 | ## Want a Feature? 29 | You can *request* a new feature by [submitting an issue](#submit-issue) to the GitHub 30 | Repository. If you would like to *implement* a new feature, please submit an issue with 31 | a proposal for your work first, to be sure that we can use it. 32 | 33 | * **Small Features** can be crafted and directly [submitted as a Pull Request](#submit-pr). 34 | 35 | ## Submission Guidelines 36 | 37 | ### Submitting an Issue 38 | Before you submit an issue, search the archive, maybe your question was already answered. 39 | 40 | If your issue appears to be a bug, and hasn't been reported, open a new issue. 41 | Help us to maximize the effort we can spend fixing issues and adding new 42 | features, by not reporting duplicate issues. Providing the following information will increase the 43 | chances of your issue being dealt with quickly: 44 | 45 | * **Overview of the Issue** - if an error is being thrown a non-minified stack trace helps 46 | * **Version** - what version is affected (e.g. 0.1.2) 47 | * **Motivation for or Use Case** - explain what are you trying to do and why the current behavior is a bug for you 48 | * **Browsers and Operating System** - is this a problem with all browsers? 49 | * **Reproduce the Error** - provide a live example or a unambiguous set of steps 50 | * **Related Issues** - has a similar issue been reported before? 51 | * **Suggest a Fix** - if you can't fix the bug yourself, perhaps you can point to what might be 52 | causing the problem (line of code or commit) 53 | 54 | You can file new issues by providing the above information at the corresponding repository's issues link: https://github.com/[organization-name]/[repository-name]/issues/new]. 55 | 56 | ### Submitting a Pull Request (PR) 57 | Before you submit your Pull Request (PR) consider the following guidelines: 58 | 59 | * Search the repository (https://github.com/[organization-name]/[repository-name]/pulls) for an open or closed PR 60 | that relates to your submission. You don't want to duplicate effort. 61 | 62 | * Make your changes in a new git fork: 63 | 64 | * Commit your changes using a descriptive commit message 65 | * Push your fork to GitHub: 66 | * In GitHub, create a pull request 67 | * If we suggest changes then: 68 | * Make the required updates. 69 | * Rebase your fork and force push to your GitHub repository (this will update your Pull Request): 70 | 71 | ```shell 72 | git rebase master -i 73 | git push -f 74 | ``` 75 | 76 | That's it! Thank you for your contribution! 77 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Azure Samples 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Microsoft Corporation. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ChatGPT + Enterprise data with Azure OpenAI and Cognitive Search 2 | 3 | [![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) 4 | [![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) 5 | 6 | ## Fork Information 7 | 8 | This repository modifies the demo application hosted at [https://github.com/Azure-Samples/azure-search-openai-demo](https://github.com/Azure-Samples/azure-search-openai-demo). It is the intent of this project to continually incorporate any upstream changes along with the original additions made in this fork, but there may delays and conflicts in this process. 9 | 10 | ## Additions 11 | Current additional modifications provided in this project: 12 | 13 | 1. Index source documents hosted in Azure Blob Storage (Defaults to 'raw' container within created Azure Storage Account) 14 | 2. On-going indexing and index administration through an Azure FunctionApp 15 | 3. Frontend authentication enabled by default 16 | 4. Full source PDF display (rather than single page) in web app citation view 17 | 18 | ## Additional Setup 19 | Deployment of the Azure FunctionApp requires Azure Functions Core Tools and Azure CLI to be installed in the deployment environment. Information about installation can be found here: [Work with Azure Functions Core Tools](https://learn.microsoft.com/en-us/azure/azure-functions/functions-run-local?tabs=v4%2Cwindows%2Ccsharp%2Cportal%2Cbash) and [Install Azure CLI on Windows](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli-windows?tabs=azure-cli). 20 | 21 | ## Enabling Authentication 22 | 23 | This application enables Azure Active Directory authentication. This requires an Azure App Registration within the Azure tenant used for deployment. Please see this tutorial for more information on registering an application [Register Application](https://learn.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app). To be used for authenticating the app service, the application must have `User.Read` permissions. Once registered, the application client Id and client secret can be configured for the Bicep deployment below. 24 | 25 | ``` 26 | azd env set AUTH_CLIENT_ID 27 | azd env set AUTH_CLIENT_SECRET 28 | azd env set AUTH_TENANT_ID 29 | ``` 30 | 31 | The App Registration must include the redirect URI for your deployed application. After app deployment, navigate to your App Registration and select Authentication in the sidebar menu. From here, click "Add a platform" under Platform configurations. Add a "Web" platform configuration with a Redirect URI of `https://.azurewebsites.net/.auth/login/aad/callback`. 32 | 33 | 34 | ## Azure Permissions 35 | 36 | To use the Azure Developer CLI for deployment, the Azure credentials used for deployment must have permissions for `Microsoft.Resources/deployments*` at the Subscription level. 37 | 38 | # Upstream Documentation 39 | 40 | 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. 41 | 42 | 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. 43 | 44 | ![RAG Architecture](docs/appcomponents.png) 45 | 46 | ## Features 47 | 48 | * Chat and Q&A interfaces 49 | * Explores various options to help users evaluate the trustworthiness of responses with citations, tracking of source content, etc. 50 | * Shows possible approaches for data preparation, prompt construction, and orchestration of interaction between model (ChatGPT) and retriever (Cognitive Search) 51 | * Settings directly in the UX to tweak the behavior and experiment with options 52 | 53 | ![Chat screen](docs/chatscreen.png) 54 | 55 | ## Getting Started 56 | 57 | > **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. 58 | 59 | > **AZURE RESOURCE COSTS** by default this sample will create Azure App Service and Azure Cognitive Search resources that have a monthly cost, as well as Form Recognizer resource that has cost per document page. 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, and the free Form Recognizer resource only analyzes the first 2 pages of each document.) 60 | 61 | ### Prerequisites 62 | 63 | #### To Run Locally 64 | - [Azure Developer CLI](https://aka.ms/azure-dev/install) 65 | - [Python 3+](https://www.python.org/downloads/) 66 | - **Important**: Python and the pip package manager must be in the path in Windows for the setup scripts to work. 67 | - **Important**: Ensure you can run `python --version` from console. On Ubuntu, you might need to run `sudo apt install python-is-python3` to link `python` to `python3`. 68 | - [Node.js](https://nodejs.org/en/download/) 69 | - [Git](https://git-scm.com/downloads) 70 | - [Powershell 7+ (pwsh)](https://github.com/powershell/powershell) - For Windows users only. 71 | - **Important**: Ensure you can run `pwsh.exe` from a PowerShell command. If this fails, you likely need to upgrade PowerShell. 72 | 73 | >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). 74 | 75 | #### To Run in GitHub Codespaces or VS Code Remote Containers 76 | 77 | 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. 78 | 79 | [![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) 80 | [![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) 81 | 82 | ### Installation 83 | 84 | #### Project Initialization 85 | 86 | 1. Create a new folder and switch to it in the terminal 87 | 1. Run `azd login` 88 | 1. Run `azd init -t azure-search-openai-demo` 89 | * 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) 90 | 91 | #### Starting from scratch: 92 | 93 | Execute the following command, if you don't have any pre-existing Azure services and want to start from a fresh deployment. 94 | 95 | 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. 96 | 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. 97 | 98 | It will look like the following: 99 | 100 | !['Output from running azd up'](assets/endpoint.png) 101 | 102 | > 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. 103 | 104 | #### Use existing resources: 105 | 106 | 1. Run `azd env set AZURE_OPENAI_SERVICE {Name of existing OpenAI service}` 107 | 1. Run `azd env set AZURE_OPENAI_RESOURCE_GROUP {Name of existing resource group that OpenAI service is provisioned to}` 108 | 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'. 109 | 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'. 110 | 1. Run `azd up` 111 | 112 | > 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. 113 | 114 | #### Deploying or re-deploying a local clone of the repo: 115 | * Simply run `azd up` 116 | 117 | #### Running locally: 118 | 1. Run `azd login` 119 | 2. Change dir to `app` 120 | 3. Run `./start.ps1` or `./start.sh` or run the "VS Code Task: Start App" to start the project locally. 121 | 122 | #### Sharing Environments 123 | 124 | Run the following if you want to give someone else access to completely deployed and existing environment. 125 | 126 | 1. Install the [Azure CLI](https://learn.microsoft.com/cli/azure/install-azure-cli) 127 | 1. Run `azd init -t azure-search-openai-demo` 128 | 1. Run `azd env refresh -e {environment name}` - 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. 129 | 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`. 130 | 131 | ### Quickstart 132 | 133 | * In Azure: navigate to the Azure WebApp deployed by azd. The URL is printed out when azd completes (as "Endpoint"), or you can find it in the Azure portal. 134 | * Running locally: navigate to 127.0.0.1:5000 135 | 136 | Once in the web app: 137 | * Try different topics in chat or Q&A context. For chat, try follow up questions, clarifications, ask to simplify or elaborate on answer, etc. 138 | * Explore citations and sources 139 | * Click on "settings" to try different options, tweak prompts, etc. 140 | 141 | ## Resources 142 | 143 | * [Revolutionize your Enterprise Data with ChatGPT: Next-gen Apps w/ Azure OpenAI and Cognitive Search](https://aka.ms/entgptsearchblog) 144 | * [Azure Cognitive Search](https://learn.microsoft.com/azure/search/search-what-is-azure-search) 145 | * [Azure OpenAI Service](https://learn.microsoft.com/azure/cognitive-services/openai/overview) 146 | 147 | ### Note 148 | >Note: The PDF documents used in this demo contain information generated using a language model (Azure OpenAI Service). The information contained in these documents is only for demonstration purposes and does not reflect the opinions or beliefs of Microsoft. Microsoft makes no representations or warranties of any kind, express or implied, about the completeness, accuracy, reliability, suitability or availability with respect to the information contained in this document. All rights reserved to Microsoft. 149 | 150 | ### FAQ 151 | 152 | ***Question***: Why do we need to break up the PDFs into chunks when Azure Cognitive Search supports searching large documents? 153 | 154 | ***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. 155 | 156 | ### Troubleshooting 157 | 158 | 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 -------------------------------------------------------------------------------- /app/backend/app.py: -------------------------------------------------------------------------------- 1 | import os 2 | import mimetypes 3 | import time 4 | import logging 5 | import openai 6 | from flask import Flask, request, jsonify 7 | from azure.identity import DefaultAzureCredential 8 | from azure.core.credentials import AzureKeyCredential, AzureNamedKeyCredential 9 | from azure.search.documents import SearchClient 10 | from approaches.retrievethenread import RetrieveThenReadApproach 11 | from approaches.readretrieveread import ReadRetrieveReadApproach 12 | from approaches.readdecomposeask import ReadDecomposeAsk 13 | from approaches.chatreadretrieveread import ChatReadRetrieveReadApproach 14 | from azure.storage.blob import BlobServiceClient 15 | 16 | # Replace these with your own values, either in environment variables or directly here 17 | AZURE_STORAGE_ACCOUNT = os.environ.get("AZURE_STORAGE_ACCOUNT") or "mystorageaccount" 18 | AZURE_STORAGE_CONTAINER = os.environ.get("AZURE_STORAGE_CONTAINER") or "content" 19 | AZURE_SOURCE_STORAGE_CONTAINER = ( 20 | os.environ.get("AZURE_SOURCE_STORAGE_CONTAINER") or "raw" 21 | ) 22 | AZURE_SEARCH_SERVICE = os.environ.get("AZURE_SEARCH_SERVICE") or "gptkb" 23 | AZURE_SEARCH_INDEX = os.environ.get("AZURE_SEARCH_INDEX") or "gptkbindex" 24 | AZURE_OPENAI_SERVICE = os.environ.get("AZURE_OPENAI_SERVICE") or "myopenai" 25 | AZURE_OPENAI_GPT_DEPLOYMENT = os.environ.get("AZURE_OPENAI_GPT_DEPLOYMENT") or "davinci" 26 | AZURE_OPENAI_CHATGPT_DEPLOYMENT = ( 27 | os.environ.get("AZURE_OPENAI_CHATGPT_DEPLOYMENT") or "chat" 28 | ) 29 | 30 | KB_FIELDS_CONTENT = os.environ.get("KB_FIELDS_CONTENT") or "content" 31 | KB_FIELDS_CATEGORY = os.environ.get("KB_FIELDS_CATEGORY") or "category" 32 | KB_FIELDS_SOURCEPAGE = os.environ.get("KB_FIELDS_SOURCEPAGE") or "sourcepage" 33 | 34 | # Use the current user identity to authenticate with Azure OpenAI, Cognitive Search and Blob Storage (no secrets needed, 35 | # just use 'az login' locally, and managed identity when deployed on Azure). If you need to use keys, use separate AzureKeyCredential instances with the 36 | # keys for each service 37 | # If you encounter a blocking error during a DefaultAzureCredntial resolution, you can exclude the problematic credential by using a parameter (ex. exclude_shared_token_cache_credential=True) 38 | azure_credential = DefaultAzureCredential() 39 | search_credential = ( 40 | AzureKeyCredential(os.getenv("AZURE_SEARCH_KEY")) 41 | if os.getenv("AZURE_SEARCH_KEY") 42 | else azure_credential 43 | ) 44 | storage_credential = ( 45 | AzureNamedKeyCredential( 46 | name=AZURE_STORAGE_ACCOUNT, key=os.getenv("AZURE_STORAGE_KEY") 47 | ) 48 | if os.getenv("AZURE_STORAGE_KEY") 49 | else azure_credential 50 | ) 51 | 52 | # Used by the OpenAI SDK 53 | openai.api_type = "azure" 54 | openai.api_base = f"https://{AZURE_OPENAI_SERVICE}.openai.azure.com" 55 | openai.api_version = "2022-12-01" 56 | 57 | # Comment these two lines out if using keys, set your API key in the OPENAI_API_KEY environment variable instead 58 | openai.api_type = "azure_ad" 59 | openai_token = azure_credential.get_token( 60 | "https://cognitiveservices.azure.com/.default" 61 | ) 62 | openai.api_key = openai_token.token 63 | 64 | # Set up clients for Cognitive Search and Storage 65 | search_client = SearchClient( 66 | endpoint=f"https://{AZURE_SEARCH_SERVICE}.search.windows.net", 67 | index_name=AZURE_SEARCH_INDEX, 68 | credential=search_credential, 69 | ) 70 | blob_client = BlobServiceClient( 71 | account_url=f"https://{AZURE_STORAGE_ACCOUNT}.blob.core.windows.net", 72 | credential=storage_credential, 73 | ) 74 | content_blob_container = blob_client.get_container_client(AZURE_STORAGE_CONTAINER) 75 | source_blob_container = blob_client.get_container_client(AZURE_SOURCE_STORAGE_CONTAINER) 76 | 77 | # Various approaches to integrate GPT and external knowledge, most applications will use a single one of these patterns 78 | # or some derivative, here we include several for exploration purposes 79 | ask_approaches = { 80 | "rtr": RetrieveThenReadApproach( 81 | search_client, 82 | AZURE_OPENAI_GPT_DEPLOYMENT, 83 | KB_FIELDS_SOURCEPAGE, 84 | KB_FIELDS_CONTENT, 85 | ), 86 | "rrr": ReadRetrieveReadApproach( 87 | search_client, 88 | AZURE_OPENAI_GPT_DEPLOYMENT, 89 | KB_FIELDS_SOURCEPAGE, 90 | KB_FIELDS_CONTENT, 91 | ), 92 | "rda": ReadDecomposeAsk( 93 | search_client, 94 | AZURE_OPENAI_GPT_DEPLOYMENT, 95 | KB_FIELDS_SOURCEPAGE, 96 | KB_FIELDS_CONTENT, 97 | ), 98 | } 99 | 100 | chat_approaches = { 101 | "rrr": ChatReadRetrieveReadApproach( 102 | search_client, 103 | AZURE_OPENAI_CHATGPT_DEPLOYMENT, 104 | AZURE_OPENAI_GPT_DEPLOYMENT, 105 | KB_FIELDS_SOURCEPAGE, 106 | KB_FIELDS_CONTENT, 107 | ) 108 | } 109 | 110 | app = Flask(__name__) 111 | 112 | 113 | @app.route("/", defaults={"path": "index.html"}) 114 | @app.route("/") 115 | def static_file(path): 116 | return app.send_static_file(path) 117 | 118 | 119 | # Serve content files from blob storage from within the app to keep the example self-contained. 120 | # *** NOTE *** this assumes that the content files are public, or at least that all users of the app 121 | # can access all the files. This is also slow and memory hungry. 122 | @app.route("/content/") 123 | def content_file(path): 124 | content_filename, extension = os.path.splitext(path) 125 | filename_splits = content_filename.split("-") 126 | page_num = filename_splits[-1] 127 | source_filename = "-".join(filename_splits[:-1]) + extension 128 | print(source_filename) 129 | blob = source_blob_container.get_blob_client(source_filename).download_blob() 130 | mime_type = blob.properties["content_settings"]["content_type"] 131 | if mime_type == "application/octet-stream": 132 | mime_type = mimetypes.guess_type(path)[0] or "application/octet-stream" 133 | return ( 134 | blob.readall(), 135 | 200, 136 | { 137 | "Content-Type": mime_type, 138 | "Content-Disposition": f"inline; filename={path}", 139 | "Page-Number": page_num, 140 | }, 141 | ) 142 | 143 | 144 | @app.route("/ask", methods=["POST"]) 145 | def ask(): 146 | ensure_openai_token() 147 | approach = request.json["approach"] 148 | try: 149 | impl = ask_approaches.get(approach) 150 | if not impl: 151 | return jsonify({"error": "unknown approach"}), 400 152 | r = impl.run(request.json["question"], request.json.get("overrides") or {}) 153 | return jsonify(r) 154 | except Exception as e: 155 | logging.exception("Exception in /ask") 156 | return jsonify({"error": str(e)}), 500 157 | 158 | 159 | @app.route("/chat", methods=["POST"]) 160 | def chat(): 161 | ensure_openai_token() 162 | approach = request.json["approach"] 163 | try: 164 | impl = chat_approaches.get(approach) 165 | if not impl: 166 | return jsonify({"error": "unknown approach"}), 400 167 | r = impl.run(request.json["history"], request.json.get("overrides") or {}) 168 | return jsonify(r) 169 | except Exception as e: 170 | logging.exception("Exception in /chat") 171 | return jsonify({"error": str(e)}), 500 172 | 173 | 174 | def ensure_openai_token(): 175 | global openai_token 176 | if openai_token.expires_on < int(time.time()) - 60: 177 | openai_token = azure_credential.get_token( 178 | "https://cognitiveservices.azure.com/.default" 179 | ) 180 | openai.api_key = openai_token.token 181 | 182 | 183 | if __name__ == "__main__": 184 | app.run() 185 | -------------------------------------------------------------------------------- /app/backend/approaches/approach.py: -------------------------------------------------------------------------------- 1 | class Approach: 2 | def run(self, q: str, use_summaries: bool) -> any: 3 | raise NotImplementedError 4 | -------------------------------------------------------------------------------- /app/backend/approaches/chatreadretrieveread.py: -------------------------------------------------------------------------------- 1 | import openai 2 | from azure.search.documents import SearchClient 3 | from azure.search.documents.models import QueryType 4 | from approaches.approach import Approach 5 | from text import nonewlines 6 | 7 | # Simple retrieve-then-read implementation, using the Cognitive Search and OpenAI APIs directly. It first retrieves 8 | # top documents from search, then constructs a prompt with them, and then uses OpenAI to generate an completion 9 | # (answer) with that prompt. 10 | class ChatReadRetrieveReadApproach(Approach): 11 | prompt_prefix = """<|im_start|>system 12 | Assistant helps the company employees with their healthcare plan questions, and questions about the employee handbook. Be brief in your answers. 13 | Answer ONLY with the facts listed in the list of sources below. If there isn't enough information below, say you don't know. Do not generate answers that don't use the sources below. If asking a clarifying question to the user would help, ask the question. 14 | For tabular information return it as an html table. Do not return markdown format. 15 | Each source has a name followed by colon and the actual information, always include the source name for each fact you use in the response. Use square brakets to reference the source, e.g. [info1.txt]. Don't combine sources, list each source separately, e.g. [info1.txt][info2.pdf]. 16 | {follow_up_questions_prompt} 17 | {injected_prompt} 18 | Sources: 19 | {sources} 20 | <|im_end|> 21 | {chat_history} 22 | """ 23 | 24 | follow_up_questions_prompt_content = """Generate three very brief follow-up questions that the user would likely ask next about their healthcare plan and employee handbook. 25 | Use double angle brackets to reference the questions, e.g. <>. 26 | Try not to repeat questions that have already been asked. 27 | Only generate questions and do not generate any text before or after the questions, such as 'Next Questions'""" 28 | 29 | query_prompt_template = """Below is a history of the conversation so far, and a new question asked by the user that needs to be answered by searching in a knowledge base about employee healthcare plans and the employee handbook. 30 | Generate a search query based on the conversation and the new question. 31 | Do not include cited source filenames and document names e.g info.txt or doc.pdf in the search query terms. 32 | Do not include any text inside [] or <<>> in the search query terms. 33 | If the question is not in English, translate the question to English before generating the search query. 34 | 35 | Chat History: 36 | {chat_history} 37 | 38 | Question: 39 | {question} 40 | 41 | Search query: 42 | """ 43 | 44 | def __init__(self, search_client: SearchClient, chatgpt_deployment: str, gpt_deployment: str, sourcepage_field: str, content_field: str): 45 | self.search_client = search_client 46 | self.chatgpt_deployment = chatgpt_deployment 47 | self.gpt_deployment = gpt_deployment 48 | self.sourcepage_field = sourcepage_field 49 | self.content_field = content_field 50 | 51 | def run(self, history: list[dict], overrides: dict) -> any: 52 | use_semantic_captions = True if overrides.get("semantic_captions") else False 53 | top = overrides.get("top") or 3 54 | exclude_category = overrides.get("exclude_category") or None 55 | filter = "category ne '{}'".format(exclude_category.replace("'", "''")) if exclude_category else None 56 | 57 | # STEP 1: Generate an optimized keyword search query based on the chat history and the last question 58 | prompt = self.query_prompt_template.format(chat_history=self.get_chat_history_as_text(history, include_last_turn=False), question=history[-1]["user"]) 59 | completion = openai.Completion.create( 60 | engine=self.gpt_deployment, 61 | prompt=prompt, 62 | temperature=0.0, 63 | max_tokens=32, 64 | n=1, 65 | stop=["\n"]) 66 | q = completion.choices[0].text 67 | 68 | # STEP 2: Retrieve relevant documents from the search index with the GPT optimized query 69 | if overrides.get("semantic_ranker"): 70 | r = self.search_client.search(q, 71 | filter=filter, 72 | query_type=QueryType.SEMANTIC, 73 | query_language="en-us", 74 | query_speller="lexicon", 75 | semantic_configuration_name="default", 76 | top=top, 77 | query_caption="extractive|highlight-false" if use_semantic_captions else None) 78 | else: 79 | r = self.search_client.search(q, filter=filter, top=top) 80 | if use_semantic_captions: 81 | results = [doc[self.sourcepage_field] + ": " + nonewlines(" . ".join([c.text for c in doc['@search.captions']])) for doc in r] 82 | else: 83 | results = [doc[self.sourcepage_field] + ": " + nonewlines(doc[self.content_field]) for doc in r] 84 | content = "\n".join(results) 85 | 86 | follow_up_questions_prompt = self.follow_up_questions_prompt_content if overrides.get("suggest_followup_questions") else "" 87 | 88 | # Allow client to replace the entire prompt, or to inject into the exiting prompt using >>> 89 | prompt_override = overrides.get("prompt_template") 90 | if prompt_override is None: 91 | prompt = self.prompt_prefix.format(injected_prompt="", sources=content, chat_history=self.get_chat_history_as_text(history), follow_up_questions_prompt=follow_up_questions_prompt) 92 | elif prompt_override.startswith(">>>"): 93 | prompt = self.prompt_prefix.format(injected_prompt=prompt_override[3:] + "\n", sources=content, chat_history=self.get_chat_history_as_text(history), follow_up_questions_prompt=follow_up_questions_prompt) 94 | else: 95 | prompt = prompt_override.format(sources=content, chat_history=self.get_chat_history_as_text(history), follow_up_questions_prompt=follow_up_questions_prompt) 96 | 97 | # STEP 3: Generate a contextual and content specific answer using the search results and chat history 98 | completion = openai.Completion.create( 99 | engine=self.chatgpt_deployment, 100 | prompt=prompt, 101 | temperature=overrides.get("temperature") or 0.7, 102 | max_tokens=1024, 103 | n=1, 104 | stop=["<|im_end|>", "<|im_start|>"]) 105 | 106 | return {"data_points": results, "answer": completion.choices[0].text, "thoughts": f"Searched for:
{q}

Prompt:
" + prompt.replace('\n', '
')} 107 | 108 | def get_chat_history_as_text(self, history, include_last_turn=True, approx_max_tokens=1000) -> str: 109 | history_text = "" 110 | for h in reversed(history if include_last_turn else history[:-1]): 111 | history_text = """<|im_start|>user""" +"\n" + h["user"] + "\n" + """<|im_end|>""" + "\n" + """<|im_start|>assistant""" + "\n" + (h.get("bot") + """<|im_end|>""" if h.get("bot") else "") + "\n" + history_text 112 | if len(history_text) > approx_max_tokens*4: 113 | break 114 | return history_text -------------------------------------------------------------------------------- /app/backend/approaches/readdecomposeask.py: -------------------------------------------------------------------------------- 1 | import openai 2 | from approaches.approach import Approach 3 | from azure.search.documents import SearchClient 4 | from azure.search.documents.models import QueryType 5 | from langchain.llms.openai import AzureOpenAI 6 | from langchain.prompts import PromptTemplate, BasePromptTemplate 7 | from langchain.callbacks.base import CallbackManager 8 | from langchain.agents import Tool, AgentExecutor 9 | from langchain.agents.react.base import ReActDocstoreAgent 10 | from langchainadapters import HtmlCallbackHandler 11 | from text import nonewlines 12 | from typing import List 13 | 14 | class ReadDecomposeAsk(Approach): 15 | def __init__(self, search_client: SearchClient, openai_deployment: str, sourcepage_field: str, content_field: str): 16 | self.search_client = search_client 17 | self.openai_deployment = openai_deployment 18 | self.sourcepage_field = sourcepage_field 19 | self.content_field = content_field 20 | 21 | def search(self, q: str, overrides: dict) -> str: 22 | use_semantic_captions = True if overrides.get("semantic_captions") else False 23 | top = overrides.get("top") or 3 24 | exclude_category = overrides.get("exclude_category") or None 25 | filter = "category ne '{}'".format(exclude_category.replace("'", "''")) if exclude_category else None 26 | 27 | if overrides.get("semantic_ranker"): 28 | r = self.search_client.search(q, 29 | filter=filter, 30 | query_type=QueryType.SEMANTIC, 31 | query_language="en-us", 32 | query_speller="lexicon", 33 | semantic_configuration_name="default", 34 | top = top, 35 | query_caption="extractive|highlight-false" if use_semantic_captions else None) 36 | else: 37 | r = self.search_client.search(q, filter=filter, top=top) 38 | if use_semantic_captions: 39 | self.results = [doc[self.sourcepage_field] + ":" + nonewlines(" . ".join([c.text for c in doc['@search.captions'] ])) for doc in r] 40 | else: 41 | self.results = [doc[self.sourcepage_field] + ":" + nonewlines(doc[self.content_field][:500]) for doc in r] 42 | return "\n".join(self.results) 43 | 44 | def lookup(self, q: str) -> str: 45 | r = self.search_client.search(q, 46 | top = 1, 47 | include_total_count=True, 48 | query_type=QueryType.SEMANTIC, 49 | query_language="en-us", 50 | query_speller="lexicon", 51 | semantic_configuration_name="default", 52 | query_answer="extractive|count-1", 53 | query_caption="extractive|highlight-false") 54 | 55 | answers = r.get_answers() 56 | if answers and len(answers) > 0: 57 | return answers[0].text 58 | if r.get_count() > 0: 59 | return "\n".join(d['content'] for d in r) 60 | return None 61 | 62 | def run(self, q: str, overrides: dict) -> any: 63 | # Not great to keep this as instance state, won't work with interleaving (e.g. if using async), but keeps the example simple 64 | self.results = None 65 | 66 | # Use to capture thought process during iterations 67 | cb_handler = HtmlCallbackHandler() 68 | cb_manager = CallbackManager(handlers=[cb_handler]) 69 | 70 | llm = AzureOpenAI(deployment_name=self.openai_deployment, temperature=overrides.get("temperature") or 0.3, openai_api_key=openai.api_key) 71 | tools = [ 72 | Tool(name="Search", func=lambda q: self.search(q, overrides)), 73 | Tool(name="Lookup", func=self.lookup) 74 | ] 75 | 76 | # Like results above, not great to keep this as a global, will interfere with interleaving 77 | global prompt 78 | prompt_prefix = overrides.get("prompt_template") 79 | prompt = PromptTemplate.from_examples( 80 | EXAMPLES, SUFFIX, ["input", "agent_scratchpad"], prompt_prefix + "\n\n" + PREFIX if prompt_prefix else PREFIX) 81 | 82 | agent = ReAct.from_llm_and_tools(llm, tools) 83 | chain = AgentExecutor.from_agent_and_tools(agent, tools, verbose=True, callback_manager=cb_manager) 84 | result = chain.run(q) 85 | 86 | # Fix up references to they look like what the frontend expects ([] instead of ()), need a better citation format since parentheses are so common 87 | result = result.replace("(", "[").replace(")", "]") 88 | 89 | return {"data_points": self.results or [], "answer": result, "thoughts": cb_handler.get_and_reset_log()} 90 | 91 | class ReAct(ReActDocstoreAgent): 92 | @classmethod 93 | def create_prompt(cls, tools: List[Tool]) -> BasePromptTemplate: 94 | return prompt 95 | 96 | # Modified version of langchain's ReAct prompt that includes instructions and examples for how to cite information sources 97 | EXAMPLES = [ 98 | """Question: What is the elevation range for the area that the eastern sector of the 99 | Colorado orogeny extends into? 100 | Thought 1: I need to search Colorado orogeny, find the area that the eastern sector 101 | of the Colorado orogeny extends into, then find the elevation range of the 102 | area. 103 | Action 1: Search[Colorado orogeny] 104 | Observation 1: [info1.pdf] The Colorado orogeny was an episode of mountain building (an orogeny) in 105 | Colorado and surrounding areas. 106 | Thought 2: It does not mention the eastern sector. So I need to look up eastern 107 | sector. 108 | Action 2: Lookup[eastern sector] 109 | Observation 2: [info2.txt] (Result 1 / 1) The eastern sector extends into the High Plains and is called 110 | the Central Plains orogeny. 111 | Thought 3: The eastern sector of Colorado orogeny extends into the High Plains. So I 112 | need to search High Plains and find its elevation range. 113 | Action 3: Search[High Plains] 114 | Observation 3: [some_file.pdf] High Plains refers to one of two distinct land regions 115 | Thought 4: I need to instead search High Plains (United States). 116 | Action 4: Search[High Plains (United States)] 117 | Observation 4: [filea.pdf] The High Plains are a subregion of the Great Plains. [another-ref.docx] From east to west, the 118 | High Plains rise in elevation from around 1,800 to 7,000 ft (550 to 2,130 119 | m). 120 | Thought 5: High Plains rise in elevation from around 1,800 to 7,000 ft, so the answer 121 | is 1,800 to 7,000 ft. 122 | Action 5: Finish[1,800 to 7,000 ft (filea.pdf) ]""", 123 | """Question: Musician and satirist Allie Goertz wrote a song about the "The Simpsons" 124 | character Milhouse, who Matt Groening named after who? 125 | Thought 1: The question simplifies to "The Simpsons" character Milhouse is named after 126 | who. I only need to search Milhouse and find who it is named after. 127 | Action 1: Search[Milhouse] 128 | Observation 1: [info7.pdf] Milhouse Mussolini Van Houten is a recurring character in the Fox animated 129 | television series The Simpsons voiced by Pamela Hayden and created by Matt 130 | Groening. 131 | Thought 2: The paragraph does not tell who Milhouse is named after, maybe I can look up 132 | "named after". 133 | Action 2: Lookup[named after] 134 | Observation 2: [historyref2.txt] (Result 1 / 1) Milhouse was named after U.S. president Richard Nixon, whose 135 | middle name was Milhous. 136 | Thought 3: Milhouse was named after U.S. president Richard Nixon, so the answer is 137 | Richard Nixon. 138 | Action 3: Finish[Richard Nixon (historyref2.txt) ]""", 139 | """Question: Which documentary is about Finnish rock groups, Adam Clayton Powell or The 140 | Saimaa Gesture? 141 | Thought 1: I need to search Adam Clayton Powell and The Saimaa Gesture, and find which 142 | documentary is about Finnish rock groups. 143 | Action 1: Search[Adam Clayton Powell] 144 | Observation 1: [info9.pdf] Could not find [Adam Clayton Powell]. Similar: ['Adam Clayton Powell 145 | III', 'Seventh Avenue (Manhattan)', 'Adam Clayton Powell Jr. State Office 146 | Building', 'Isabel Washington Powell', 'Adam Powell', vAdam Clayton Powell 147 | (film)', 'Giancarlo Esposito']. 148 | Thought 2: To find the documentary, I can search Adam Clayton Powell (film). 149 | Action 2: Search[Adam Clayton Powell (film)] 150 | Observation 2: [data123.txt] Adam Clayton Powell is a 1989 American documentary film directed by 151 | Richard Kilberg. The film is about the rise and fall of influential 152 | African-American politician Adam Clayton Powell Jr.[3][4] It was later aired 153 | as part of the PBS series The American Experience. 154 | Thought 3: Adam Clayton Powell (film) is a documentary about an African-American 155 | politician, not Finnish rock groups. So the documentary about Finnish rock 156 | groups must instead be The Saimaa Gesture. 157 | Action 3: Finish[The Saimaa Gesture (data123.txt) ]""", 158 | """Question: What profession does Nicholas Ray and Elia Kazan have in common? 159 | Thought 1: I need to search Nicholas Ray and Elia Kazan, find their professions, then 160 | find the profession they have in common. 161 | Action 1: Search[Nicholas Ray] 162 | Observation 1: [files-987.png] Nicholas Ray (born Raymond Nicholas Kienzle Jr., August 7, 1911 - June 16, 163 | 1979) was an American film director, screenwriter, and actor best known for 164 | the 1955 film Rebel Without a Cause. 165 | Thought 2: Professions of Nicholas Ray are director, screenwriter, and actor. I need 166 | to search Elia Kazan next and find his professions. 167 | Action 2: Search[Elia Kazan] 168 | Observation 2: [files-654.txt] Elia Kazan was an American film and theatre director, producer, screenwriter 169 | and actor. 170 | Thought 3: Professions of Elia Kazan are director, producer, screenwriter, and actor. 171 | So profession Nicholas Ray and Elia Kazan have in common is director, 172 | screenwriter, and actor. 173 | Action 3: Finish[director, screenwriter, actor (files-987.png)(files-654.txt) ]""", 174 | """Question: Which magazine was started first Arthur's Magazine or First for Women? 175 | Thought 1: I need to search Arthur's Magazine and First for Women, and find which was 176 | started first. 177 | Action 1: Search[Arthur's Magazine] 178 | Observation 1: [magazines-1850.pdf] Arthur's Magazine (1844-1846) was an American literary periodical published 179 | in Philadelphia in the 19th century. 180 | Thought 2: Arthur's Magazine was started in 1844. I need to search First for Women 181 | next. 182 | Action 2: Search[First for Women] 183 | Observation 2: [magazines-1900.pdf] First for Women is a woman's magazine published by Bauer Media Group in the 184 | USA.[1] The magazine was started in 1989. 185 | Thought 3: First for Women was started in 1989. 1844 (Arthur's Magazine) < 1989 (First 186 | for Women), so Arthur's Magazine was started first. 187 | Action 3: Finish[Arthur's Magazine (magazines-1850.pdf)(magazines-1900.pdf) ]""", 188 | """Question: Were Pavel Urysohn and Leonid Levin known for the same type of work? 189 | Thought 1: I need to search Pavel Urysohn and Leonid Levin, find their types of work, 190 | then find if they are the same. 191 | Action 1: Search[Pavel Urysohn] 192 | Observation 1: [info4444.pdf] Pavel Samuilovich Urysohn (February 3, 1898 - August 17, 1924) was a Soviet 193 | mathematician who is best known for his contributions in dimension theory. 194 | Thought 2: Pavel Urysohn is a mathematician. I need to search Leonid Levin next and 195 | find its type of work. 196 | Action 2: Search[Leonid Levin] 197 | Observation 2: [datapoints_aaa.txt] Leonid Anatolievich Levin is a Soviet-American mathematician and computer 198 | scientist. 199 | Thought 3: Leonid Levin is a mathematician and computer scientist. So Pavel Urysohn 200 | and Leonid Levin have the same type of work. 201 | Action 3: Finish[yes (info4444.pdf)(datapoints_aaa.txt) ]""", 202 | ] 203 | SUFFIX = """\nQuestion: {input} 204 | {agent_scratchpad}""" 205 | PREFIX = "Answer questions as shown in the following examples, by splitting the question into individual search or lookup actions to find facts until you can answer the question. " \ 206 | "Observations are prefixed by their source name in square brackets, source names MUST be included with the actions in the answers." \ 207 | "Only answer the questions using the information from observations, do not speculate." 208 | -------------------------------------------------------------------------------- /app/backend/approaches/readretrieveread.py: -------------------------------------------------------------------------------- 1 | import openai 2 | from approaches.approach import Approach 3 | from azure.search.documents import SearchClient 4 | from azure.search.documents.models import QueryType 5 | from langchain.llms.openai import AzureOpenAI 6 | from langchain.callbacks.base import CallbackManager 7 | from langchain.chains import LLMChain 8 | from langchain.agents import Tool, ZeroShotAgent, AgentExecutor 9 | from langchain.llms.openai import AzureOpenAI 10 | from langchainadapters import HtmlCallbackHandler 11 | from text import nonewlines 12 | from lookuptool import CsvLookupTool 13 | 14 | # Attempt to answer questions by iteratively evaluating the question to see what information is missing, and once all information 15 | # is present then formulate an answer. Each iteration consists of two parts: first use GPT to see if we need more information, 16 | # second if more data is needed use the requested "tool" to retrieve it. The last call to GPT answers the actual question. 17 | # This is inspired by the MKRL paper[1] and applied here using the implementation in Langchain. 18 | # [1] E. Karpas, et al. arXiv:2205.00445 19 | class ReadRetrieveReadApproach(Approach): 20 | 21 | template_prefix = \ 22 | "You are an intelligent assistant helping Contoso Inc employees with their healthcare plan questions and employee handbook questions. " \ 23 | "Answer the question using only the data provided in the information sources below. " \ 24 | "For tabular information return it as an html table. Do not return markdown format. " \ 25 | "Each source has a name followed by colon and the actual data, quote the source name for each piece of data you use in the response. " \ 26 | "For example, if the question is \"What color is the sky?\" and one of the information sources says \"info123: the sky is blue whenever it's not cloudy\", then answer with \"The sky is blue [info123]\" " \ 27 | "It's important to strictly follow the format where the name of the source is in square brackets at the end of the sentence, and only up to the prefix before the colon (\":\"). " \ 28 | "If there are multiple sources, cite each one in their own square brackets. For example, use \"[info343][ref-76]\" and not \"[info343,ref-76]\". " \ 29 | "Never quote tool names as sources." \ 30 | "If you cannot answer using the sources below, say that you don't know. " \ 31 | "\n\nYou can access to the following tools:" 32 | 33 | template_suffix = """ 34 | Begin! 35 | 36 | Question: {input} 37 | 38 | Thought: {agent_scratchpad}""" 39 | 40 | CognitiveSearchToolDescription = "useful for searching the Microsoft employee benefits information such as healthcare plans, retirement plans, etc." 41 | 42 | def __init__(self, search_client: SearchClient, openai_deployment: str, sourcepage_field: str, content_field: str): 43 | self.search_client = search_client 44 | self.openai_deployment = openai_deployment 45 | self.sourcepage_field = sourcepage_field 46 | self.content_field = content_field 47 | 48 | def retrieve(self, q: str, overrides: dict) -> any: 49 | use_semantic_captions = True if overrides.get("semantic_captions") else False 50 | top = overrides.get("top") or 3 51 | exclude_category = overrides.get("exclude_category") or None 52 | filter = "category ne '{}'".format(exclude_category.replace("'", "''")) if exclude_category else None 53 | 54 | if overrides.get("semantic_ranker"): 55 | r = self.search_client.search(q, 56 | filter=filter, 57 | query_type=QueryType.SEMANTIC, 58 | query_language="en-us", 59 | query_speller="lexicon", 60 | semantic_configuration_name="default", 61 | top = top, 62 | query_caption="extractive|highlight-false" if use_semantic_captions else None) 63 | else: 64 | r = self.search_client.search(q, filter=filter, top=top) 65 | if use_semantic_captions: 66 | self.results = [doc[self.sourcepage_field] + ":" + nonewlines(" -.- ".join([c.text for c in doc['@search.captions']])) for doc in r] 67 | else: 68 | self.results = [doc[self.sourcepage_field] + ":" + nonewlines(doc[self.content_field][:250]) for doc in r] 69 | content = "\n".join(self.results) 70 | return content 71 | 72 | def run(self, q: str, overrides: dict) -> any: 73 | # Not great to keep this as instance state, won't work with interleaving (e.g. if using async), but keeps the example simple 74 | self.results = None 75 | 76 | # Use to capture thought process during iterations 77 | cb_handler = HtmlCallbackHandler() 78 | cb_manager = CallbackManager(handlers=[cb_handler]) 79 | 80 | acs_tool = Tool(name = "CognitiveSearch", func = lambda q: self.retrieve(q, overrides), description = self.CognitiveSearchToolDescription) 81 | employee_tool = EmployeeInfoTool("Employee1") 82 | tools = [acs_tool, employee_tool] 83 | 84 | prompt = ZeroShotAgent.create_prompt( 85 | tools=tools, 86 | prefix=overrides.get("prompt_template_prefix") or self.template_prefix, 87 | suffix=overrides.get("prompt_template_suffix") or self.template_suffix, 88 | input_variables = ["input", "agent_scratchpad"]) 89 | llm = AzureOpenAI(deployment_name=self.openai_deployment, temperature=overrides.get("temperature") or 0.3, openai_api_key=openai.api_key) 90 | chain = LLMChain(llm = llm, prompt = prompt) 91 | agent_exec = AgentExecutor.from_agent_and_tools( 92 | agent = ZeroShotAgent(llm_chain = chain, tools = tools), 93 | tools = tools, 94 | verbose = True, 95 | callback_manager = cb_manager) 96 | result = agent_exec.run(q) 97 | 98 | # Remove references to tool names that might be confused with a citation 99 | result = result.replace("[CognitiveSearch]", "").replace("[Employee]", "") 100 | 101 | return {"data_points": self.results or [], "answer": result, "thoughts": cb_handler.get_and_reset_log()} 102 | 103 | class EmployeeInfoTool(CsvLookupTool): 104 | employee_name: str = "" 105 | 106 | def __init__(self, employee_name: str): 107 | super().__init__(filename = "data/employeeinfo.csv", key_field = "name", name = "Employee", description = "useful for answering questions about the employee, their benefits and other personal information") 108 | self.func = self.employee_info 109 | self.employee_name = employee_name 110 | 111 | def employee_info(self, unused: str) -> str: 112 | return self.lookup(self.employee_name) 113 | -------------------------------------------------------------------------------- /app/backend/approaches/retrievethenread.py: -------------------------------------------------------------------------------- 1 | import openai 2 | from approaches.approach import Approach 3 | from azure.search.documents import SearchClient 4 | from azure.search.documents.models import QueryType 5 | from text import nonewlines 6 | 7 | # Simple retrieve-then-read implementation, using the Cognitive Search and OpenAI APIs directly. It first retrieves 8 | # top documents from search, then constructs a prompt with them, and then uses OpenAI to generate an completion 9 | # (answer) with that prompt. 10 | class RetrieveThenReadApproach(Approach): 11 | 12 | template = \ 13 | "You are an intelligent assistant helping Contoso Inc employees with their healthcare plan questions and employee handbook questions. " + \ 14 | "Use 'you' to refer to the individual asking the questions even if they ask with 'I'. " + \ 15 | "Answer the following question using only the data provided in the sources below. " + \ 16 | "For tabular information return it as an html table. Do not return markdown format. " + \ 17 | "Each source has a name followed by colon and the actual information, always include the source name for each fact you use in the response. " + \ 18 | "If you cannot answer using the sources below, say you don't know. " + \ 19 | """ 20 | 21 | ### 22 | Question: 'What is the deductible for the employee plan for a visit to Overlake in Bellevue?' 23 | 24 | Sources: 25 | info1.txt: deductibles depend on whether you are in-network or out-of-network. In-network deductibles are $500 for employee and $1000 for family. Out-of-network deductibles are $1000 for employee and $2000 for family. 26 | info2.pdf: Overlake is in-network for the employee plan. 27 | info3.pdf: Overlake is the name of the area that includes a park and ride near Bellevue. 28 | info4.pdf: In-network institutions include Overlake, Swedish and others in the region 29 | 30 | Answer: 31 | In-network deductibles are $500 for employee and $1000 for family [info1.txt] and Overlake is in-network for the employee plan [info2.pdf][info4.pdf]. 32 | 33 | ### 34 | Question: '{q}'? 35 | 36 | Sources: 37 | {retrieved} 38 | 39 | Answer: 40 | """ 41 | 42 | def __init__(self, search_client: SearchClient, openai_deployment: str, sourcepage_field: str, content_field: str): 43 | self.search_client = search_client 44 | self.openai_deployment = openai_deployment 45 | self.sourcepage_field = sourcepage_field 46 | self.content_field = content_field 47 | 48 | def run(self, q: str, overrides: dict) -> any: 49 | use_semantic_captions = True if overrides.get("semantic_captions") else False 50 | top = overrides.get("top") or 3 51 | exclude_category = overrides.get("exclude_category") or None 52 | filter = "category ne '{}'".format(exclude_category.replace("'", "''")) if exclude_category else None 53 | 54 | if overrides.get("semantic_ranker"): 55 | r = self.search_client.search(q, 56 | filter=filter, 57 | query_type=QueryType.SEMANTIC, 58 | query_language="en-us", 59 | query_speller="lexicon", 60 | semantic_configuration_name="default", 61 | top=top, 62 | query_caption="extractive|highlight-false" if use_semantic_captions else None) 63 | else: 64 | r = self.search_client.search(q, filter=filter, top=top) 65 | if use_semantic_captions: 66 | results = [doc[self.sourcepage_field] + ": " + nonewlines(" . ".join([c.text for c in doc['@search.captions']])) for doc in r] 67 | else: 68 | results = [doc[self.sourcepage_field] + ": " + nonewlines(doc[self.content_field]) for doc in r] 69 | content = "\n".join(results) 70 | 71 | prompt = (overrides.get("prompt_template") or self.template).format(q=q, retrieved=content) 72 | completion = openai.Completion.create( 73 | engine=self.openai_deployment, 74 | prompt=prompt, 75 | temperature=overrides.get("temperature") or 0.3, 76 | max_tokens=1024, 77 | n=1, 78 | stop=["\n"]) 79 | 80 | return {"data_points": results, "answer": completion.choices[0].text, "thoughts": f"Question:
{q}

Prompt:
" + prompt.replace('\n', '
')} 81 | -------------------------------------------------------------------------------- /app/backend/data/employeeinfo.csv: -------------------------------------------------------------------------------- 1 | name,title,insurance,insurancegroup 2 | Employee1,Program Manager,Northwind Health Plus,Family 3 | Employee2,Software Engineer,Northwind Health Plus,Single 4 | Employee3,Software Engineer,Northwind Health Standard,Family 5 | -------------------------------------------------------------------------------- /app/backend/langchainadapters.py: -------------------------------------------------------------------------------- 1 | from typing import Any, Dict, List, Optional 2 | from langchain.callbacks.base import BaseCallbackHandler 3 | from langchain.schema import AgentAction, AgentFinish, LLMResult 4 | 5 | def ch(text: str) -> str: 6 | s = text if isinstance(text, str) else str(text) 7 | return s.replace("<", "<").replace(">", ">").replace("\r", "").replace("\n", "
") 8 | 9 | class HtmlCallbackHandler (BaseCallbackHandler): 10 | html: str = "" 11 | 12 | def get_and_reset_log(self) -> str: 13 | result = self.html 14 | self.html = "" 15 | return result 16 | 17 | def on_llm_start( 18 | self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any 19 | ) -> None: 20 | """Print out the prompts.""" 21 | self.html += f"LLM prompts:
" + "
".join(ch(prompts)) + "
"; 22 | 23 | def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None: 24 | """Do nothing.""" 25 | pass 26 | 27 | def on_llm_error(self, error: Exception, **kwargs: Any) -> None: 28 | self.html += f"LLM error: {ch(error)}
" 29 | 30 | def on_chain_start( 31 | self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any 32 | ) -> None: 33 | """Print out that we are entering a chain.""" 34 | class_name = serialized["name"] 35 | self.html += f"Entering chain: {ch(class_name)}
" 36 | 37 | def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None: 38 | """Print out that we finished a chain.""" 39 | self.html += f"Finished chain
" 40 | 41 | def on_chain_error(self, error: Exception, **kwargs: Any) -> None: 42 | self.html += f"Chain error: {ch(error)}
" 43 | 44 | def on_tool_start( 45 | self, 46 | serialized: Dict[str, Any], 47 | action: AgentAction, 48 | color: Optional[str] = None, 49 | **kwargs: Any, 50 | ) -> None: 51 | """Print out the log in specified color.""" 52 | self.html += f"{ch(action.log)}
" 53 | 54 | def on_tool_end( 55 | self, 56 | output: str, 57 | color: Optional[str] = None, 58 | observation_prefix: Optional[str] = None, 59 | llm_prefix: Optional[str] = None, 60 | **kwargs: Any, 61 | ) -> None: 62 | """If not the final action, print out observation.""" 63 | self.html += f"{ch(observation_prefix)}
{ch(output)}
{ch(llm_prefix)}
" 64 | 65 | def on_tool_error(self, error: Exception, **kwargs: Any) -> None: 66 | self.html += f"Tool error: {ch(error)}
" 67 | 68 | def on_text( 69 | self, 70 | text: str, 71 | color: Optional[str] = None, 72 | end: str = "", 73 | **kwargs: Optional[str], 74 | ) -> None: 75 | """Run when agent ends.""" 76 | self.html += f"{ch(text)}
" 77 | 78 | def on_agent_finish( 79 | self, finish: AgentFinish, color: Optional[str] = None, **kwargs: Any 80 | ) -> None: 81 | """Run on agent end.""" 82 | self.html += f"{ch(finish.log)}
" 83 | -------------------------------------------------------------------------------- /app/backend/lookuptool.py: -------------------------------------------------------------------------------- 1 | from os import path 2 | import csv 3 | from langchain.agents import Tool 4 | from typing import Optional 5 | 6 | class CsvLookupTool(Tool): 7 | def __init__(self, filename: path, key_field: str, name: str = "lookup", description: str = "useful to look up details given an input key as opposite to searching data with an unstructured question"): 8 | super().__init__(name, self.lookup, description) 9 | self.data = {} 10 | with open(filename, newline='') as csvfile: 11 | reader = csv.DictReader(csvfile) 12 | for row in reader: 13 | self.data[row[key_field]] = "\n".join([f"{i}:{row[i]}" for i in row]) 14 | 15 | def lookup(self, key: str) -> Optional[str]: 16 | return self.data.get(key, "") 17 | -------------------------------------------------------------------------------- /app/backend/requirements.txt: -------------------------------------------------------------------------------- 1 | azure-identity==1.13.0b3 2 | Flask==2.2.2 3 | langchain==0.0.78 4 | openai==0.26.4 5 | azure-search-documents==11.4.0b3 6 | azure-storage-blob==12.14.1 7 | -------------------------------------------------------------------------------- /app/backend/text.py: -------------------------------------------------------------------------------- 1 | def nonewlines(s: str) -> str: 2 | return s.replace('\n', ' ').replace('\r', ' ') 3 | -------------------------------------------------------------------------------- /app/frontend/.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "tabWidth": 4, 3 | "printWidth": 160, 4 | "arrowParens": "avoid", 5 | "trailingComma": "none" 6 | } 7 | -------------------------------------------------------------------------------- /app/frontend/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | GPT + Enterprise data | Sample 8 | 9 | 10 |
11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /app/frontend/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "frontend", 3 | "private": true, 4 | "version": "0.0.0", 5 | "type": "module", 6 | "scripts": { 7 | "dev": "vite", 8 | "build": "tsc && vite build", 9 | "watch": "tsc && vite build --watch" 10 | }, 11 | "dependencies": { 12 | "@fluentui/react": "^8.105.3", 13 | "@fluentui/react-icons": "^2.0.195", 14 | "@react-spring/web": "^9.7.1", 15 | "dompurify": "^3.0.1", 16 | "react": "^18.2.0", 17 | "react-dom": "^18.2.0", 18 | "react-router-dom": "^6.8.1" 19 | }, 20 | "devDependencies": { 21 | "@types/dompurify": "^2.4.0", 22 | "@types/react": "^18.0.27", 23 | "@types/react-dom": "^18.0.10", 24 | "@vitejs/plugin-react": "^3.1.0", 25 | "prettier": "^2.8.3", 26 | "typescript": "^4.9.3", 27 | "vite": "^4.1.0" 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /app/frontend/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ManufacturingCSU/azure-search-openai-demo/775bb0535bd17427f4268d7fa6cfe241e04b0c89/app/frontend/public/favicon.ico -------------------------------------------------------------------------------- /app/frontend/src/api/api.ts: -------------------------------------------------------------------------------- 1 | import { AskRequest, AskResponse, ChatRequest } from "./models"; 2 | 3 | export async function askApi(options: AskRequest): Promise { 4 | const response = await fetch("/ask", { 5 | method: "POST", 6 | headers: { 7 | "Content-Type": "application/json" 8 | }, 9 | body: JSON.stringify({ 10 | question: options.question, 11 | approach: options.approach, 12 | overrides: { 13 | semantic_ranker: options.overrides?.semanticRanker, 14 | semantic_captions: options.overrides?.semanticCaptions, 15 | top: options.overrides?.top, 16 | temperature: options.overrides?.temperature, 17 | prompt_template: options.overrides?.promptTemplate, 18 | prompt_template_prefix: options.overrides?.promptTemplatePrefix, 19 | prompt_template_suffix: options.overrides?.promptTemplateSuffix, 20 | exclude_category: options.overrides?.excludeCategory 21 | } 22 | }) 23 | }); 24 | 25 | const parsedResponse: AskResponse = await response.json(); 26 | if (response.status > 299 || !response.ok) { 27 | throw Error(parsedResponse.error || "Unknown error"); 28 | } 29 | 30 | return parsedResponse; 31 | } 32 | 33 | export async function chatApi(options: ChatRequest): Promise { 34 | const response = await fetch("/chat", { 35 | method: "POST", 36 | headers: { 37 | "Content-Type": "application/json" 38 | }, 39 | body: JSON.stringify({ 40 | history: options.history, 41 | approach: options.approach, 42 | overrides: { 43 | semantic_ranker: options.overrides?.semanticRanker, 44 | semantic_captions: options.overrides?.semanticCaptions, 45 | top: options.overrides?.top, 46 | temperature: options.overrides?.temperature, 47 | prompt_template: options.overrides?.promptTemplate, 48 | prompt_template_prefix: options.overrides?.promptTemplatePrefix, 49 | prompt_template_suffix: options.overrides?.promptTemplateSuffix, 50 | exclude_category: options.overrides?.excludeCategory, 51 | suggest_followup_questions: options.overrides?.suggestFollowupQuestions 52 | } 53 | }) 54 | }); 55 | 56 | const parsedResponse: AskResponse = await response.json(); 57 | if (response.status > 299 || !response.ok) { 58 | throw Error(parsedResponse.error || "Unknown error"); 59 | } 60 | 61 | return parsedResponse; 62 | } 63 | 64 | export function getCitationFilePath(citation: string): string { 65 | return `/content/${citation}`; 66 | } 67 | -------------------------------------------------------------------------------- /app/frontend/src/api/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./api"; 2 | export * from "./models"; 3 | -------------------------------------------------------------------------------- /app/frontend/src/api/models.ts: -------------------------------------------------------------------------------- 1 | export const enum Approaches { 2 | RetrieveThenRead = "rtr", 3 | ReadRetrieveRead = "rrr", 4 | ReadDecomposeAsk = "rda" 5 | } 6 | 7 | export type AskRequestOverrides = { 8 | semanticRanker?: boolean; 9 | semanticCaptions?: boolean; 10 | excludeCategory?: string; 11 | top?: number; 12 | temperature?: number; 13 | promptTemplate?: string; 14 | promptTemplatePrefix?: string; 15 | promptTemplateSuffix?: string; 16 | suggestFollowupQuestions?: boolean; 17 | }; 18 | 19 | export type AskRequest = { 20 | question: string; 21 | approach: Approaches; 22 | overrides?: AskRequestOverrides; 23 | }; 24 | 25 | export type AskResponse = { 26 | answer: string; 27 | thoughts: string | null; 28 | data_points: string[]; 29 | error?: string; 30 | }; 31 | 32 | export type ChatTurn = { 33 | user: string; 34 | bot?: string; 35 | }; 36 | 37 | export type ChatRequest = { 38 | history: ChatTurn[]; 39 | approach: Approaches; 40 | overrides?: AskRequestOverrides; 41 | }; 42 | -------------------------------------------------------------------------------- /app/frontend/src/assets/github.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /app/frontend/src/assets/search.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /app/frontend/src/components/AnalysisPanel/AnalysisPanel.module.css: -------------------------------------------------------------------------------- 1 | .thoughtProcess { 2 | font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New", monospace; 3 | word-wrap: break-word; 4 | padding-top: 12px; 5 | padding-bottom: 12px; 6 | } 7 | -------------------------------------------------------------------------------- /app/frontend/src/components/AnalysisPanel/AnalysisPanel.tsx: -------------------------------------------------------------------------------- 1 | import { Pivot, PivotItem } from "@fluentui/react"; 2 | import DOMPurify from "dompurify"; 3 | 4 | import styles from "./AnalysisPanel.module.css"; 5 | 6 | import { SupportingContent } from "../SupportingContent"; 7 | import { AskResponse } from "../../api"; 8 | import { AnalysisPanelTabs } from "./AnalysisPanelTabs"; 9 | 10 | interface Props { 11 | className: string; 12 | activeTab: AnalysisPanelTabs; 13 | onActiveTabChanged: (tab: AnalysisPanelTabs) => void; 14 | activeCitation: string | undefined; 15 | activeCitationPage: number | undefined; 16 | citationHeight: string; 17 | answer: AskResponse; 18 | } 19 | 20 | const pivotItemDisabledStyle = { disabled: true, style: { color: "grey" } }; 21 | 22 | export const AnalysisPanel = ({ answer, activeTab, activeCitation, activeCitationPage, citationHeight, className, onActiveTabChanged }: Props) => { 23 | const isDisabledThoughtProcessTab: boolean = !answer.thoughts; 24 | const isDisabledSupportingContentTab: boolean = !answer.data_points.length; 25 | const isDisabledCitationTab: boolean = !activeCitation; 26 | 27 | const sanitizedThoughts = DOMPurify.sanitize(answer.thoughts!); 28 | 29 | const citationURL = activeCitationPage ? activeCitation+`#page=${activeCitationPage}` : activeCitation; 30 | 31 | return ( 32 | pivotItem && onActiveTabChanged(pivotItem.props.itemKey! as AnalysisPanelTabs)} 36 | > 37 | 42 |
43 |
44 | 49 | 50 | 51 | 56 |