├── .devcontainer └── devcontainer.json ├── .github ├── CODE_OF_CONDUCT.md ├── ISSUE_TEMPLATE.md └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── .vscode ├── extensions.json ├── launch.json ├── settings.json └── tasks.json ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE ├── LICENSE.md ├── README.md ├── REST.http ├── app ├── backend │ ├── app.py │ ├── approaches │ │ ├── __init__.py │ │ ├── approach.py │ │ ├── chatreadretrieveread.py │ │ ├── readdecomposeask.py │ │ ├── readretrieveread.py │ │ └── retrievethenread.py │ ├── core │ │ ├── __init__.py │ │ ├── messagebuilder.py │ │ └── modelhelper.py │ ├── data │ │ └── employeeinfo.csv │ ├── gunicorn.conf.py │ ├── langchainadapters.py │ ├── lookuptool.py │ ├── main.py │ ├── requirements.txt │ ├── swagger.json │ └── text.py ├── frontend │ ├── .npmrc │ ├── .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 ├── azure.yaml ├── data └── sample-data.pdf ├── docs ├── .dockerignore ├── .gitignore ├── .nojekyll ├── Dockerfile ├── README.md ├── appcomponents.png ├── chatscreen.png ├── coverpage.md ├── favicon.ico ├── images │ ├── apim1.png │ ├── apim10.png │ ├── apim11.png │ ├── apim12.png │ ├── apim2.png │ ├── apim3.png │ ├── apim4.png │ ├── apim6.png │ ├── apim7.png │ ├── apim8.png │ ├── apim9.png │ ├── azd-init.png │ ├── azd-init2.png │ ├── azd-up-config1.png │ ├── azd-up-config2.png │ ├── azd-up-config3.png │ ├── azd-up-config4.png │ ├── azd-up-config5.png │ ├── azd-up-config6.png │ ├── azd-up-config7.png │ ├── azd-up-config8.png │ ├── backend2.png │ ├── backend3.png │ ├── backend4.png │ ├── bicep-extention.png │ ├── bicep.png │ ├── fig.pptx │ ├── form1.png │ ├── form10.png │ ├── form11.png │ ├── form12.png │ ├── form13.png │ ├── form14.png │ ├── form15.png │ ├── form9-1.png │ ├── form9.png │ ├── infra1.png │ ├── infra3.png │ ├── logicapp1.png │ ├── logicapp2.png │ ├── logicapp3.png │ ├── logicapp4.png │ ├── network-overview.png │ ├── overview.png │ ├── part2-overview.png │ ├── part3-overview.png │ ├── part4-overview.png │ ├── powerapps.png │ ├── search1.png │ ├── search2.png │ ├── search3.png │ ├── search4.png │ ├── search5-1.png │ ├── search5.png │ ├── search6.png │ ├── solution.png │ ├── swagger1.png │ ├── swagger2.png │ ├── swagger3.png │ ├── vscode-devcontainer1.png │ ├── vscode-devcontainer2.png │ ├── vscode-devcontainer3.png │ ├── vscode-devcontainer4.png │ ├── vscode-setup-1.png │ └── workshop-overview.png └── index.html ├── infra ├── abbreviations.json ├── core │ ├── ai │ │ └── cognitiveservices.bicep │ ├── api │ │ └── apimanagement.bicep │ ├── host │ │ ├── appservice.bicep │ │ └── appserviceplan.bicep │ ├── network │ │ ├── nsg.bicep │ │ ├── private-endpoint.bicep │ │ ├── publicip.bicep │ │ └── vnet.bicep │ ├── search │ │ └── search-services.bicep │ ├── security │ │ └── role.bicep │ └── storage │ │ └── storage-account.bicep ├── main.bicep └── main.parameters.json ├── notebooks ├── TextChunking.ipynb ├── chat-read-retrieve-read.ipynb ├── read-decompose-ask.ipynb └── requirements.txt ├── pyproject.toml ├── requirements-dev.txt └── scripts ├── prepdocs.ps1 ├── prepdocs.py ├── prepdocs.sh ├── requirements.txt ├── roles.ps1 └── roles.sh /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Azure Developer CLI", 3 | "image": "mcr.microsoft.com/devcontainers/python:3.10", 4 | "features": { 5 | "ghcr.io/devcontainers/features/node:1": { 6 | "version": "16", 7 | "nodeGypDependencies": false 8 | }, 9 | "ghcr.io/devcontainers/features/powershell:1.1.0": {}, 10 | // "ghcr.io/devcontainers/features/azure-cli:1.0.8": {}, 11 | "ghcr.io/azure/azure-dev/azd:latest": {} 12 | }, 13 | "customizations": { 14 | "vscode": { 15 | "settings": { 16 | "rest-client.decodeEscapedUnicodeCharacters": true 17 | }, 18 | "extensions": [ 19 | "ms-azuretools.azure-dev", 20 | "ms-azuretools.vscode-bicep", 21 | "ms-python.python", 22 | "humao.rest-client", 23 | "arjun.swagger-viewer" 24 | ] 25 | } 26 | }, 27 | "forwardPorts": [ 28 | 5000 29 | ] 30 | } -------------------------------------------------------------------------------- /.github/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Microsoft Open Source Code of Conduct 2 | 3 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). 4 | 5 | Resources: 6 | 7 | - [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/) 8 | - [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) 9 | - Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns 10 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 4 | > Please provide us with the following information: 5 | > --------------------------------------------------------------- 6 | 7 | ### This issue is for a: (mark with an `x`) 8 | ``` 9 | - [ ] bug report -> please search issues before submitting 10 | - [ ] feature request 11 | - [ ] documentation issue or request 12 | - [ ] regression (a behavior that used to work and stopped in a new release) 13 | ``` 14 | 15 | ### Minimal steps to reproduce 16 | > 17 | 18 | ### Any log messages given by the failure 19 | > 20 | 21 | ### Expected/desired behavior 22 | > 23 | 24 | ### OS and Version? 25 | > Windows 7, 8 or 10. Linux (which distribution). macOS (Yosemite? El Capitan? Sierra?) 26 | 27 | ### Versions 28 | > 29 | 30 | ### Mention any other details that might be useful 31 | 32 | > --------------------------------------------------------------- 33 | > Thanks! We'll be in touch soon. 34 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## Purpose 2 | 3 | * ... 4 | 5 | ## Does this introduce a breaking change? 6 | 7 | ``` 8 | [ ] Yes 9 | [ ] No 10 | ``` 11 | 12 | ## Pull Request Type 13 | What kind of change does this Pull Request introduce? 14 | 15 | 16 | ``` 17 | [ ] Bugfix 18 | [ ] Feature 19 | [ ] Code style update (formatting, local variables) 20 | [ ] Refactoring (no functional changes, no api changes) 21 | [ ] Documentation content changes 22 | [ ] Other... Please describe: 23 | ``` 24 | 25 | ## How to Test 26 | * Get the code 27 | 28 | ``` 29 | git clone [repo-address] 30 | cd [repo-name] 31 | git checkout [branch-name] 32 | npm install 33 | ``` 34 | 35 | * Test the code 36 | 37 | ``` 38 | ``` 39 | 40 | ## What to Check 41 | Verify that the following are valid 42 | * ... 43 | 44 | ## Other Information 45 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Azure az webapp deployment details 2 | .azure 3 | 4 | # Byte-compiled / optimized / DLL files 5 | __pycache__/ 6 | *.py[cod] 7 | *$py.class 8 | 9 | # C extensions 10 | *.so 11 | 12 | # Distribution / packaging 13 | .Python 14 | build/ 15 | develop-eggs/ 16 | dist/ 17 | downloads/ 18 | eggs/ 19 | .eggs/ 20 | lib/ 21 | lib64/ 22 | parts/ 23 | sdist/ 24 | var/ 25 | wheels/ 26 | share/python-wheels/ 27 | *.egg-info/ 28 | .installed.cfg 29 | *.egg 30 | MANIFEST 31 | 32 | # PyInstaller 33 | # Usually these files are written by a python script from a template 34 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 35 | *.manifest 36 | *.spec 37 | 38 | # Installer logs 39 | pip-log.txt 40 | pip-delete-this-directory.txt 41 | 42 | # Unit test / coverage reports 43 | htmlcov/ 44 | .tox/ 45 | .nox/ 46 | .coverage 47 | .coverage.* 48 | .cache 49 | nosetests.xml 50 | coverage.xml 51 | *.cover 52 | *.py,cover 53 | .hypothesis/ 54 | .pytest_cache/ 55 | cover/ 56 | 57 | # Translations 58 | *.mo 59 | *.pot 60 | 61 | # Django stuff: 62 | *.log 63 | local_settings.py 64 | db.sqlite3 65 | db.sqlite3-journal 66 | 67 | # Flask stuff: 68 | instance/ 69 | .webassets-cache 70 | 71 | # Scrapy stuff: 72 | .scrapy 73 | 74 | # Sphinx documentation 75 | docs/_build/ 76 | 77 | # PyBuilder 78 | .pybuilder/ 79 | target/ 80 | 81 | # Jupyter Notebook 82 | .ipynb_checkpoints 83 | 84 | # IPython 85 | profile_default/ 86 | ipython_config.py 87 | 88 | # pyenv 89 | # For a library or package, you might want to ignore these files since the code is 90 | # intended to run in multiple environments; otherwise, check them in: 91 | # .python-version 92 | 93 | # pipenv 94 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 95 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 96 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 97 | # install all needed dependencies. 98 | #Pipfile.lock 99 | 100 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 101 | __pypackages__/ 102 | 103 | # Celery stuff 104 | celerybeat-schedule 105 | celerybeat.pid 106 | 107 | # SageMath parsed files 108 | *.sage.py 109 | 110 | # Environments 111 | .env 112 | .venv 113 | env/ 114 | venv/ 115 | ENV/ 116 | env.bak/ 117 | venv.bak/ 118 | 119 | # Spyder project settings 120 | .spyderproject 121 | .spyproject 122 | 123 | # Rope project settings 124 | .ropeproject 125 | 126 | # mkdocs documentation 127 | /site 128 | 129 | # mypy 130 | .mypy_cache/ 131 | .dmypy.json 132 | dmypy.json 133 | 134 | # Pyre type checker 135 | .pyre/ 136 | 137 | # pytype static type analyzer 138 | .pytype/ 139 | 140 | # Cython debug symbols 141 | cython_debug/ 142 | 143 | # NPM 144 | npm-debug.log* 145 | node_modules 146 | static/ 147 | 148 | output/ 149 | .DS_Store -------------------------------------------------------------------------------- /.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": "start.cmd", 16 | "presentation": { 17 | "reveal": "silent" 18 | }, 19 | "options": { 20 | "cwd": "${workspaceFolder}/app" 21 | }, 22 | "problemMatcher": [] 23 | } 24 | ], 25 | "inputs": [ 26 | { 27 | "id": "dotEnvFilePath", 28 | "type": "command", 29 | "command": "azure-dev.commands.getDotEnvFilePath" 30 | } 31 | ] 32 | } -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## [project-title] Changelog 2 | 3 | 4 | # x.y.z (yyyy-mm-dd) 5 | 6 | *Features* 7 | * ... 8 | 9 | *Bug Fixes* 10 | * ... 11 | 12 | *Breaking Changes* 13 | * ... 14 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to [project-title] 2 | 3 | This project welcomes contributions and suggestions. Most contributions require you to agree to a 4 | Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us 5 | the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com. 6 | 7 | When you submit a pull request, a CLA bot will automatically determine whether you need to provide 8 | a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions 9 | provided by the bot. You will only need to do this once across all repos using our CLA. 10 | 11 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). 12 | For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or 13 | contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. 14 | 15 | - [Code of Conduct](#coc) 16 | - [Issues and Bugs](#issue) 17 | - [Feature Requests](#feature) 18 | - [Submission Guidelines](#submit) 19 | 20 | ## Code of Conduct 21 | Help us keep this project open and inclusive. Please read and follow our [Code of Conduct](https://opensource.microsoft.com/codeofconduct/). 22 | 23 | ## Found an Issue? 24 | If you find a bug in the source code or a mistake in the documentation, you can help us by 25 | [submitting an issue](#submit-issue) to the GitHub Repository. Even better, you can 26 | [submit a Pull Request](#submit-pr) with a fix. 27 | 28 | ## Want a Feature? 29 | You can *request* a new feature by [submitting an issue](#submit-issue) to the GitHub 30 | Repository. If you would like to *implement* a new feature, please submit an issue with 31 | a proposal for your work first, to be sure that we can use it. 32 | 33 | * **Small Features** can be crafted and directly [submitted as a Pull Request](#submit-pr). 34 | 35 | ## Submission Guidelines 36 | 37 | ### Submitting an Issue 38 | Before you submit an issue, search the archive, maybe your question was already answered. 39 | 40 | If your issue appears to be a bug, and hasn't been reported, open a new issue. 41 | Help us to maximize the effort we can spend fixing issues and adding new 42 | features, by not reporting duplicate issues. Providing the following information will increase the 43 | chances of your issue being dealt with quickly: 44 | 45 | * **Overview of the Issue** - if an error is being thrown a non-minified stack trace helps 46 | * **Version** - what version is affected (e.g. 0.1.2) 47 | * **Motivation for or Use Case** - explain what are you trying to do and why the current behavior is a bug for you 48 | * **Browsers and Operating System** - is this a problem with all browsers? 49 | * **Reproduce the Error** - provide a live example or a unambiguous set of steps 50 | * **Related Issues** - has a similar issue been reported before? 51 | * **Suggest a Fix** - if you can't fix the bug yourself, perhaps you can point to what might be 52 | causing the problem (line of code or commit) 53 | 54 | You can file new issues by providing the above information at the corresponding repository's issues link: https://github.com/[organization-name]/[repository-name]/issues/new]. 55 | 56 | ### Submitting a Pull Request (PR) 57 | Before you submit your Pull Request (PR) consider the following guidelines: 58 | 59 | * Search the repository (https://github.com/[organization-name]/[repository-name]/pulls) for an open or closed PR 60 | that relates to your submission. You don't want to duplicate effort. 61 | 62 | * Make your changes in a new git fork: 63 | 64 | * Commit your changes using a descriptive commit message 65 | * Push your fork to GitHub: 66 | * In GitHub, create a pull request 67 | * If we suggest changes then: 68 | * Make the required updates. 69 | * Rebase your fork and force push to your GitHub repository (this will update your Pull Request): 70 | 71 | ```shell 72 | git rebase master -i 73 | git push -f 74 | ``` 75 | 76 | That's it! Thank you for your contribution! 77 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Azure Samples 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Microsoft Corporation. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 業務データを活用したAIチャット ワークショップ 2 | 3 | このリポジトリは業務データを活用したAIチャットシステムを構築するためのワークショップ資料です。 4 | [ChatGPT + Enterprise data with Azure OpenAI and Cognitive Search](https://github.com/Azure-Samples/azure-search-openai-demo)および[ChatGPT + Enterprise data with Azure OpenAI and Cognitive Search - 日本語カスタマイズ版 /@nohanaga](https://github.com/nohanaga/azure-search-openai-demo) をベースに作成しています。 5 | 6 | ワークショップ資料は[こちら](https://asashiho.github.io/azure-search-openai-demo/) 7 | 8 | --- 9 | ## ワークショップ概要 10 | 11 | 研究論文の内容もとに適切な回答を作成するチャットシステム の作成を通して、Azure OpenAI Service やAzure Cognitive Searchなどの使い方やチャットシステムを社内に展開するためのWebアプリケーションの作成やAPI基盤の整備などの基礎を学びます。 12 | 13 | このワークショップの特徴は次の2つです。 14 | 15 | - **専門用語や業界独自のナレッジを検索できる** 16 | 17 | ChatGPT(gpt-35-turbo)モデルでトレーニングされたデータに基づいてテキストを生成するのではなく、企業内に閉じたデータをもとに生成します 18 | 19 | - **回答の根拠を明確にする** 20 | 21 | ChatGPTの回答に「引用」をテキストに付加することで信頼できる応答を生成します 22 | 23 | ![](docs/images/workshop-overview.png) 24 | 25 | ### 対象者 26 | このワークショップは、AI技術に興味のあるデータサイエンティスト、エンジニア、研究者、または企業内での情報アクセスやナレッジ共有の改善を目指す方々に適しています。 27 | 28 | 29 | ### 参考資料 30 | 31 | Azure OpenAI Serviceについての技術詳細は、以下を参照してください。 32 | 33 | * [ChatGPT + Enterprise data with Azure OpenAI and Cognitive Search](https://github.com/nohanaga/azure-search-openai-demo) 34 | 35 | * [Azure で ChatGPT × Cognitive Search を使ったエンタープライズサーチを実現](https://qiita.com/nohanaga/items/803c09b5a3a4e2d1776f) 36 | 37 | [![Azure OpenAI Developers セミナー](docs/images/movietitle1.png)](https://www.youtube.com/watch?v=tFgqdHKsOME) 38 | 39 | [![『ChatGPTによって描かれる未来とAI開発の変遷』日本マイクロソフト株式会社 蒲生 弘郷氏](docs/images/movietitle2.png)](https://www.youtube.com/watch?v=l9fpxtz22JU) 40 | 41 | 42 | ## Resources 43 | 44 | * [Revolutionize your Enterprise Data with ChatGPT: Next-gen Apps w/ Azure OpenAI and Cognitive Search](https://aka.ms/entgptsearchblog) 45 | * [Azure Cognitive Search](https://learn.microsoft.com/azure/search/search-what-is-azure-search) 46 | * [Azure OpenAI Service](https://learn.microsoft.com/azure/cognitive-services/openai/overview) 47 | 48 | ### Note 49 | >Note: The PDF documents used in this demo contain information generated using a language model (Azure OpenAI Service). The information contained in these documents is only for demonstration purposes and does not reflect the opinions or beliefs of Microsoft. Microsoft makes no representations or warranties of any kind, express or implied, about the completeness, accuracy, reliability, suitability or availability with respect to the information contained in this document. All rights reserved to Microsoft. 50 | -------------------------------------------------------------------------------- /REST.http: -------------------------------------------------------------------------------- 1 | @backend = https://app-backend-xxx.azurewebsites.net 2 | ### 3 | 4 | ### 5 | POST {{backend}}/chat HTTP/1.1 6 | content-type: application/json 7 | 8 | { 9 | "history": [ 10 | { 11 | "user": "水素ハイブリッド電車とはなんですか" 12 | } 13 | ], 14 | "approach": "rrr", 15 | "overrides": { 16 | "retrieval_mode": "hybrid", 17 | "semantic_ranker": true, 18 | "semantic_captions": false, 19 | "top": 1, 20 | "suggest_followup_questions": false 21 | } 22 | } 23 | 24 | ### 25 | POST {{backend}}/ask HTTP/1.1 26 | content-type: application/json 27 | 28 | { 29 | "question": "水素ハイブリッド電車とはなんですか", 30 | "approach": "rtr", 31 | "overrides": { 32 | "retrieval_mode": "hybrid", 33 | "semantic_ranker": true, 34 | "semantic_captions": false, 35 | "top": 1 36 | } 37 | } 38 | 39 | 40 | ### 41 | API Managementの動作確認 42 | ### 43 | 44 | @apimanagement = https://apim-xxx.azure-api.net 45 | ### 46 | POST {{apimanagement}}/api/ask HTTP/1.1 47 | Content-Type: application/json 48 | 49 | { 50 | "question": "水素ハイブリッド電車とはなんですか", 51 | "approach": "rtr", 52 | "overrides": { 53 | "retrieval_mode": "hybrid", 54 | "semantic_ranker": true, 55 | "semantic_captions": false, 56 | "top": 1 57 | } 58 | } 59 | 60 | 61 | ### 62 | POST {{apimanagement}}/api/ask HTTP/1.1 63 | Content-Type: application/json 64 | Ocp-Apim-Subscription-Key: xxxxxxxxxxxxxxxx 65 | 66 | { 67 | "question": "水素ハイブリッド電車とはなんですか", 68 | "approach": "rtr", 69 | "overrides": { 70 | "retrieval_mode": "hybrid", 71 | "semantic_ranker": true, 72 | "semantic_captions": false, 73 | "top": 1 74 | } 75 | } -------------------------------------------------------------------------------- /app/backend/app.py: -------------------------------------------------------------------------------- 1 | import io 2 | import logging 3 | import mimetypes 4 | import os 5 | import time 6 | 7 | import openai 8 | from azure.identity.aio import DefaultAzureCredential 9 | from azure.search.documents.aio import SearchClient 10 | from azure.storage.blob.aio import BlobServiceClient 11 | from quart import ( 12 | Blueprint, 13 | Quart, 14 | abort, 15 | current_app, 16 | jsonify, 17 | request, 18 | send_file, 19 | send_from_directory, 20 | ) 21 | 22 | from approaches.chatreadretrieveread import ChatReadRetrieveReadApproach 23 | from approaches.readdecomposeask import ReadDecomposeAsk 24 | from approaches.readretrieveread import ReadRetrieveReadApproach 25 | from approaches.retrievethenread import RetrieveThenReadApproach 26 | 27 | # Replace these with your own values, either in environment variables or directly here 28 | AZURE_STORAGE_ACCOUNT = os.getenv("AZURE_STORAGE_ACCOUNT", "mystorageaccount") 29 | AZURE_STORAGE_CONTAINER = os.getenv("AZURE_STORAGE_CONTAINER", "content") 30 | AZURE_SEARCH_SERVICE = os.getenv("AZURE_SEARCH_SERVICE", "gptkb") 31 | AZURE_SEARCH_INDEX = os.getenv("AZURE_SEARCH_INDEX", "gptkbindex") 32 | AZURE_OPENAI_SERVICE = os.getenv("AZURE_OPENAI_SERVICE", "myopenai") 33 | AZURE_OPENAI_GPT_DEPLOYMENT = os.getenv("AZURE_OPENAI_GPT_DEPLOYMENT", "davinci") 34 | AZURE_OPENAI_CHATGPT_DEPLOYMENT = os.getenv("AZURE_OPENAI_CHATGPT_DEPLOYMENT", "chat") 35 | AZURE_OPENAI_CHATGPT_MODEL = os.getenv("AZURE_OPENAI_CHATGPT_MODEL", "gpt-35-turbo") 36 | AZURE_OPENAI_EMB_DEPLOYMENT = os.getenv("AZURE_OPENAI_EMB_DEPLOYMENT", "embedding") 37 | 38 | KB_FIELDS_CONTENT = os.getenv("KB_FIELDS_CONTENT", "content") 39 | KB_FIELDS_CATEGORY = os.getenv("KB_FIELDS_CATEGORY", "category") 40 | KB_FIELDS_SOURCEPAGE = os.getenv("KB_FIELDS_SOURCEPAGE", "sourcepage") 41 | 42 | CONFIG_OPENAI_TOKEN = "openai_token" 43 | CONFIG_CREDENTIAL = "azure_credential" 44 | CONFIG_ASK_APPROACHES = "ask_approaches" 45 | CONFIG_CHAT_APPROACHES = "chat_approaches" 46 | CONFIG_BLOB_CLIENT = "blob_client" 47 | 48 | 49 | bp = Blueprint("routes", __name__, static_folder='static') 50 | 51 | @bp.route("/") 52 | async def index(): 53 | return await bp.send_static_file("index.html") 54 | 55 | @bp.route("/favicon.ico") 56 | async def favicon(): 57 | return await bp.send_static_file("favicon.ico") 58 | 59 | @bp.route("/assets/") 60 | async def assets(path): 61 | return await send_from_directory("static/assets", path) 62 | 63 | # Serve content files from blob storage from within the app to keep the example self-contained. 64 | # *** NOTE *** this assumes that the content files are public, or at least that all users of the app 65 | # can access all the files. This is also slow and memory hungry. 66 | @bp.route("/content/") 67 | async def content_file(path): 68 | blob_container = current_app.config[CONFIG_BLOB_CLIENT].get_container_client(AZURE_STORAGE_CONTAINER) 69 | blob = await blob_container.get_blob_client(path).download_blob() 70 | if not blob.properties or not blob.properties.has_key("content_settings"): 71 | abort(404) 72 | mime_type = blob.properties["content_settings"]["content_type"] 73 | if mime_type == "application/octet-stream": 74 | mime_type = mimetypes.guess_type(path)[0] or "application/octet-stream" 75 | blob_file = io.BytesIO() 76 | await blob.readinto(blob_file) 77 | blob_file.seek(0) 78 | return await send_file(blob_file, mimetype=mime_type, as_attachment=False, attachment_filename=path) 79 | 80 | @bp.route("/ask", methods=["POST"]) 81 | async def ask(): 82 | if not request.is_json: 83 | return jsonify({"error": "request must be json"}), 415 84 | request_json = await request.get_json() 85 | approach = request_json["approach"] 86 | try: 87 | impl = current_app.config[CONFIG_ASK_APPROACHES].get(approach) 88 | if not impl: 89 | return jsonify({"error": "unknown approach"}), 400 90 | r = await impl.run(request_json["question"], request_json.get("overrides") or {}) 91 | return jsonify(r) 92 | except Exception as e: 93 | logging.exception("Exception in /ask") 94 | return jsonify({"error": str(e)}), 500 95 | 96 | @bp.route("/chat", methods=["POST"]) 97 | async def chat(): 98 | if not request.is_json: 99 | return jsonify({"error": "request must be json"}), 415 100 | request_json = await request.get_json() 101 | approach = request_json["approach"] 102 | try: 103 | impl = current_app.config[CONFIG_CHAT_APPROACHES].get(approach) 104 | if not impl: 105 | return jsonify({"error": "unknown approach"}), 400 106 | r = await impl.run(request_json["history"], request_json.get("overrides") or {}) 107 | return jsonify(r) 108 | except Exception as e: 109 | logging.exception("Exception in /chat") 110 | return jsonify({"error": str(e)}), 500 111 | 112 | @bp.before_request 113 | async def ensure_openai_token(): 114 | openai_token = current_app.config[CONFIG_OPENAI_TOKEN] 115 | if openai_token.expires_on < time.time() + 60: 116 | openai_token = await current_app.config[CONFIG_CREDENTIAL].get_token("https://cognitiveservices.azure.com/.default") 117 | current_app.config[CONFIG_OPENAI_TOKEN] = openai_token 118 | openai.api_key = openai_token.token 119 | 120 | @bp.before_app_serving 121 | async def setup_clients(): 122 | 123 | # Use the current user identity to authenticate with Azure OpenAI, Cognitive Search and Blob Storage (no secrets needed, 124 | # just use 'az login' locally, and managed identity when deployed on Azure). If you need to use keys, use separate AzureKeyCredential instances with the 125 | # keys for each service 126 | # 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) 127 | azure_credential = DefaultAzureCredential(exclude_shared_token_cache_credential = True) 128 | 129 | # Set up clients for Cognitive Search and Storage 130 | search_client = SearchClient( 131 | endpoint=f"https://{AZURE_SEARCH_SERVICE}.search.windows.net", 132 | index_name=AZURE_SEARCH_INDEX, 133 | credential=azure_credential) 134 | blob_client = BlobServiceClient( 135 | account_url=f"https://{AZURE_STORAGE_ACCOUNT}.blob.core.windows.net", 136 | credential=azure_credential) 137 | 138 | # Used by the OpenAI SDK 139 | openai.api_base = f"https://{AZURE_OPENAI_SERVICE}.openai.azure.com" 140 | openai.api_version = "2023-05-15" 141 | openai.api_type = "azure_ad" 142 | openai_token = await azure_credential.get_token( 143 | "https://cognitiveservices.azure.com/.default" 144 | ) 145 | openai.api_key = openai_token.token 146 | 147 | # Store on app.config for later use inside requests 148 | current_app.config[CONFIG_OPENAI_TOKEN] = openai_token 149 | current_app.config[CONFIG_CREDENTIAL] = azure_credential 150 | current_app.config[CONFIG_BLOB_CLIENT] = blob_client 151 | # Various approaches to integrate GPT and external knowledge, most applications will use a single one of these patterns 152 | # or some derivative, here we include several for exploration purposes 153 | current_app.config[CONFIG_ASK_APPROACHES] = { 154 | "rtr": RetrieveThenReadApproach( 155 | search_client, 156 | AZURE_OPENAI_CHATGPT_DEPLOYMENT, 157 | AZURE_OPENAI_CHATGPT_MODEL, 158 | AZURE_OPENAI_EMB_DEPLOYMENT, 159 | KB_FIELDS_SOURCEPAGE, 160 | KB_FIELDS_CONTENT 161 | ), 162 | "rrr": ReadRetrieveReadApproach( 163 | search_client, 164 | AZURE_OPENAI_GPT_DEPLOYMENT, 165 | AZURE_OPENAI_EMB_DEPLOYMENT, 166 | KB_FIELDS_SOURCEPAGE, 167 | KB_FIELDS_CONTENT 168 | ), 169 | "rda": ReadDecomposeAsk(search_client, 170 | AZURE_OPENAI_GPT_DEPLOYMENT, 171 | AZURE_OPENAI_EMB_DEPLOYMENT, 172 | KB_FIELDS_SOURCEPAGE, 173 | KB_FIELDS_CONTENT 174 | ) 175 | } 176 | current_app.config[CONFIG_CHAT_APPROACHES] = { 177 | "rrr": ChatReadRetrieveReadApproach( 178 | search_client, 179 | AZURE_OPENAI_CHATGPT_DEPLOYMENT, 180 | AZURE_OPENAI_CHATGPT_MODEL, 181 | AZURE_OPENAI_EMB_DEPLOYMENT, 182 | KB_FIELDS_SOURCEPAGE, 183 | KB_FIELDS_CONTENT, 184 | ) 185 | } 186 | 187 | 188 | def create_app(): 189 | app = Quart(__name__) 190 | app.register_blueprint(bp) 191 | return app 192 | -------------------------------------------------------------------------------- /app/backend/approaches/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asashiho/azure-search-openai-demo/d47885dc3ddbd4c29e89cc08ce0c601f1806429a/app/backend/approaches/__init__.py -------------------------------------------------------------------------------- /app/backend/approaches/approach.py: -------------------------------------------------------------------------------- 1 | from abc import ABC, abstractmethod 2 | from typing import Any 3 | 4 | 5 | class ChatApproach(ABC): 6 | @abstractmethod 7 | async def run(self, history: list[dict], overrides: dict[str, Any]) -> Any: 8 | ... 9 | 10 | 11 | class AskApproach(ABC): 12 | @abstractmethod 13 | async def run(self, q: str, overrides: dict[str, Any]) -> Any: 14 | ... 15 | -------------------------------------------------------------------------------- /app/backend/approaches/chatreadretrieveread.py: -------------------------------------------------------------------------------- 1 | from typing import Any 2 | 3 | import openai 4 | from azure.search.documents.aio import SearchClient 5 | from azure.search.documents.models import QueryType 6 | 7 | from approaches.approach import ChatApproach 8 | from core.messagebuilder import MessageBuilder 9 | from core.modelhelper import get_token_limit 10 | from text import nonewlines 11 | 12 | 13 | class ChatReadRetrieveReadApproach(ChatApproach): 14 | # Chat roles 15 | SYSTEM = "system" 16 | USER = "user" 17 | ASSISTANT = "assistant" 18 | 19 | """ 20 | Cognitive SearchとOpenAIのAPIを直接使用した、シンプルなretrieve-then-readの実装です。はじめに検索で上位の文書を取得し、それを使ってプロンプトを作成し、OpenAIを使ってそのプロンプトを使った回答を生成します。 21 | """ 22 | system_message_chat_conversation = """アシスタントは、鉄道技術に関する質問をサポートします。回答は簡潔にしてください。 23 | {follow_up_questions_prompt} 24 | {injected_prompt} 25 | """ 26 | follow_up_questions_prompt_content = """鉄道技術について、ユーザーが次に尋ねそうな質問を3つ作成します。""" 27 | 28 | query_prompt_template = """以下は、これまでの会話の履歴と、鉄道技術に関するナレッジベースで検索して回答する必要があります。 29 | """ 30 | query_prompt_few_shots = [ 31 | {'role' : USER, 'content' : '水素ハイブリット電車について教えて' }, 32 | {'role' : ASSISTANT, 'content' : '水素ハイブリット電車の概要を表示' }, 33 | {'role' : USER, 'content' : '水素供給システムの利点は?' }, 34 | {'role' : ASSISTANT, 'content' : '車両の⾧距離走行を可能にします' } 35 | ] 36 | 37 | def __init__(self, search_client: SearchClient, chatgpt_deployment: str, chatgpt_model: str, embedding_deployment: str, sourcepage_field: str, content_field: str): 38 | self.search_client = search_client 39 | self.chatgpt_deployment = chatgpt_deployment 40 | self.chatgpt_model = chatgpt_model 41 | self.embedding_deployment = embedding_deployment 42 | self.sourcepage_field = sourcepage_field 43 | self.content_field = content_field 44 | self.chatgpt_token_limit = get_token_limit(chatgpt_model) 45 | 46 | async def run(self, history: list[dict[str, str]], overrides: dict[str, Any]) -> Any: 47 | has_text = overrides.get("retrieval_mode") in ["text", "hybrid", None] 48 | has_vector = overrides.get("retrieval_mode") in ["vectors", "hybrid", None] 49 | use_semantic_captions = True if overrides.get("semantic_captions") and has_text 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 | user_q = 'Generate search query for: ' + history[-1]["user"] 55 | 56 | # STEP 1: Generate an optimized keyword search query based on the chat history and the last question 57 | messages = self.get_messages_from_history( 58 | self.query_prompt_template, 59 | self.chatgpt_model, 60 | history, 61 | user_q, 62 | self.query_prompt_few_shots, 63 | self.chatgpt_token_limit - len(user_q) 64 | ) 65 | 66 | chat_completion = await openai.ChatCompletion.acreate( 67 | deployment_id=self.chatgpt_deployment, 68 | model=self.chatgpt_model, 69 | messages=messages, 70 | temperature=0.0, 71 | max_tokens=32, 72 | n=1) 73 | 74 | query_text = chat_completion.choices[0].message.content 75 | if query_text.strip() == "0": 76 | query_text = history[-1]["user"] # Use the last user input if we failed to generate a better query 77 | 78 | # STEP 2: Retrieve relevant documents from the search index with the GPT optimized query 79 | 80 | # If retrieval mode includes vectors, compute an embedding for the query 81 | if has_vector: 82 | query_vector = (await openai.Embedding.acreate(engine=self.embedding_deployment, input=query_text))["data"][0]["embedding"] 83 | else: 84 | query_vector = None 85 | 86 | # Only keep the text query if the retrieval mode uses text, otherwise drop it 87 | if not has_text: 88 | query_text = None 89 | 90 | # Use semantic L2 reranker if requested and if retrieval mode is text or hybrid (vectors + text) 91 | if overrides.get("semantic_ranker") and has_text: 92 | r = await self.search_client.search(query_text, 93 | filter=filter, 94 | query_type=QueryType.SEMANTIC, 95 | query_language="ja-JP", 96 | query_speller="none", 97 | semantic_configuration_name="default", 98 | top=top, 99 | query_caption="extractive|highlight-false" if use_semantic_captions else None, 100 | vector=query_vector, 101 | top_k=50 if query_vector else None, 102 | vector_fields="embedding" if query_vector else None) 103 | else: 104 | r = await self.search_client.search(query_text, 105 | filter=filter, 106 | top=top, 107 | vector=query_vector, 108 | top_k=50 if query_vector else None, 109 | vector_fields="embedding" if query_vector else None) 110 | if use_semantic_captions: 111 | results = [doc[self.sourcepage_field] + ": " + nonewlines(" . ".join([c.text for c in doc['@search.captions']])) async for doc in r] 112 | else: 113 | results = [doc[self.sourcepage_field] + ": " + nonewlines(doc[self.content_field]) async for doc in r] 114 | content = "\n".join(results) 115 | 116 | follow_up_questions_prompt = self.follow_up_questions_prompt_content if overrides.get("suggest_followup_questions") else "" 117 | 118 | # STEP 3: Generate a contextual and content specific answer using the search results and chat history 119 | 120 | # Allow client to replace the entire prompt, or to inject into the exiting prompt using >>> 121 | prompt_override = overrides.get("prompt_override") 122 | if prompt_override is None: 123 | system_message = self.system_message_chat_conversation.format(injected_prompt="", follow_up_questions_prompt=follow_up_questions_prompt) 124 | elif prompt_override.startswith(">>>"): 125 | system_message = self.system_message_chat_conversation.format(injected_prompt=prompt_override[3:] + "\n", follow_up_questions_prompt=follow_up_questions_prompt) 126 | else: 127 | system_message = prompt_override.format(follow_up_questions_prompt=follow_up_questions_prompt) 128 | 129 | messages = self.get_messages_from_history( 130 | system_message + "\n\nSources:\n" + content, 131 | self.chatgpt_model, 132 | history, 133 | history[-1]["user"], 134 | max_tokens=self.chatgpt_token_limit) 135 | 136 | chat_completion = await openai.ChatCompletion.acreate( 137 | deployment_id=self.chatgpt_deployment, 138 | model=self.chatgpt_model, 139 | messages=messages, 140 | temperature=overrides.get("temperature") or 0.7, 141 | max_tokens=1024, 142 | n=1) 143 | 144 | chat_content = chat_completion.choices[0].message.content 145 | 146 | msg_to_display = '\n\n'.join([str(message) for message in messages]) 147 | 148 | return {"data_points": results, "answer": chat_content, "thoughts": f"Searched for:
{query_text}

