├── .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.md ├── NOTICE.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 └── endpoint.png ├── azure.yaml ├── backend └── package-lock.json ├── data └── TNO │ └── test │ └── TNO.zip ├── docs ├── appcomponents.png └── chatscreen.png ├── infra ├── abbreviations.json ├── core │ ├── ai │ │ └── cognitiveservices.bicep │ ├── databricks │ │ └── databricks.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 ├── databricks.py ├── databricks_unzip_data_draft_03_07.ipynb ├── read-decompose-ask.ipynb └── requirements.txt └── scripts ├── dataprocessor.ps1 ├── dataprocessor.py ├── dataprocessor.sh ├── requirements.txt └── roles.ps1 /.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 | ### azd version? 28 | > run `azd version` and copy paste here. 29 | 30 | ### Versions 31 | > 32 | 33 | ### Mention any other details that might be useful 34 | 35 | > --------------------------------------------------------------- 36 | > Thanks! We'll be in touch soon. 37 | -------------------------------------------------------------------------------- /.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": "Frontend: build", 42 | "type": "node", 43 | "request": "launch", 44 | "cwd": "${workspaceFolder}/app/frontend", 45 | "runtimeExecutable": "npm", 46 | "runtimeArgs": [ 47 | "run-script", 48 | "build" 49 | ], 50 | "console": "integratedTerminal", 51 | } 52 | ], 53 | "inputs": [ 54 | { 55 | "id": "dotEnvFilePath", 56 | "type": "command", 57 | "command": "azure-dev.commands.getDotEnvFilePath" 58 | } 59 | ] 60 | } -------------------------------------------------------------------------------- /.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.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 -------------------------------------------------------------------------------- /NOTICE.MD: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2020 Open Subsurface Data Universe Software / Platform 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Azure Data Manager for Energy + Azure OpenAI demo 2 | 3 | [![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-data-manager-for-energy-openai-demo) 4 | [![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=657138749&machine=standardLinux32gb&devcontainer_path=.devcontainer%2Fdevcontainer.json&location=WestEurope) 5 | 6 | This sample demonstrates a few approaches for creating ChatGPT-like experiences on data from Azure Data Manager for Energy 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. 7 | 8 | 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 Energy, and the experience allows its employees to ask questions about their fields, wells, wellbores, logs, trajectories etc. 9 | 10 | ![RAG Architecture](docs/appcomponents.png) 11 | 12 | ## Features 13 | 14 | * Chat and Q&A interfaces 15 | * Explores various options to help users evaluate the trustworthiness of responses with citations, tracking of source content, etc. 16 | * Shows possible approaches for data preparation, prompt construction, and orchestration of interaction between model (ChatGPT) and retriever (Cognitive Search) 17 | * Settings directly in the UX to tweak the behavior and experiment with options 18 | 19 | ## Getting Started 20 | 21 | > **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. 22 | 23 | > **AZURE RESOURCE COSTS** by default this sample will create Azure App Service, Databricks 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, and the free Form Recognizer resource only analyzes the first 2 pages of each document.) 24 | 25 | ### Prerequisites 26 | 27 | #### To Run Locally 28 | - [Azure Developer CLI](https://aka.ms/azure-dev/install) 29 | - [Python 3+](https://www.python.org/downloads/) 30 | - **Important**: Python and the pip package manager must be in the path in Windows for the setup scripts to work. 31 | - **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`. 32 | - [Node.js](https://nodejs.org/en/download/) 33 | - [Git](https://git-scm.com/downloads) 34 | - [Powershell 7+ (pwsh)](https://github.com/powershell/powershell) - For Windows users only. 35 | - **Important**: Ensure you can run `pwsh.exe` from a PowerShell command. If this fails, you likely need to upgrade PowerShell. 36 | 37 | >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). 38 | 39 | #### To Run in GitHub Codespaces or VS Code Remote Containers 40 | 41 | 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. 42 | 43 | [![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-data-manager-for-energy-openai-demo) 44 | [![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=657138749&machine=standardLinux32gb&devcontainer_path=.devcontainer%2Fdevcontainer.json&location=WestEurope) 45 | 46 | ### Installation 47 | 48 | #### Project Initialization 49 | 50 | 1. Create a new folder and switch to it in the terminal 51 | 1. Run `azd auth login` 52 | 1. Run `azd init -t azure-data-manager-for-energy-openai-demo` 53 | * 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) 54 | 55 | #### Starting from scratch: 56 | 57 | Execute the following command, if you don't have any pre-existing Azure services and want to start from a fresh deployment. 58 | 59 | 1. Run `az login --scope https://graph.microsoft.com//.default` - This is used to perform the Databricks role assignments during deployment (in the absence of Bicep support (https://github.com/Azure/bicep/issues/11035)). 60 | 1. Check that you are logged in to the right subscription by running the command: `az account show --query "{SubscriptionName:name, SubscriptionId:id}"`. If you need to change to the right subscription then run `az account set --subscription ` 61 | 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. 62 | 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. 63 | 64 | It will look like the following: 65 | 66 | !['Output from running azd up'](assets/endpoint.png) 67 | 68 | > 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. 69 | 70 | #### Use existing resources: 71 | 72 | 1. Run `azd env set AZURE_OPENAI_SERVICE {Name of existing OpenAI service}` 73 | 1. Run `azd env set AZURE_OPENAI_RESOURCE_GROUP {Name of existing resource group that OpenAI service is provisioned to}` 74 | 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'. 75 | 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'. 76 | 1. Run `azd up` 77 | 78 | > 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. 79 | 80 | #### Deploying or re-deploying a local clone of the repo: 81 | * Simply run `azd up` 82 | 83 | #### Running locally: 84 | 1. Run `azd login` 85 | 1. Change dir to `app` 86 | 1. Run `./start.ps1` or `./start.sh` or run the "VS Code Task: Start App" to start the project locally. 87 | 88 | #### Sharing Environments 89 | 90 | Run the following if you want to give someone else access to completely deployed and existing environment. 91 | 92 | 1. Install the [Azure CLI](https://learn.microsoft.com/cli/azure/install-azure-cli) 93 | 1. Run `azd init -t azure-data-manager-for-energy-openai-demo` 94 | 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. 95 | 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`. 96 | 97 | ### Quickstart 98 | 99 | * 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. 100 | * Running locally: navigate to 127.0.0.1:5000 101 | 102 | Once in the web app: 103 | * Try different topics in chat or Q&A context. For chat, try follow up questions, clarifications, ask to simplify or elaborate on answer, etc. 104 | * Explore citations and sources 105 | * Click on "settings" to try different options, tweak prompts, etc. 106 | 107 | ## Resources 108 | 109 | * [Revolutionize your Enterprise Data with ChatGPT: Next-gen Apps w/ Azure OpenAI and Cognitive Search](https://aka.ms/entgptsearchblog) 110 | * [Azure Data Manager for Energy](https://aka.ms/azuredatamanagerforenergy) 111 | * [Azure Cognitive Search](https://learn.microsoft.com/azure/search/search-what-is-azure-search) 112 | * [Azure OpenAI Service](https://learn.microsoft.com/azure/cognitive-services/openai/overview) 113 | 114 | ### Note 115 | >Note: The information contained in the sample 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. 116 | 117 | ### FAQ 118 | 119 | ***Question***: Which data are you using? 120 | 121 | ***Answer***: In this demo we are using the open-source TNO dataset, available in the [OSDU Forum GitLab](https://community.opengroup.org/osdu/platform/data-flow/data-loading/open-test-data/-/tree/master/rc--3.0.0/1-data/3-provided/TNO). Specifically we are using the indexed versions of the master data and work product components (WPC): 122 | - Master Data: Field 123 | - Master Data: GeoPoliticalEntity 124 | - Master Data: Organisation 125 | - Master Data: Well 126 | - Master Data: Wellbore 127 | - Work Product Component: WellboreMarkerSet 128 | - Work Product Component: WellLog 129 | - Work Product Component: WellboreTrajectory 130 | 131 | --- 132 | 133 | ***Question***: Why do we need to break up the JSON documents into chunks when Azure Cognitive Search supports searching large documents? 134 | 135 | ***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. 136 | 137 | --- 138 | 139 | ***Question***: Why can I not retrieve aggregated summaries from the data? 140 | 141 | ***Answer***: There's only a certain amount of data that can be retrieved and provided to the AI model due to token limitations. Therefore, the AI cannot consume all the JSON documents and aggregate across. For this use-case you would need to parse the documents to a table structure or similar. The LLM can then create the necessary programmatic queries (i.e. SQL, KQL) and retrieve the aggregated data from the table source directly. 142 | 143 | ### Troubleshooting 144 | 145 | 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 146 | 147 | If the web app fails to deploy and you receive a '404 Not Found' message in your browser, run 'azd deploy'. 148 | -------------------------------------------------------------------------------- /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.search.documents import SearchClient 9 | from approaches.retrievethenread import RetrieveThenReadApproach 10 | from approaches.readretrieveread import ReadRetrieveReadApproach 11 | from approaches.readdecomposeask import ReadDecomposeAsk 12 | from approaches.chatreadretrieveread import ChatReadRetrieveReadApproach 13 | from azure.storage.blob import BlobServiceClient 14 | 15 | # Replace these with your own values, either in environment variables or directly here 16 | AZURE_STORAGE_ACCOUNT = os.environ.get("AZURE_STORAGE_ACCOUNT") or "mystorageaccount" 17 | AZURE_STORAGE_CONTAINER = os.environ.get("AZURE_STORAGE_CONTAINER") or "content" 18 | AZURE_SEARCH_SERVICE = os.environ.get("AZURE_SEARCH_SERVICE") or "gptkb" 19 | AZURE_SEARCH_INDEX = os.environ.get("AZURE_SEARCH_INDEX") or "gptkbindex" 20 | AZURE_OPENAI_SERVICE = os.environ.get("AZURE_OPENAI_SERVICE") or "myopenai" 21 | AZURE_OPENAI_GPT_DEPLOYMENT = os.environ.get("AZURE_OPENAI_GPT_DEPLOYMENT") or "davinci" 22 | AZURE_OPENAI_CHATGPT_DEPLOYMENT = os.environ.get("AZURE_OPENAI_CHATGPT_DEPLOYMENT") or "chat" 23 | 24 | KB_FIELDS_CONTENT = os.environ.get("KB_FIELDS_CONTENT") or "content" 25 | KB_FIELDS_CATEGORY = os.environ.get("KB_FIELDS_CATEGORY") or "category" 26 | KB_FIELDS_SOURCEPAGE = os.environ.get("KB_FIELDS_SOURCEPAGE") or "sourcepage" 27 | 28 | # Use the current user identity to authenticate with Azure OpenAI, Cognitive Search and Blob Storage (no secrets needed, 29 | # just use 'az login' locally, and managed identity when deployed on Azure). If you need to use keys, use separate AzureKeyCredential instances with the 30 | # keys for each service 31 | # 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) 32 | azure_credential = DefaultAzureCredential() 33 | 34 | # Used by the OpenAI SDK 35 | openai.api_type = "azure" 36 | openai.api_base = f"https://{AZURE_OPENAI_SERVICE}.openai.azure.com" 37 | openai.api_version = "2022-12-01" 38 | 39 | # Comment these two lines out if using keys, set your API key in the OPENAI_API_KEY environment variable instead 40 | openai.api_type = "azure_ad" 41 | openai_token = azure_credential.get_token("https://cognitiveservices.azure.com/.default") 42 | openai.api_key = openai_token.token 43 | 44 | # Set up clients for Cognitive Search and Storage 45 | search_client = SearchClient( 46 | endpoint=f"https://{AZURE_SEARCH_SERVICE}.search.windows.net", 47 | index_name=AZURE_SEARCH_INDEX, 48 | credential=azure_credential) 49 | blob_client = BlobServiceClient( 50 | account_url=f"https://{AZURE_STORAGE_ACCOUNT}.blob.core.windows.net", 51 | credential=azure_credential) 52 | blob_container = blob_client.get_container_client(AZURE_STORAGE_CONTAINER) 53 | 54 | # Various approaches to integrate GPT and external knowledge, most applications will use a single one of these patterns 55 | # or some derivative, here we include several for exploration purposes 56 | ask_approaches = { 57 | "rtr": RetrieveThenReadApproach(search_client, AZURE_OPENAI_GPT_DEPLOYMENT, KB_FIELDS_CONTENT, KB_FIELDS_SOURCEPAGE), 58 | "rrr": ReadRetrieveReadApproach(search_client, AZURE_OPENAI_GPT_DEPLOYMENT, KB_FIELDS_SOURCEPAGE, KB_FIELDS_CONTENT), 59 | "rda": ReadDecomposeAsk(search_client, AZURE_OPENAI_GPT_DEPLOYMENT, KB_FIELDS_SOURCEPAGE, KB_FIELDS_CONTENT) 60 | } 61 | 62 | chat_approaches = { 63 | "rrr": ChatReadRetrieveReadApproach(search_client, AZURE_OPENAI_CHATGPT_DEPLOYMENT, AZURE_OPENAI_GPT_DEPLOYMENT, KB_FIELDS_SOURCEPAGE, KB_FIELDS_CONTENT) 64 | } 65 | 66 | app = Flask(__name__) 67 | 68 | @app.route("/", defaults={"path": "index.html"}) 69 | @app.route("/") 70 | def static_file(path): 71 | return app.send_static_file(path) 72 | 73 | # Serve content files from blob storage from within the app to keep the example self-contained. 74 | # *** NOTE *** this assumes that the content files are public, or at least that all users of the app 75 | # can access all the files. This is also slow and memory hungry. 76 | @app.route("/content/") 77 | def content_file(path): 78 | # Remove text from first - from the end of the string in path variable 79 | newPath = path.rsplit("-", 1)[0] 80 | blob = blob_container.get_blob_client(newPath).download_blob() 81 | mime_type = blob.properties["content_settings"]["content_type"] 82 | if mime_type == "application/octet-stream": 83 | mime_type = mimetypes.guess_type(newPath)[0] or "application/octet-stream" 84 | return blob.readall(), 200, {"Content-Type": mime_type, "Content-Disposition": f"inline; filename={newPath}"} 85 | 86 | @app.route("/ask", methods=["POST"]) 87 | def ask(): 88 | ensure_openai_token() 89 | approach = request.json["approach"] 90 | try: 91 | impl = ask_approaches.get(approach) 92 | if not impl: 93 | return jsonify({"error": "unknown approach"}), 400 94 | r = impl.run(request.json["question"], request.json.get("overrides") or {}) 95 | return jsonify(r) 96 | except Exception as e: 97 | logging.exception("Exception in /ask") 98 | return jsonify({"error": str(e)}), 500 99 | 100 | @app.route("/chat", methods=["POST"]) 101 | def chat(): 102 | ensure_openai_token() 103 | approach = request.json["approach"] 104 | try: 105 | impl = chat_approaches.get(approach) 106 | if not impl: 107 | return jsonify({"error": "unknown approach"}), 400 108 | r = impl.run(request.json["history"], request.json.get("overrides") or {}) 109 | return jsonify(r) 110 | except Exception as e: 111 | logging.exception("Exception in /chat") 112 | return jsonify({"error": str(e)}), 500 113 | 114 | def ensure_openai_token(): 115 | global openai_token 116 | if openai_token.expires_on < int(time.time()) - 60: 117 | openai_token = azure_credential.get_token("https://cognitiveservices.azure.com/.default") 118 | openai.api_key = openai_token.token 119 | 120 | if __name__ == "__main__": 121 | app.run() 122 | -------------------------------------------------------------------------------- /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 | import re 7 | 8 | 9 | # Simple retrieve-then-read implementation, using the Cognitive Search and OpenAI APIs directly. It first retrieves 10 | # top documents from search, then constructs a prompt with them, and then uses OpenAI to generate an completion 11 | # (answer) with that prompt. 12 | class ChatReadRetrieveReadApproach(Approach): 13 | prompt_prefix = """<|im_start|>system 14 | You are an intelligent assistant helping Contoso Energy employees with questions about their data, such as fields, wells, wellbores, welltrajectories, wellboremarkersets etc. 15 | Use 'you' to refer to the individual asking the questions even if they ask with 'I'. 16 | Answer the following question using only the data provided in the sources below. 17 | For arrays take the text from all values and treat as a string in the answer. 18 | The record IDs (e.g. contoso-data:reference-data--FacilityStateType:Abandoned:) consists of three main parts (publisher:schema:value:). Reply with the value, unless the user request the full ID. 19 | 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. 20 | 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]. 21 | For tabular information return it as an HTML table. Do not return markdown format. 22 | {follow_up_questions_prompt} 23 | {injected_prompt} 24 | Sources: 25 | {sources} 26 | <|im_end|> 27 | {chat_history} 28 | """ 29 | 30 | follow_up_questions_prompt_content = """Generate three very brief follow-up questions that the user would likely ask next about the data that has been asked about before. 31 | Use double angle brackets to reference the questions, e.g. <>. 32 | Try not to repeat questions that have already been asked. 33 | Only generate questions and do not generate any text before or after the questions, such as 'Next Questions'""" 34 | 35 | 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. 36 | Generate a search query based on the conversation and the new question. 37 | Do not include cited source filenames and document names e.g info.txt or doc.pdf in the search query terms. 38 | Do not use quotes when generating the search query. 39 | Do not include any text inside [] or <<>> in the search query terms. 40 | If the question is not in English, translate the question to English before generating the search query. 41 | 42 | Chat History: 43 | {chat_history} 44 | 45 | Question: 46 | {question} 47 | 48 | Search query: 49 | """ 50 | 51 | def __init__(self, search_client: SearchClient, chatgpt_deployment: str, gpt_deployment: str, sourcepage_field: str, content_field: str): 52 | self.search_client = search_client 53 | self.chatgpt_deployment = chatgpt_deployment 54 | self.gpt_deployment = gpt_deployment 55 | self.sourcepage_field = sourcepage_field 56 | self.content_field = content_field 57 | 58 | 59 | def run(self, history: list[dict], overrides: dict) -> any: 60 | use_semantic_captions = True if overrides.get("semantic_captions") else False 61 | top = overrides.get("top") or 10 62 | exclude_category = overrides.get("exclude_category") or None 63 | filter = "category ne '{}'".format(exclude_category.replace("'", "''")) if exclude_category else None 64 | 65 | # STEP 1: Generate an optimized keyword search query based on the chat history and the last question 66 | prompt = self.query_prompt_template.format(chat_history=self.get_chat_history_as_text(history, include_last_turn=False), question=history[-1]["user"]) 67 | completion = openai.Completion.create( 68 | engine=self.gpt_deployment, 69 | prompt=prompt, 70 | temperature=0.0, 71 | max_tokens=32, 72 | n=1, 73 | stop=["\n"]) 74 | q = completion.choices[0].text 75 | 76 | # STEP 2: Retrieve relevant documents from the search index with the GPT optimized query 77 | if overrides.get("semantic_ranker"): 78 | r = self.search_client.search(q, 79 | filter=filter, 80 | query_type=QueryType.SEMANTIC, 81 | query_language="en-us", 82 | query_speller="lexicon", 83 | semantic_configuration_name="default", 84 | top=top, 85 | query_caption="extractive|highlight-false" if use_semantic_captions else None) 86 | else: 87 | r = self.search_client.search(q, filter=filter, top=top) 88 | if use_semantic_captions: 89 | results = [doc[self.sourcepage_field] + ": " + nonewlines(" . ".join([c.text for c in doc['@search.captions']])) for doc in r] 90 | else: 91 | results = [doc[self.sourcepage_field] + ": " + nonewlines(doc[self.content_field]) for doc in r] 92 | content = "\n".join(results) 93 | #Removing [] because they cause the UI to think text inside [] are citations 94 | content = content.replace('[', '').replace(']', '') 95 | 96 | follow_up_questions_prompt = self.follow_up_questions_prompt_content if overrides.get("suggest_followup_questions") else "" 97 | 98 | # Allow client to replace the entire prompt, or to inject into the exiting prompt using >>> 99 | prompt_override = overrides.get("prompt_template") 100 | if prompt_override is None: 101 | 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) 102 | elif prompt_override.startswith(">>>"): 103 | 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) 104 | else: 105 | prompt = prompt_override.format(sources=content, chat_history=self.get_chat_history_as_text(history), follow_up_questions_prompt=follow_up_questions_prompt) 106 | 107 | # STEP 3: Generate a contextual and content specific answer using the search results and chat history 108 | completion = openai.Completion.create( 109 | engine=self.chatgpt_deployment, 110 | prompt=prompt, 111 | temperature=overrides.get("temperature") or 0.7, 112 | max_tokens=1024, 113 | n=1, 114 | stop=["<|im_end|>", "<|im_start|>"]) 115 | 116 | return {"data_points": results, "answer": completion.choices[0].text, "thoughts": f"Searched for:
{q}