Conversations:
" + msg_to_display.replace('\n', '
')} 149 | 150 | def get_messages_from_history(self, system_prompt: str, model_id: str, history: list[dict[str, str]], user_conv: str, few_shots = [], max_tokens: int = 4096) -> list: 151 | message_builder = MessageBuilder(system_prompt, model_id) 152 | 153 | # Add examples to show the chat what responses we want. It will try to mimic any responses and make sure they match the rules laid out in the system message. 154 | for shot in few_shots: 155 | message_builder.append_message(shot.get('role'), shot.get('content')) 156 | 157 | user_content = user_conv 158 | append_index = len(few_shots) + 1 159 | 160 | message_builder.append_message(self.USER, user_content, index=append_index) 161 | 162 | for h in reversed(history[:-1]): 163 | if bot_msg := h.get("bot"): 164 | message_builder.append_message(self.ASSISTANT, bot_msg, index=append_index) 165 | if user_msg := h.get("user"): 166 | message_builder.append_message(self.USER, user_msg, index=append_index) 167 | if message_builder.token_length > max_tokens: 168 | break 169 | 170 | messages = message_builder.messages 171 | return messages 172 | -------------------------------------------------------------------------------- /app/backend/approaches/readdecomposeask.py: -------------------------------------------------------------------------------- 1 | import re 2 | from typing import Any, Optional, Sequence 3 | 4 | import openai 5 | from azure.search.documents.aio import SearchClient 6 | from azure.search.documents.models import QueryType 7 | from langchain.agents import AgentExecutor, Tool 8 | from langchain.agents.react.base import ReActDocstoreAgent 9 | from langchain.callbacks.manager import CallbackManager 10 | from langchain.llms.openai import AzureOpenAI 11 | from langchain.prompts import BasePromptTemplate, PromptTemplate 12 | from langchain.tools.base import BaseTool 13 | 14 | from approaches.approach import AskApproach 15 | from langchainadapters import HtmlCallbackHandler 16 | from text import nonewlines 17 | 18 | 19 | class ReadDecomposeAsk(AskApproach): 20 | def __init__(self, search_client: SearchClient, openai_deployment: str, embedding_deployment: str, sourcepage_field: str, content_field: str): 21 | self.search_client = search_client 22 | self.openai_deployment = openai_deployment 23 | self.embedding_deployment = embedding_deployment 24 | self.sourcepage_field = sourcepage_field 25 | self.content_field = content_field 26 | 27 | async def search(self, query_text: str, overrides: dict[str, Any]) -> tuple[list[str], str]: 28 | has_text = overrides.get("retrieval_mode") in ["text", "hybrid", None] 29 | has_vector = overrides.get("retrieval_mode") in ["vectors", "hybrid", None] 30 | use_semantic_captions = True if overrides.get("semantic_captions") and has_text else False 31 | top = overrides.get("top") or 3 32 | exclude_category = overrides.get("exclude_category") or None 33 | filter = "category ne '{}'".format(exclude_category.replace("'", "''")) if exclude_category else None 34 | 35 | # If retrieval mode includes vectors, compute an embedding for the query 36 | if has_vector: 37 | query_vector = (await openai.Embedding.acreate(engine=self.embedding_deployment, input=query_text))["data"][0]["embedding"] 38 | else: 39 | query_vector = None 40 | 41 | # Only keep the text query if the retrieval mode uses text, otherwise drop it 42 | if not has_text: 43 | query_text = "" 44 | 45 | if overrides.get("semantic_ranker") and has_text: 46 | r = await self.search_client.search(query_text, 47 | filter=filter, 48 | query_type=QueryType.SEMANTIC, 49 | query_language="en-us", 50 | query_speller="lexicon", 51 | semantic_configuration_name="default", 52 | top=top, 53 | query_caption="extractive|highlight-false" if use_semantic_captions else None, 54 | vector=query_vector, 55 | top_k=50 if query_vector else None, 56 | vector_fields="embedding" if query_vector else None) 57 | else: 58 | r = await self.search_client.search(query_text, 59 | filter=filter, 60 | top=top, 61 | vector=query_vector, 62 | top_k=50 if query_vector else None, 63 | vector_fields="embedding" if query_vector else None) 64 | if use_semantic_captions: 65 | results = [doc[self.sourcepage_field] + ":" + nonewlines(" . ".join([c.text for c in doc['@search.captions'] ])) async for doc in r] 66 | else: 67 | results = [doc[self.sourcepage_field] + ":" + nonewlines(doc[self.content_field][:500]) async for doc in r] 68 | return results, "\n".join(results) 69 | 70 | async def lookup(self, q: str) -> Optional[str]: 71 | r = await self.search_client.search(q, 72 | top = 1, 73 | include_total_count=True, 74 | query_type=QueryType.SEMANTIC, 75 | query_language="en-us", 76 | query_speller="lexicon", 77 | semantic_configuration_name="default", 78 | query_answer="extractive|count-1", 79 | query_caption="extractive|highlight-false") 80 | 81 | answers = await r.get_answers() 82 | if answers and len(answers) > 0: 83 | return answers[0].text 84 | if await r.get_count() > 0: 85 | return "\n".join([d['content'] async for d in r]) 86 | return None 87 | 88 | async def run(self, q: str, overrides: dict[str, Any]) -> Any: 89 | 90 | search_results = None 91 | async def search_and_store(q: str) -> Any: 92 | nonlocal search_results 93 | search_results, content = await self.search(q, overrides) 94 | return content 95 | 96 | # Use to capture thought process during iterations 97 | cb_handler = HtmlCallbackHandler() 98 | cb_manager = CallbackManager(handlers=[cb_handler]) 99 | 100 | llm = AzureOpenAI(deployment_name=self.openai_deployment, temperature=overrides.get("temperature") or 0.3, openai_api_key=openai.api_key) 101 | tools = [ 102 | Tool(name="Search", func=lambda _: 'Not implemented', coroutine=search_and_store, description="useful for when you need to ask with search", callbacks=cb_manager), 103 | Tool(name="Lookup", func=lambda _: 'Not implemented', coroutine=self.lookup, description="useful for when you need to ask with lookup", callbacks=cb_manager) 104 | ] 105 | 106 | prompt_prefix = overrides.get("prompt_template") 107 | prompt = PromptTemplate.from_examples( 108 | EXAMPLES, SUFFIX, ["input", "agent_scratchpad"], prompt_prefix + "\n\n" + PREFIX if prompt_prefix else PREFIX) 109 | 110 | class ReAct(ReActDocstoreAgent): 111 | @classmethod 112 | def create_prompt(cls, tools: Sequence[BaseTool]) -> BasePromptTemplate: 113 | return prompt 114 | 115 | agent = ReAct.from_llm_and_tools(llm, tools) 116 | chain = AgentExecutor.from_agent_and_tools(agent, tools, verbose=True, callback_manager=cb_manager) 117 | result = await chain.arun(q) 118 | 119 | # Replace substrings of the form with [file.ext] so that the frontend can render them as links, match them with a regex to avoid 120 | # generalizing too much and disrupt HTML snippets if present 121 | result = re.sub(r"<([a-zA-Z0-9_ \-\.]+)>", r"[\1]", result) 122 | 123 | return {"data_points": search_results or [], "answer": result, "thoughts": cb_handler.get_and_reset_log()} 124 | 125 | 126 | 127 | # Modified version of langchain's ReAct prompt that includes instructions and examples for how to cite information sources 128 | EXAMPLES = [ 129 | """Question: コロラド造山帯の東部が広がる地域の標高範囲は? 130 | Thought: コロラド造山帯を検索し、その東部地域が広がっている地域を見つける必要がある。 131 | コロラド造山帯の東部が伸びている地域を見つけ、その地域の標高範囲を調べたい。 132 | そして、その地域の標高範囲を求める。 133 | Action: Search[Colorado orogeny] 134 | Observation: コロラド造山は、コロラド州とその周辺地域で起こった造山活動である。 135 | Thought: 東部地区については書かれていない。だから、東部セクターについて調べる必要がある。 136 | """, 137 | """Question: ミュージシャンで風刺作家のアリー・ゴーツが、『ザ・シンプソンズ』のキャラクター、ミルハウスについて曲を書いた。 138 | マット・グルーニングが誰にちなんで名付けたか? 139 | Thought: 質問は「ザ・シンプソンズ」のキャラクター、ミルハウスは誰にちなんで名づけられたか?誰の名前か?ミルハウスを検索して、誰の名前にちなんでいるのかを見つけるだけでいい。 140 | Action: Search[Milhouse] 141 | Observation: ミルハウス・ムッソリーニ・ヴァン・ホーテン(Milhouse Mussolini Van Houten)は、FOXのテレビアニメ『ザ・シンプソンズ』シリーズの登場人物である。「ザ・シンプソンズ」のレギュラーキャラクターで、声はパメラ・ヘイデン、作画はマット・グルーニング。よってグルーニングによって創作された。 142 | """, 143 | """Question: ニコラス・レイとエリア・カザンの共通点は? 144 | Thought: ニコラス・レイとエリア・カザンを検索し、彼らの職業を見つけ、そして共通する職業を見つける必要がある。共通する職業を見つける必要がある。 145 | Action: Search[Nicholas Ray] 146 | Observation: ニコラス・レイ(Raymond Nicholas Kienzle Jr、1911年8月7日 - 1979年6月16日、1979年6月16日)は、1955年の映画『理由なき反抗』で知られるアメリカの映画監督、脚本家、俳優。1955年の映画『理由なき反抗』で知られる。 147 | """, 148 | """Question: パヴェル・ウリソーンとレオニード・レヴィンは同じタイプの仕事で知られていたのですか? 149 | Thought: パヴェル・ウリゾーンとレオニード・レヴィンを検索して、彼らの仕事の種類を見つける必要がある、そして、両者が同じかどうかを調べる必要がある。 150 | Action: Search[Pavel Urysohn] 151 | """, 152 | ] 153 | SUFFIX = """\nQuestion: {input} 154 | {agent_scratchpad}""" 155 | PREFIX = "次の例に示すように、質問を個々の検索に分割して、質問に答えられるようになるまで事実を見つけることで、質問に答えます。" \ 156 | "Observationsは角括弧で囲まれたソース名を前につける。ソース名は、回答のアクションに含めなければならない。" \ 157 | "すべての質問は、検索の結果から答えなければなりません。 " 158 | "質問にはできるだけ正直に答え、推測や自分の知識ではなく、観察から得た情報のみを使って答えること。" 159 | -------------------------------------------------------------------------------- /app/backend/approaches/readretrieveread.py: -------------------------------------------------------------------------------- 1 | from typing import Any 2 | 3 | import openai 4 | from azure.search.documents.aio import SearchClient 5 | from azure.search.documents.models import QueryType 6 | from langchain.agents import AgentExecutor, Tool, ZeroShotAgent 7 | from langchain.callbacks.manager import CallbackManager, Callbacks 8 | from langchain.chains import LLMChain 9 | from langchain.llms.openai import AzureOpenAI 10 | 11 | from approaches.approach import AskApproach 12 | from langchainadapters import HtmlCallbackHandler 13 | from lookuptool import CsvLookupTool 14 | from text import nonewlines 15 | 16 | 17 | class ReadRetrieveReadApproach(AskApproach): 18 | """ 19 | どのような情報が欠けているかを確認するために質問を繰り返し評価することによって、質問に答えます。質問は2つの部分で構成されます: 20 | 1. GPTを使用して、さらに情報が必要かどうかを確認する 21 | 2. より多くのデータが必要な場合は、要求された "ツール "を使用してデータを取得する。 22 | GPTへの最後の呼び出しが、実際の質問に答えます。 23 | """ 24 | 25 | template_prefix = \ 26 | "あなたは、鉄道技術に関する質問をサポートするインテリジェントアシスタントです。 " \ 27 | "以下の情報源に記載されているデータのみを使用して質問に答えてください。 " \ 28 | "表形式の情報については、HTMLとして返してください。マークダウン形式は返さないでください。" \ 29 | "各ソースには、名前の後にコロンと実際のデータが続き、レスポンスで使用するデータごとにソース名を引用します。" \ 30 | "たとえば, もし質問が \"空の色は?\" であり、情報源が \"info123: 曇っていなければ空は青い\", という場合は \"空は青い[info123]\"と答えます " \ 31 | "出典の名前は文末の角括弧の中に、コロンの前の接頭辞までしか書かないという形式に従う必要があります。 (\":\"). " \ 32 | "複数の出典がある場合は、それぞれの出典を角括弧で囲んで引用します。例えば, \"[info343][ref-76]\" と \"[info343,ref-76]\". " \ 33 | "ツール名を情報源として引用してはいけません" \ 34 | "以下の資料で答えられない場合は、「わからない」と答えてください。" \ 35 | "\n\n以下のツールにアクセスできます:" 36 | 37 | template_suffix = """ 38 | Begin! 39 | 40 | Question: {input} 41 | 42 | Thought: {agent_scratchpad}""" 43 | 44 | CognitiveSearchToolDescription = "鉄道技術を知りたいときに便利です" 45 | 46 | def __init__(self, search_client: SearchClient, openai_deployment: str, embedding_deployment: str, sourcepage_field: str, content_field: str): 47 | self.search_client = search_client 48 | self.openai_deployment = openai_deployment 49 | self.embedding_deployment = embedding_deployment 50 | self.sourcepage_field = sourcepage_field 51 | self.content_field = content_field 52 | 53 | async def retrieve(self, query_text: str, overrides: dict[str, Any]) -> Any: 54 | has_text = overrides.get("retrieval_mode") in ["text", "hybrid", None] 55 | has_vector = overrides.get("retrieval_mode") in ["vectors", "hybrid", None] 56 | use_semantic_captions = True if overrides.get("semantic_captions") and has_text else False 57 | top = overrides.get("top") or 3 58 | exclude_category = overrides.get("exclude_category") or None 59 | filter = "category ne '{}'".format(exclude_category.replace("'", "''")) if exclude_category else None 60 | 61 | # If retrieval mode includes vectors, compute an embedding for the query 62 | if has_vector: 63 | query_vector = (await openai.Embedding.acreate(engine=self.embedding_deployment, input=query_text))["data"][0]["embedding"] 64 | else: 65 | query_vector = None 66 | 67 | # Only keep the text query if the retrieval mode uses text, otherwise drop it 68 | if not has_text: 69 | query_text = "" 70 | 71 | # Use semantic ranker if requested and if retrieval mode is text or hybrid (vectors + text) 72 | if overrides.get("semantic_ranker") and has_text: 73 | r = await self.search_client.search(query_text, 74 | filter=filter, 75 | query_type=QueryType.SEMANTIC, 76 | query_language="en-us", 77 | query_speller="lexicon", 78 | semantic_configuration_name="default", 79 | top = top, 80 | query_caption="extractive|highlight-false" if use_semantic_captions else None, 81 | vector=query_vector, 82 | top_k=50 if query_vector else None, 83 | vector_fields="embedding" if query_vector else None) 84 | else: 85 | r = await self.search_client.search(query_text, 86 | filter=filter, 87 | top=top, 88 | vector=query_vector, 89 | top_k=50 if query_vector else None, 90 | vector_fields="embedding" if query_vector else None) 91 | if use_semantic_captions: 92 | results = [doc[self.sourcepage_field] + ":" + nonewlines(" -.- ".join([c.text for c in doc['@search.captions']])) async for doc in r] 93 | else: 94 | results = [doc[self.sourcepage_field] + ":" + nonewlines(doc[self.content_field][:250]) async for doc in r] 95 | content = "\n".join(results) 96 | return results, content 97 | 98 | async def run(self, q: str, overrides: dict[str, Any]) -> Any: 99 | 100 | retrieve_results = None 101 | async def retrieve_and_store(q: str) -> Any: 102 | nonlocal retrieve_results 103 | retrieve_results, content = await self.retrieve(q, overrides) 104 | return content 105 | 106 | # Use to capture thought process during iterations 107 | cb_handler = HtmlCallbackHandler() 108 | cb_manager = CallbackManager(handlers=[cb_handler]) 109 | 110 | acs_tool = Tool(name="CognitiveSearch", 111 | func=lambda _: 'Not implemented', 112 | coroutine=retrieve_and_store, 113 | description=self.CognitiveSearchToolDescription, 114 | callbacks=cb_manager) 115 | employee_tool = EmployeeInfoTool("Employee1", callbacks=cb_manager) 116 | tools = [acs_tool, employee_tool] 117 | 118 | prompt = ZeroShotAgent.create_prompt( 119 | tools=tools, 120 | prefix=overrides.get("prompt_template_prefix") or self.template_prefix, 121 | suffix=overrides.get("prompt_template_suffix") or self.template_suffix, 122 | input_variables = ["input", "agent_scratchpad"]) 123 | llm = AzureOpenAI(deployment_name=self.openai_deployment, temperature=overrides.get("temperature") or 0.3, openai_api_key=openai.api_key) 124 | chain = LLMChain(llm = llm, prompt = prompt) 125 | agent_exec = AgentExecutor.from_agent_and_tools( 126 | agent = ZeroShotAgent(llm_chain = chain), 127 | tools = tools, 128 | verbose = True, 129 | callback_manager = cb_manager) 130 | result = await agent_exec.arun(q) 131 | 132 | # Remove references to tool names that might be confused with a citation 133 | result = result.replace("[CognitiveSearch]", "").replace("[Employee]", "") 134 | 135 | return {"data_points": retrieve_results or [], "answer": result, "thoughts": cb_handler.get_and_reset_log()} 136 | 137 | class EmployeeInfoTool(CsvLookupTool): 138 | employee_name: str = "" 139 | 140 | def __init__(self, employee_name: str, callbacks: Callbacks = None): 141 | super().__init__(filename="data/employeeinfo.csv", 142 | key_field="name", 143 | name="Employee", 144 | description="useful for answering questions about the employee, their benefits and other personal information", 145 | callbacks=callbacks) 146 | self.func = lambda _: 'Not implemented' 147 | self.coroutine = self.employee_info 148 | self.employee_name = employee_name 149 | 150 | async def employee_info(self, name: str) -> str: 151 | return self.lookup(name) 152 | -------------------------------------------------------------------------------- /app/backend/approaches/retrievethenread.py: -------------------------------------------------------------------------------- 1 | from typing import Any 2 | 3 | import openai 4 | from azure.search.documents.aio import SearchClient 5 | from azure.search.documents.models import QueryType 6 | 7 | from approaches.approach import AskApproach 8 | from core.messagebuilder import MessageBuilder 9 | from text import nonewlines 10 | 11 | 12 | class RetrieveThenReadApproach(AskApproach): 13 | """ 14 | Cognitive SearchとOpenAIのAPIを直接使用した、シンプルなretrieve-then-readの実装です。まず検索から上位のドキュメントを取得し、それを使ってプロンプトを作成し、回答を生成します。 15 | """ 16 | 17 | system_chat_template = \ 18 | "あなたは、鉄道技術に関する質問をサポートするインテリジェントアシスタントです。 " + \ 19 | "相手が「わたし」で質問しても、「あなた」を使って質問者を指してください。" + \ 20 | "以下の資料に記載されているデータのみを使って、質問に答えてください。" + \ 21 | "表形式の情報については、HTMLとして返してください。マークダウン形式は返さないでください。" + \ 22 | "各出典元には、名前の後にコロンが続き、実際の情報が記載されています。回答で使用する各事実には、必ず出典元名を記載してください。" + \ 23 | "以下の資料で答えられない場合は、「わからない」と答えなさい。以下の例を使って答えてください。" 24 | 25 | #shots/sample conversation 26 | question = """ 27 | '水素ハイブリッド電車とはなんですか?' 28 | 29 | Sources: 30 | info1.txt: 水素をエネルギー源とする燃料電池は、高いエネルギー変換効率と環境負荷の少なさが特徴 31 | info2.txt: 燃料電池自動車やバスの技術を鉄道車両の技術と融合・応用することにより、水素ハイブリッド電車を開発し、実証試験を始めた。 32 | """ 33 | answer = "水素を燃料とする燃料電池は、高いエネルギー変換効率と環境負荷の少なさが特徴[info1.txt]です。この技術を鉄道車両に応用し、水素ハイブリッド電車を開発し、実証試験を始めました。[info2.txt] " 34 | 35 | def __init__(self, search_client: SearchClient, openai_deployment: str, chatgpt_model: str, embedding_deployment: str, sourcepage_field: str, content_field: str): 36 | self.search_client = search_client 37 | self.openai_deployment = openai_deployment 38 | self.chatgpt_model = chatgpt_model 39 | self.embedding_deployment = embedding_deployment 40 | self.sourcepage_field = sourcepage_field 41 | self.content_field = content_field 42 | 43 | async def run(self, q: str, overrides: dict[str, Any]) -> Any: 44 | has_text = overrides.get("retrieval_mode") in ["text", "hybrid", None] 45 | has_vector = overrides.get("retrieval_mode") in ["vectors", "hybrid", None] 46 | use_semantic_captions = True if overrides.get("semantic_captions") and has_text 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 retrieval mode includes vectors, compute an embedding for the query 52 | if has_vector: 53 | query_vector = (await openai.Embedding.acreate(engine=self.embedding_deployment, input=q))["data"][0]["embedding"] 54 | else: 55 | query_vector = None 56 | 57 | # Only keep the text query if the retrieval mode uses text, otherwise drop it 58 | query_text = q if has_text else "" 59 | 60 | # Use semantic ranker if requested and if retrieval mode is text or hybrid (vectors + text) 61 | if overrides.get("semantic_ranker") and has_text: 62 | r = await self.search_client.search(query_text, 63 | filter=filter, 64 | query_type=QueryType.SEMANTIC, 65 | query_language="en-us", 66 | query_speller="lexicon", 67 | semantic_configuration_name="default", 68 | top=top, 69 | query_caption="extractive|highlight-false" if use_semantic_captions else None, 70 | vector=query_vector, 71 | top_k=50 if query_vector else None, 72 | vector_fields="embedding" if query_vector else None) 73 | else: 74 | r = await self.search_client.search(query_text, 75 | filter=filter, 76 | top=top, 77 | vector=query_vector, 78 | top_k=50 if query_vector else None, 79 | vector_fields="embedding" if query_vector else None) 80 | if use_semantic_captions: 81 | results = [doc[self.sourcepage_field] + ": " + nonewlines(" . ".join([c.text for c in doc['@search.captions']])) async for doc in r] 82 | else: 83 | results = [doc[self.sourcepage_field] + ": " + nonewlines(doc[self.content_field]) async for doc in r] 84 | content = "\n".join(results) 85 | 86 | message_builder = MessageBuilder(overrides.get("prompt_template") or self.system_chat_template, self.chatgpt_model) 87 | 88 | # add user question 89 | user_content = q + "\n" + f"Sources:\n {content}" 90 | message_builder.append_message('user', user_content) 91 | 92 | # Add shots/samples. This helps model to mimic response and make sure they match rules laid out in system message. 93 | message_builder.append_message('assistant', self.answer) 94 | message_builder.append_message('user', self.question) 95 | 96 | messages = message_builder.messages 97 | chat_completion = await openai.ChatCompletion.acreate( 98 | deployment_id=self.openai_deployment, 99 | model=self.chatgpt_model, 100 | messages=messages, 101 | temperature=overrides.get("temperature") or 0.3, 102 | max_tokens=1024, 103 | n=1) 104 | 105 | return {"data_points": results, "answer": chat_completion.choices[0].message.content, "thoughts": f"Question:
{query_text}

Prompt:
" + '\n\n'.join([str(message) for message in messages])} 106 | -------------------------------------------------------------------------------- /app/backend/core/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asashiho/azure-search-openai-demo/d47885dc3ddbd4c29e89cc08ce0c601f1806429a/app/backend/core/__init__.py -------------------------------------------------------------------------------- /app/backend/core/messagebuilder.py: -------------------------------------------------------------------------------- 1 | from .modelhelper import num_tokens_from_messages 2 | 3 | 4 | class MessageBuilder: 5 | """ 6 | A class for building and managing messages in a chat conversation. 7 | Attributes: 8 | message (list): A list of dictionaries representing chat messages. 9 | model (str): The name of the ChatGPT model. 10 | token_count (int): The total number of tokens in the conversation. 11 | Methods: 12 | __init__(self, system_content: str, chatgpt_model: str): Initializes the MessageBuilder instance. 13 | append_message(self, role: str, content: str, index: int = 1): Appends a new message to the conversation. 14 | """ 15 | 16 | def __init__(self, system_content: str, chatgpt_model: str): 17 | self.messages = [{'role': 'system', 'content': system_content}] 18 | self.model = chatgpt_model 19 | self.token_length = num_tokens_from_messages( 20 | self.messages[-1], self.model) 21 | 22 | def append_message(self, role: str, content: str, index: int = 1): 23 | self.messages.insert(index, {'role': role, 'content': content}) 24 | self.token_length += num_tokens_from_messages( 25 | self.messages[index], self.model) 26 | -------------------------------------------------------------------------------- /app/backend/core/modelhelper.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import tiktoken 4 | 5 | MODELS_2_TOKEN_LIMITS = { 6 | "gpt-35-turbo": 4000, 7 | "gpt-3.5-turbo": 4000, 8 | "gpt-35-turbo-16k": 16000, 9 | "gpt-3.5-turbo-16k": 16000, 10 | "gpt-4": 8100, 11 | "gpt-4-32k": 32000 12 | } 13 | 14 | AOAI_2_OAI = { 15 | "gpt-35-turbo": "gpt-3.5-turbo", 16 | "gpt-35-turbo-16k": "gpt-3.5-turbo-16k" 17 | } 18 | 19 | 20 | def get_token_limit(model_id: str) -> int: 21 | if model_id not in MODELS_2_TOKEN_LIMITS: 22 | raise ValueError("Expected model gpt-35-turbo and above") 23 | return MODELS_2_TOKEN_LIMITS[model_id] 24 | 25 | 26 | def num_tokens_from_messages(message: dict[str, str], model: str) -> int: 27 | """ 28 | Calculate the number of tokens required to encode a message. 29 | Args: 30 | message (dict): The message to encode, represented as a dictionary. 31 | model (str): The name of the model to use for encoding. 32 | Returns: 33 | int: The total number of tokens required to encode the message. 34 | Example: 35 | message = {'role': 'user', 'content': 'Hello, how are you?'} 36 | model = 'gpt-3.5-turbo' 37 | num_tokens_from_messages(message, model) 38 | output: 11 39 | """ 40 | encoding = tiktoken.encoding_for_model(get_oai_chatmodel_tiktok(model)) 41 | num_tokens = 2 # For "role" and "content" keys 42 | for key, value in message.items(): 43 | num_tokens += len(encoding.encode(value)) 44 | return num_tokens 45 | 46 | 47 | def get_oai_chatmodel_tiktok(aoaimodel: str) -> str: 48 | message = "Expected Azure OpenAI ChatGPT model name" 49 | if aoaimodel == "" or aoaimodel is None: 50 | raise ValueError(message) 51 | if aoaimodel not in AOAI_2_OAI and aoaimodel not in MODELS_2_TOKEN_LIMITS: 52 | raise ValueError(message) 53 | return AOAI_2_OAI.get(aoaimodel) or aoaimodel 54 | -------------------------------------------------------------------------------- /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/gunicorn.conf.py: -------------------------------------------------------------------------------- 1 | import multiprocessing 2 | 3 | max_requests = 1000 4 | max_requests_jitter = 50 5 | log_file = "-" 6 | bind = "0.0.0.0" 7 | 8 | timeout = 600 9 | num_cpus = multiprocessing.cpu_count() 10 | workers = (num_cpus * 2) + 1 11 | worker_class = "uvicorn.workers.UvicornWorker" 12 | -------------------------------------------------------------------------------- /app/backend/langchainadapters.py: -------------------------------------------------------------------------------- 1 | from typing import Any, Dict, List, Optional, Union 2 | 3 | from langchain.callbacks.base import BaseCallbackHandler 4 | from langchain.schema import AgentAction, AgentFinish, LLMResult 5 | 6 | 7 | def ch(text: Union[str, object]) -> str: 8 | s = text if isinstance(text, str) else str(text) 9 | return s.replace("<", "<").replace(">", ">").replace("\r", "").replace("\n", "
") 10 | 11 | class HtmlCallbackHandler (BaseCallbackHandler): 12 | html: str = "" 13 | 14 | def get_and_reset_log(self) -> str: 15 | result = self.html 16 | self.html = "" 17 | return result 18 | 19 | def on_llm_start( 20 | self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any 21 | ) -> None: 22 | """Print out the prompts.""" 23 | self.html += "LLM prompts:
" + "
".join(ch(prompts)) + "
" 24 | 25 | def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None: 26 | """Do nothing.""" 27 | pass 28 | 29 | def on_llm_error(self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any) -> None: 30 | self.html += f"LLM error: {ch(error)}
" 31 | 32 | def on_chain_start( 33 | self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any 34 | ) -> None: 35 | """Print out that we are entering a chain.""" 36 | class_name = serialized["name"] 37 | self.html += f"Entering chain: {ch(class_name)}
" 38 | 39 | def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None: 40 | """Print out that we finished a chain.""" 41 | self.html += "Finished chain
" 42 | 43 | def on_chain_error(self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any) -> None: 44 | self.html += f"Chain error: {ch(error)}
" 45 | 46 | def on_tool_start( 47 | self, 48 | serialized: Dict[str, Any], 49 | input_str: str, 50 | color: Optional[str] = None, 51 | **kwargs: Any, 52 | ) -> None: 53 | """Print out the log in specified color.""" 54 | pass 55 | 56 | def on_tool_end( 57 | self, 58 | output: str, 59 | color: Optional[str] = None, 60 | observation_prefix: Optional[str] = None, 61 | llm_prefix: Optional[str] = None, 62 | **kwargs: Any, 63 | ) -> None: 64 | """If not the final action, print out observation.""" 65 | self.html += f"{ch(observation_prefix)}
{ch(output)}
{ch(llm_prefix)}
" 66 | 67 | def on_tool_error(self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any) -> None: 68 | self.html += f"Tool error: {ch(error)}
" 69 | 70 | def on_text( 71 | self, 72 | text: str, 73 | color: Optional[str] = None, 74 | **kwargs: Optional[str], 75 | ) -> None: 76 | """Run when agent ends.""" 77 | self.html += f"{ch(text)}
" 78 | 79 | def on_agent_action( 80 | self, 81 | action: AgentAction, 82 | color: Optional[str] = None, 83 | **kwargs: Any) -> Any: 84 | self.html += f"{ch(action.log)}
" 85 | 86 | def on_agent_finish( 87 | self, finish: AgentFinish, color: Optional[str] = None, **kwargs: Any 88 | ) -> None: 89 | """Run on agent end.""" 90 | self.html += f"{ch(finish.log)}
" 91 | -------------------------------------------------------------------------------- /app/backend/lookuptool.py: -------------------------------------------------------------------------------- 1 | import csv 2 | from pathlib import Path 3 | from typing import Union 4 | 5 | from langchain.agents import Tool 6 | from langchain.callbacks.manager import Callbacks 7 | 8 | 9 | class CsvLookupTool(Tool): 10 | data: dict[str, str] = {} 11 | 12 | def __init__(self, filename: Union[str, Path], key_field: str, name: str = "lookup", 13 | description: str = "useful to look up details given an input key as opposite to searching data with an unstructured question", 14 | callbacks: Callbacks = None): 15 | super().__init__(name, self.lookup, description, callbacks=callbacks) 16 | with open(filename, newline='') as csvfile: 17 | reader = csv.DictReader(csvfile) 18 | for row in reader: 19 | self.data[row[key_field]] = "\n".join([f"{i}:{row[i]}" for i in row]) 20 | 21 | def lookup(self, key: str) -> str: 22 | return self.data.get(key, "") 23 | -------------------------------------------------------------------------------- /app/backend/main.py: -------------------------------------------------------------------------------- 1 | from app import create_app 2 | 3 | app = create_app() 4 | -------------------------------------------------------------------------------- /app/backend/requirements.txt: -------------------------------------------------------------------------------- 1 | azure-identity==1.13.0 2 | quart==0.19.1 3 | langchain==0.0.187 4 | openai[datalib]==0.27.8 5 | tiktoken==0.4.0 6 | azure-search-documents==11.4.0b6 7 | azure-storage-blob==12.14.1 8 | uvicorn[standard]==0.23.2 -------------------------------------------------------------------------------- /app/backend/swagger.json: -------------------------------------------------------------------------------- 1 | { 2 | "openapi": "3.0.0", 3 | "info": { 4 | "title": "Azure OpenAI Sample API", 5 | "description": "API to interact with chat and question-answering approaches.", 6 | "version": "1.0.0" 7 | }, 8 | "servers": [ 9 | { 10 | "url": "https://app-backend-xxx.azurewebsites.net" 11 | } 12 | ], 13 | "paths": { 14 | "/chat": { 15 | "post": { 16 | "summary": "Chat with the application", 17 | "requestBody": { 18 | "description": "Chat request", 19 | "content": { 20 | "application/json": { 21 | "schema": { 22 | "type": "object", 23 | "properties": { 24 | "approach": { 25 | "type": "string", 26 | "description": "Approach name" 27 | }, 28 | "history": { 29 | "type": "array", 30 | "items": { 31 | "type": "string" 32 | }, 33 | "description": "Chat history" 34 | }, 35 | "overrides": { 36 | "type": "object", 37 | "description": "Overrides" 38 | } 39 | }, 40 | "required": [ 41 | "approach", 42 | "history" 43 | ], 44 | "example": { 45 | "approach": "rrr", 46 | "history": [ 47 | "User: Hi", 48 | "Bot: Hello" 49 | ], 50 | "overrides": {} 51 | } 52 | } 53 | } 54 | } 55 | }, 56 | "responses": { 57 | "200": { 58 | "description": "Successful response", 59 | "content": { 60 | "application/json": { 61 | "schema": { 62 | "type": "object", 63 | "properties": { 64 | "answer": { 65 | "type": "string", 66 | "default": "", 67 | "title": "The answer Schema", 68 | "example": [ 69 | "水素ハイブリッド電車は、水素燃料電池と電気モーターを組み合わせた車両です。" 70 | ] 71 | }, 72 | "data_points": { 73 | "type": "array", 74 | "default": [], 75 | "title": "The data_points Schema", 76 | "items": { 77 | "type": "string", 78 | "default": "", 79 | "title": "A Schema", 80 | "example": [ 81 | "sample-data-1.pdf: 水素ハイブリッド電車は⾧距離の移動需要に対応しやすくなります。" 82 | ] 83 | }, 84 | "example": [ 85 | [ 86 | "sample-data-1.pdf: 水素ハイブリッド電車は⾧距離の移動需要に対応しやすくなります。" 87 | ] 88 | ] 89 | }, 90 | "thoughts": { 91 | "type": "string", 92 | "default": "", 93 | "title": "The thoughts Schema", 94 | "example": [ 95 | "水素ハイブリッド電車とは何ですか" 96 | ] 97 | } 98 | }, 99 | "example": [ 100 | { 101 | "answer": "水素ハイブリッド電車は、水素燃料電池と電気モーターを組み合わせた車両です。", 102 | "data_points": [ 103 | "sample-data-1.pdf: 水素ハイブリッド電車は⾧距離の移動需要に対応しやすくなります。" 104 | ], 105 | "thoughts": "水素ハイブリッド電車とは何ですか" 106 | } 107 | ] 108 | } 109 | } 110 | } 111 | }, 112 | "400": { 113 | "description": "Bad request", 114 | "content": { 115 | "application/json": { 116 | "schema": { 117 | "type": "object", 118 | "properties": { 119 | "error": { 120 | "type": "string", 121 | "description": "Error message" 122 | } 123 | } 124 | }, 125 | "example": { 126 | "error": "unknown approach" 127 | } 128 | } 129 | } 130 | }, 131 | "415": { 132 | "description": "Bad request", 133 | "content": { 134 | "application/json": { 135 | "schema": { 136 | "type": "object", 137 | "properties": { 138 | "error": { 139 | "type": "string", 140 | "description": "Error message" 141 | } 142 | } 143 | }, 144 | "example": { 145 | "error": "Unsupported Media Type" 146 | } 147 | } 148 | } 149 | }, 150 | "500": { 151 | "description": "Internal server error", 152 | "content": { 153 | "application/json": { 154 | "schema": { 155 | "type": "object", 156 | "properties": { 157 | "error": { 158 | "type": "string", 159 | "description": "Error message" 160 | } 161 | } 162 | }, 163 | "example": { 164 | "error": "An internal error occurred." 165 | } 166 | } 167 | } 168 | } 169 | } 170 | } 171 | }, 172 | "/ask": { 173 | "post": { 174 | "summary": "Ask a question to the application", 175 | "requestBody": { 176 | "description": "Question request", 177 | "content": { 178 | "application/json": { 179 | "schema": { 180 | "type": "object", 181 | "properties": { 182 | "approach": { 183 | "type": "string", 184 | "description": "Approach name" 185 | }, 186 | "question": { 187 | "type": "string", 188 | "description": "Question text" 189 | }, 190 | "overrides": { 191 | "type": "object", 192 | "description": "Overrides" 193 | } 194 | }, 195 | "required": [ 196 | "approach", 197 | "question" 198 | ], 199 | "example": { 200 | "approach": "rtr", 201 | "question": "What is the capital of France?", 202 | "overrides": {} 203 | } 204 | } 205 | } 206 | } 207 | }, 208 | "responses": { 209 | "200": { 210 | "description": "Successful response", 211 | "content": { 212 | "application/json": { 213 | "schema": { 214 | "type": "object", 215 | "properties": { 216 | "answer": { 217 | "type": "string", 218 | "default": "", 219 | "title": "The answer Schema", 220 | "example": [ 221 | "水素ハイブリッド電車は、水素燃料電池と電気モーターを組み合わせた車両です。" 222 | ] 223 | }, 224 | "data_points": { 225 | "type": "array", 226 | "default": [], 227 | "title": "The data_points Schema", 228 | "items": { 229 | "type": "string", 230 | "default": "", 231 | "title": "A Schema", 232 | "example": [ 233 | "sample-data-1.pdf: 水素ハイブリッド電車は⾧距離の移動需要に対応しやすくなります。" 234 | ] 235 | }, 236 | "example": [ 237 | [ 238 | "sample-data-1.pdf: 水素ハイブリッド電車は⾧距離の移動需要に対応しやすくなります。" 239 | ] 240 | ] 241 | }, 242 | "thoughts": { 243 | "type": "string", 244 | "default": "", 245 | "title": "The thoughts Schema", 246 | "example": [ 247 | "水素ハイブリッド電車とは何ですか" 248 | ] 249 | } 250 | }, 251 | "example": [ 252 | { 253 | "answer": "水素ハイブリッド電車は、水素燃料電池と電気モーターを組み合わせた車両です。", 254 | "data_points": [ 255 | "sample-data-1.pdf: 水素ハイブリッド電車は⾧距離の移動需要に対応しやすくなります。" 256 | ], 257 | "thoughts": "水素ハイブリッド電車とは何ですか" 258 | } 259 | ] 260 | } 261 | } 262 | } 263 | }, 264 | "400": { 265 | "description": "Bad request", 266 | "content": { 267 | "application/json": { 268 | "schema": { 269 | "type": "object", 270 | "properties": { 271 | "error": { 272 | "type": "string", 273 | "description": "Error message" 274 | } 275 | } 276 | }, 277 | "example": { 278 | "error": "unknown approach" 279 | } 280 | } 281 | } 282 | }, 283 | "415": { 284 | "description": "Bad request", 285 | "content": { 286 | "application/json": { 287 | "schema": { 288 | "type": "object", 289 | "properties": { 290 | "error": { 291 | "type": "string", 292 | "description": "Error message" 293 | } 294 | } 295 | }, 296 | "example": { 297 | "error": "Unsupported Media Type" 298 | } 299 | } 300 | } 301 | }, 302 | "500": { 303 | "description": "Internal server error", 304 | "content": { 305 | "application/json": { 306 | "schema": { 307 | "type": "object", 308 | "properties": { 309 | "error": { 310 | "type": "string", 311 | "description": "Error message" 312 | } 313 | } 314 | }, 315 | "example": { 316 | "error": "An internal error occurred." 317 | } 318 | } 319 | } 320 | } 321 | } 322 | } 323 | } 324 | } 325 | } -------------------------------------------------------------------------------- /app/backend/text.py: -------------------------------------------------------------------------------- 1 | def nonewlines(s: str) -> str: 2 | return s.replace('\n', ' ').replace('\r', ' ') 3 | -------------------------------------------------------------------------------- /app/frontend/.npmrc: -------------------------------------------------------------------------------- 1 | engine-strict=true 2 | -------------------------------------------------------------------------------- /app/frontend/.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "tabWidth": 4, 3 | "printWidth": 160, 4 | "arrowParens": "avoid", 5 | "trailingComma": "none" 6 | } 7 | -------------------------------------------------------------------------------- /app/frontend/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | GPT + Enterprise data | Sample 8 | 9 | 10 |
11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /app/frontend/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "frontend", 3 | "private": true, 4 | "version": "0.0.0", 5 | "type": "module", 6 | "engines": { 7 | "node": ">=14.0.0" 8 | }, 9 | "scripts": { 10 | "dev": "vite", 11 | "build": "tsc && vite build", 12 | "watch": "tsc && vite build --watch" 13 | }, 14 | "dependencies": { 15 | "@fluentui/react": "^8.110.7", 16 | "@fluentui/react-icons": "^2.0.206", 17 | "@react-spring/web": "^9.7.3", 18 | "dompurify": "^3.0.4", 19 | "react": "^18.2.0", 20 | "react-dom": "^18.2.0", 21 | "react-router-dom": "^6.14.1" 22 | }, 23 | "devDependencies": { 24 | "@types/dompurify": "^3.0.2", 25 | "@types/react": "^18.2.14", 26 | "@types/react-dom": "^18.2.6", 27 | "@vitejs/plugin-react": "^4.0.2", 28 | "prettier": "^3.0.0", 29 | "typescript": "^5.1.6", 30 | "vite": "^4.4.2" 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /app/frontend/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asashiho/azure-search-openai-demo/d47885dc3ddbd4c29e89cc08ce0c601f1806429a/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 | retrieval_mode: options.overrides?.retrievalMode, 14 | semantic_ranker: options.overrides?.semanticRanker, 15 | semantic_captions: options.overrides?.semanticCaptions, 16 | top: options.overrides?.top, 17 | temperature: options.overrides?.temperature, 18 | prompt_template: options.overrides?.promptTemplate, 19 | prompt_template_prefix: options.overrides?.promptTemplatePrefix, 20 | prompt_template_suffix: options.overrides?.promptTemplateSuffix, 21 | exclude_category: options.overrides?.excludeCategory 22 | } 23 | }) 24 | }); 25 | 26 | const parsedResponse: AskResponse = await response.json(); 27 | if (response.status > 299 || !response.ok) { 28 | throw Error(parsedResponse.error || "Unknown error"); 29 | } 30 | 31 | return parsedResponse; 32 | } 33 | 34 | export async function chatApi(options: ChatRequest): Promise { 35 | const response = await fetch("/chat", { 36 | method: "POST", 37 | headers: { 38 | "Content-Type": "application/json" 39 | }, 40 | body: JSON.stringify({ 41 | history: options.history, 42 | approach: options.approach, 43 | overrides: { 44 | retrieval_mode: options.overrides?.retrievalMode, 45 | semantic_ranker: options.overrides?.semanticRanker, 46 | semantic_captions: options.overrides?.semanticCaptions, 47 | top: options.overrides?.top, 48 | temperature: options.overrides?.temperature, 49 | prompt_template: options.overrides?.promptTemplate, 50 | prompt_template_prefix: options.overrides?.promptTemplatePrefix, 51 | prompt_template_suffix: options.overrides?.promptTemplateSuffix, 52 | exclude_category: options.overrides?.excludeCategory, 53 | suggest_followup_questions: options.overrides?.suggestFollowupQuestions 54 | } 55 | }) 56 | }); 57 | 58 | const parsedResponse: AskResponse = await response.json(); 59 | if (response.status > 299 || !response.ok) { 60 | throw Error(parsedResponse.error || "Unknown error"); 61 | } 62 | 63 | return parsedResponse; 64 | } 65 | 66 | export function getCitationFilePath(citation: string): string { 67 | return `/content/${citation}`; 68 | } 69 | -------------------------------------------------------------------------------- /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 const enum RetrievalMode { 8 | Hybrid = "hybrid", 9 | Vectors = "vectors", 10 | Text = "text" 11 | } 12 | 13 | export type AskRequestOverrides = { 14 | retrievalMode?: RetrievalMode; 15 | semanticRanker?: boolean; 16 | semanticCaptions?: boolean; 17 | excludeCategory?: string; 18 | top?: number; 19 | temperature?: number; 20 | promptTemplate?: string; 21 | promptTemplatePrefix?: string; 22 | promptTemplateSuffix?: string; 23 | suggestFollowupQuestions?: boolean; 24 | }; 25 | 26 | export type AskRequest = { 27 | question: string; 28 | approach: Approaches; 29 | overrides?: AskRequestOverrides; 30 | }; 31 | 32 | export type AskResponse = { 33 | answer: string; 34 | thoughts: string | null; 35 | data_points: string[]; 36 | error?: string; 37 | }; 38 | 39 | export type ChatTurn = { 40 | user: string; 41 | bot?: string; 42 | }; 43 | 44 | export type ChatRequest = { 45 | history: ChatTurn[]; 46 | approach: Approaches; 47 | overrides?: AskRequestOverrides; 48 | }; 49 | -------------------------------------------------------------------------------- /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 |