Prompt:
" + prompt.replace('\n', '
')} 117 | 118 | def get_chat_history_as_text(self, history, include_last_turn=True, approx_max_tokens=1000) -> str: 119 | history_text = "" 120 | for h in reversed(history if include_last_turn else history[:-1]): 121 | 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 122 | if len(history_text) > approx_max_tokens*4: 123 | break 124 | 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": "I am readcomposeask", "thoughts": cb_handler.get_and_reset_log()} 90 | return {"data_points": self.results or [], "answer": result, "thoughts": cb_handler.get_and_reset_log()} 91 | 92 | class ReAct(ReActDocstoreAgent): 93 | @classmethod 94 | def create_prompt(cls, tools: List[Tool]) -> BasePromptTemplate: 95 | return prompt 96 | 97 | # Modified version of langchain's ReAct prompt that includes instructions and examples for how to cite information sources 98 | EXAMPLES = [ 99 | """Question: What is the elevation range for the area that the eastern sector of the 100 | Colorado orogeny extends into? 101 | Thought 1: I need to search Colorado orogeny, find the area that the eastern sector 102 | of the Colorado orogeny extends into, then find the elevation range of the 103 | area. 104 | Action 1: Search[Colorado orogeny] 105 | Observation 1: [info1.pdf] The Colorado orogeny was an episode of mountain building (an orogeny) in 106 | Colorado and surrounding areas. 107 | Thought 2: It does not mention the eastern sector. So I need to look up eastern 108 | sector. 109 | Action 2: Lookup[eastern sector] 110 | Observation 2: [info2.txt] (Result 1 / 1) The eastern sector extends into the High Plains and is called 111 | the Central Plains orogeny. 112 | Thought 3: The eastern sector of Colorado orogeny extends into the High Plains. So I 113 | need to search High Plains and find its elevation range. 114 | Action 3: Search[High Plains] 115 | Observation 3: [some_file.pdf] High Plains refers to one of two distinct land regions 116 | Thought 4: I need to instead search High Plains (United States). 117 | Action 4: Search[High Plains (United States)] 118 | Observation 4: [filea.pdf] The High Plains are a subregion of the Great Plains. [another-ref.docx] From east to west, the 119 | High Plains rise in elevation from around 1,800 to 7,000 ft (550 to 2,130 120 | m). 121 | Thought 5: High Plains rise in elevation from around 1,800 to 7,000 ft, so the answer 122 | is 1,800 to 7,000 ft. 123 | Action 5: Finish[1,800 to 7,000 ft (filea.pdf) ]""", 124 | """Question: Musician and satirist Allie Goertz wrote a song about the "The Simpsons" 125 | character Milhouse, who Matt Groening named after who? 126 | Thought 1: The question simplifies to "The Simpsons" character Milhouse is named after 127 | who. I only need to search Milhouse and find who it is named after. 128 | Action 1: Search[Milhouse] 129 | Observation 1: [info7.pdf] Milhouse Mussolini Van Houten is a recurring character in the Fox animated 130 | television series The Simpsons voiced by Pamela Hayden and created by Matt 131 | Groening. 132 | Thought 2: The paragraph does not tell who Milhouse is named after, maybe I can look up 133 | "named after". 134 | Action 2: Lookup[named after] 135 | Observation 2: [historyref2.txt] (Result 1 / 1) Milhouse was named after U.S. president Richard Nixon, whose 136 | middle name was Milhous. 137 | Thought 3: Milhouse was named after U.S. president Richard Nixon, so the answer is 138 | Richard Nixon. 139 | Action 3: Finish[Richard Nixon (historyref2.txt) ]""", 140 | """Question: Which documentary is about Finnish rock groups, Adam Clayton Powell or The 141 | Saimaa Gesture? 142 | Thought 1: I need to search Adam Clayton Powell and The Saimaa Gesture, and find which 143 | documentary is about Finnish rock groups. 144 | Action 1: Search[Adam Clayton Powell] 145 | Observation 1: [info9.pdf] Could not find [Adam Clayton Powell]. Similar: ['Adam Clayton Powell 146 | III', 'Seventh Avenue (Manhattan)', 'Adam Clayton Powell Jr. State Office 147 | Building', 'Isabel Washington Powell', 'Adam Powell', vAdam Clayton Powell 148 | (film)', 'Giancarlo Esposito']. 149 | Thought 2: To find the documentary, I can search Adam Clayton Powell (film). 150 | Action 2: Search[Adam Clayton Powell (film)] 151 | Observation 2: [data123.txt] Adam Clayton Powell is a 1989 American documentary film directed by 152 | Richard Kilberg. The film is about the rise and fall of influential 153 | African-American politician Adam Clayton Powell Jr.[3][4] It was later aired 154 | as part of the PBS series The American Experience. 155 | Thought 3: Adam Clayton Powell (film) is a documentary about an African-American 156 | politician, not Finnish rock groups. So the documentary about Finnish rock 157 | groups must instead be The Saimaa Gesture. 158 | Action 3: Finish[The Saimaa Gesture (data123.txt) ]""", 159 | """Question: What profession does Nicholas Ray and Elia Kazan have in common? 160 | Thought 1: I need to search Nicholas Ray and Elia Kazan, find their professions, then 161 | find the profession they have in common. 162 | Action 1: Search[Nicholas Ray] 163 | Observation 1: [files-987.png] Nicholas Ray (born Raymond Nicholas Kienzle Jr., August 7, 1911 - June 16, 164 | 1979) was an American film director, screenwriter, and actor best known for 165 | the 1955 film Rebel Without a Cause. 166 | Thought 2: Professions of Nicholas Ray are director, screenwriter, and actor. I need 167 | to search Elia Kazan next and find his professions. 168 | Action 2: Search[Elia Kazan] 169 | Observation 2: [files-654.txt] Elia Kazan was an American film and theatre director, producer, screenwriter 170 | and actor. 171 | Thought 3: Professions of Elia Kazan are director, producer, screenwriter, and actor. 172 | So profession Nicholas Ray and Elia Kazan have in common is director, 173 | screenwriter, and actor. 174 | Action 3: Finish[director, screenwriter, actor (files-987.png)(files-654.txt) ]""", 175 | """Question: Which magazine was started first Arthur's Magazine or First for Women? 176 | Thought 1: I need to search Arthur's Magazine and First for Women, and find which was 177 | started first. 178 | Action 1: Search[Arthur's Magazine] 179 | Observation 1: [magazines-1850.pdf] Arthur's Magazine (1844-1846) was an American literary periodical published 180 | in Philadelphia in the 19th century. 181 | Thought 2: Arthur's Magazine was started in 1844. I need to search First for Women 182 | next. 183 | Action 2: Search[First for Women] 184 | Observation 2: [magazines-1900.pdf] First for Women is a woman's magazine published by Bauer Media Group in the 185 | USA.[1] The magazine was started in 1989. 186 | Thought 3: First for Women was started in 1989. 1844 (Arthur's Magazine) < 1989 (First 187 | for Women), so Arthur's Magazine was started first. 188 | Action 3: Finish[Arthur's Magazine (magazines-1850.pdf)(magazines-1900.pdf) ]""", 189 | """Question: Were Pavel Urysohn and Leonid Levin known for the same type of work? 190 | Thought 1: I need to search Pavel Urysohn and Leonid Levin, find their types of work, 191 | then find if they are the same. 192 | Action 1: Search[Pavel Urysohn] 193 | Observation 1: [info4444.pdf] Pavel Samuilovich Urysohn (February 3, 1898 - August 17, 1924) was a Soviet 194 | mathematician who is best known for his contributions in dimension theory. 195 | Thought 2: Pavel Urysohn is a mathematician. I need to search Leonid Levin next and 196 | find its type of work. 197 | Action 2: Search[Leonid Levin] 198 | Observation 2: [datapoints_aaa.txt] Leonid Anatolievich Levin is a Soviet-American mathematician and computer 199 | scientist. 200 | Thought 3: Leonid Levin is a mathematician and computer scientist. So Pavel Urysohn 201 | and Leonid Levin have the same type of work. 202 | Action 3: Finish[yes (info4444.pdf)(datapoints_aaa.txt) ]""", 203 | ] 204 | SUFFIX = """\nQuestion: {input} 205 | {agent_scratchpad}""" 206 | 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. " \ 207 | "Observations are prefixed by their source name in square brackets, source names MUST be included with the actions in the answers." \ 208 | "Only answer the questions using the information from observations, do not speculate." 209 | -------------------------------------------------------------------------------- /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 questions about their data stored in Azure Data Manager for Energy (ADME). " + \ 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: 'Who is the operator of wellbore 1014?' 23 | 24 | Sources: 25 | contoso-opendes:master-data--Wellbore:1014: CurrentOperatorID: contoso-opendesw:master-data--Organisation:Vermilion%20Energy%20Netherlands%20B.V.: 26 | 27 | Answer: 28 | The operator of wellbore 1014 is Vermilion Energy Netherlands B.V. 29 | 30 | ### 31 | Question: '{q}'? 32 | 33 | Sources: 34 | {retrieved} 35 | 36 | Answer: 37 | """ 38 | 39 | def __init__(self, search_client: SearchClient, openai_deployment: str, content_field: str, sourcepage_field: str): 40 | self.search_client = search_client 41 | self.openai_deployment = openai_deployment 42 | self.content_field = content_field 43 | self.sourcepage_field = sourcepage_field 44 | 45 | def run(self, q: str, overrides: dict) -> any: 46 | use_semantic_captions = True if overrides.get("semantic_captions") else False 47 | top = overrides.get("top") or 3 48 | exclude_category = overrides.get("exclude_category") or None 49 | filter = "category ne '{}'".format(exclude_category.replace("'", "''")) if exclude_category else None 50 | 51 | if overrides.get("semantic_ranker"): 52 | r = self.search_client.search(q, 53 | filter=filter, 54 | query_type=QueryType.SEMANTIC, 55 | query_language="en-us", 56 | query_speller="lexicon", 57 | semantic_configuration_name="default", 58 | top=top, 59 | query_caption="extractive|highlight-false" if use_semantic_captions else None) 60 | else: 61 | r = self.search_client.search(q, filter=filter, top=top) 62 | if use_semantic_captions: 63 | results = [doc[self.sourcepage_field] + ": " + nonewlines(" . ".join([c.text for c in doc['@search.captions']])) for doc in r] 64 | #results = [nonewlines(" . ".join([c.text for c in doc['@search.captions']])) for doc in r] 65 | else: 66 | results = [doc[self.sourcepage_field] + ": " + nonewlines(doc[self.content_field]) for doc in r] 67 | #results = [nonewlines(doc[self.content_field]) for doc in r] 68 | content = "\n".join(results) 69 | 70 | prompt = (overrides.get("prompt_template") or self.template).format(q=q, retrieved=content) 71 | print(prompt) 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', '
')} -------------------------------------------------------------------------------- /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.5 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 | databricks-sdk>=0.1.6 -------------------------------------------------------------------------------- /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 | Azure Data Manager for Energy + OpenAI demo 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.5" 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /app/frontend/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure-Samples/azure-data-manager-for-energy-openai-demo/fbd4c70e2e01583bd095535143f64dec63ce3b80/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 | //return "https://openaius.blob.core.windows.net/json/platform2280-jabeland_master-data--Wellbore_1014.json?sp=r&st=2023-06-09T12:40:55Z&se=2023-06-09T20:40:55Z&spr=https&sv=2022-11-02&sr=b&sig=efHVCa48JD63gwn1Bb4IbGTyn8YC8Ix6mzVPmoWIJC4%3D"; 67 | } 68 | -------------------------------------------------------------------------------- /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 | citationHeight: string; 16 | answer: AskResponse; 17 | } 18 | 19 | const pivotItemDisabledStyle = { disabled: true, style: { color: "grey" } }; 20 | 21 | export const AnalysisPanel = ({ answer, activeTab, activeCitation, citationHeight, className, onActiveTabChanged }: Props) => { 22 | const isDisabledThoughtProcessTab: boolean = !answer.thoughts; 23 | const isDisabledSupportingContentTab: boolean = !answer.data_points.length; 24 | const isDisabledCitationTab: boolean = !activeCitation; 25 | 26 | const sanitizedThoughts = DOMPurify.sanitize(answer.thoughts!); 27 | 28 | return ( 29 | pivotItem && onActiveTabChanged(pivotItem.props.itemKey! as AnalysisPanelTabs)} 33 | > 34 | 39 |
40 |
41 | 46 | 47 | 48 | 53 |