├── .devcontainer └── devcontainer.json ├── .gitattributes ├── .github ├── CODE_OF_CONDUCT.md ├── ISSUE_TEMPLATE.md └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── CHANGELOG.md ├── CONTRIBUTING.md ├── ChatApp.AppHost ├── ChatApp.AppHost.csproj ├── Program.cs ├── Properties │ └── launchSettings.json ├── appsettings.Development.json └── appsettings.json ├── ChatApp.React ├── .eslintrc.cjs ├── .gitignore ├── README.md ├── index.html ├── package-lock.json ├── package.json ├── public │ └── icon.svg ├── src │ ├── App.module.css │ ├── App.tsx │ ├── Chat.module.css │ ├── Chat.tsx │ ├── Readme.tsx │ ├── assets │ │ └── caution.svg │ ├── globals.d.ts │ ├── main.tsx │ └── vite-env.d.ts ├── tsconfig.json ├── tsconfig.node.json └── vite.config.ts ├── ChatApp.ServiceDefaults ├── ChatApp.ServiceDefaults.csproj └── Extensions.cs ├── ChatApp.WebApi ├── ChatApp.WebApi.csproj ├── Controllers │ └── ChatController.cs ├── Converters │ └── JsonCamelCaseEnumConverter.cs ├── Interfaces │ ├── ISecretStore.cs │ ├── ISemanticKernelApp.cs │ ├── ISemanticKernelSession.cs │ └── IStateStore.cs ├── Model │ ├── AIChatCompletion.cs │ ├── AIChatCompletionDelta.cs │ ├── AIChatMessage.cs │ ├── AIChatMessageDelta.cs │ ├── AIChatRequest.cs │ └── AIChatRole.cs ├── Program.cs ├── Properties │ └── launchSettings.json ├── Services │ ├── EnvVarSecretStore.cs │ ├── InMemoryStore.cs │ ├── KeyVaultSecretStore.cs │ └── SemanticKernelApp.cs ├── appsettings.Development.json └── appsettings.json ├── ChatApp.sln ├── LICENSE.md └── README.md /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | // For format details, see https://aka.ms/devcontainer.json. For config options, see the 2 | // README at: https://github.com/devcontainers/templates/tree/main/src/dotnet 3 | { 4 | "name": "C# (.NET)", 5 | // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile 6 | "image": "mcr.microsoft.com/devcontainers/dotnet:1-8.0-bookworm", 7 | "features": { 8 | "ghcr.io/devcontainers/features/azure-cli:1": {}, 9 | "ghcr.io/devcontainers/features/node:1": {}, 10 | "ghcr.io/azure/azure-dev/azd:0": {} 11 | } 12 | 13 | // Features to add to the dev container. More info: https://containers.dev/features. 14 | // "features": {}, 15 | 16 | // Use 'forwardPorts' to make a list of ports inside the container available locally. 17 | // "forwardPorts": [5000, 5001], 18 | // "portsAttributes": { 19 | // "5001": { 20 | // "protocol": "https" 21 | // } 22 | // } 23 | 24 | // Use 'postCreateCommand' to run commands after the container is created. 25 | // "postCreateCommand": "dotnet restore", 26 | 27 | // Configure tool-specific properties. 28 | // "customizations": {}, 29 | 30 | // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root. 31 | // "remoteUser": "root" 32 | } 33 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto eol=lf 2 | *.{cmd,[cC][mM][dD]} text eol=crlf 3 | *.{bat,[bB][aA][tT]} text eol=crlf -------------------------------------------------------------------------------- /.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 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # ASP.NET Scaffolding 66 | ScaffoldingReadMe.txt 67 | 68 | # StyleCop 69 | StyleCopReport.xml 70 | 71 | # Files built by Visual Studio 72 | *_i.c 73 | *_p.c 74 | *_h.h 75 | *.ilk 76 | *.meta 77 | *.obj 78 | *.iobj 79 | *.pch 80 | *.pdb 81 | *.ipdb 82 | *.pgc 83 | *.pgd 84 | *.rsp 85 | *.sbr 86 | *.tlb 87 | *.tli 88 | *.tlh 89 | *.tmp 90 | *.tmp_proj 91 | *_wpftmp.csproj 92 | *.log 93 | *.tlog 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio 6 auto-generated project file (contains which files were open etc.) 298 | *.vbp 299 | 300 | # Visual Studio 6 workspace and project file (working project files containing files to include in project) 301 | *.dsw 302 | *.dsp 303 | 304 | # Visual Studio 6 technical files 305 | *.ncb 306 | *.aps 307 | 308 | # Visual Studio LightSwitch build output 309 | **/*.HTMLClient/GeneratedArtifacts 310 | **/*.DesktopClient/GeneratedArtifacts 311 | **/*.DesktopClient/ModelManifest.xml 312 | **/*.Server/GeneratedArtifacts 313 | **/*.Server/ModelManifest.xml 314 | _Pvt_Extensions 315 | 316 | # Paket dependency manager 317 | .paket/paket.exe 318 | paket-files/ 319 | 320 | # FAKE - F# Make 321 | .fake/ 322 | 323 | # CodeRush personal settings 324 | .cr/personal 325 | 326 | # Python Tools for Visual Studio (PTVS) 327 | __pycache__/ 328 | *.pyc 329 | 330 | # Cake - Uncomment if you are using it 331 | # tools/** 332 | # !tools/packages.config 333 | 334 | # Tabs Studio 335 | *.tss 336 | 337 | # Telerik's JustMock configuration file 338 | *.jmconfig 339 | 340 | # BizTalk build output 341 | *.btp.cs 342 | *.btm.cs 343 | *.odx.cs 344 | *.xsd.cs 345 | 346 | # OpenCover UI analysis results 347 | OpenCover/ 348 | 349 | # Azure Stream Analytics local run output 350 | ASALocalRun/ 351 | 352 | # MSBuild Binary and Structured Log 353 | *.binlog 354 | 355 | # NVidia Nsight GPU debugger configuration file 356 | *.nvuser 357 | 358 | # MFractors (Xamarin productivity tool) working folder 359 | .mfractor/ 360 | 361 | # Local History for Visual Studio 362 | .localhistory/ 363 | 364 | # Visual Studio History (VSHistory) files 365 | .vshistory/ 366 | 367 | # BeatPulse healthcheck temp database 368 | healthchecksdb 369 | 370 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 371 | MigrationBackup/ 372 | 373 | # Ionide (cross platform F# VS Code tools) working folder 374 | .ionide/ 375 | 376 | # Fody - auto-generated XML schema 377 | FodyWeavers.xsd 378 | 379 | # VS Code files for those working on multiple tools 380 | .vscode/* 381 | !.vscode/settings.json 382 | !.vscode/tasks.json 383 | !.vscode/launch.json 384 | !.vscode/extensions.json 385 | *.code-workspace 386 | 387 | # Local History for Visual Studio Code 388 | .history/ 389 | 390 | # Windows Installer files from build outputs 391 | *.cab 392 | *.msi 393 | *.msix 394 | *.msm 395 | *.msp 396 | 397 | # JetBrains Rider 398 | *.sln.iml 399 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /ChatApp.AppHost/ChatApp.AppHost.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | true 9 | 7213c4bf-6a44-4714-8cbe-cf7d4dc69e88 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /ChatApp.AppHost/Program.cs: -------------------------------------------------------------------------------- 1 | var builder = DistributedApplication.CreateBuilder(args); 2 | 3 | var useAzureOpenAI = bool.Parse(Environment.GetEnvironmentVariable("UseAzureOpenAI") ?? "true"); 4 | var azureDeployment = Environment.GetEnvironmentVariable("AzureDeployment") ?? "chat"; 5 | var azureEndpoint = Environment.GetEnvironmentVariable("AzureEndpoint"); 6 | 7 | var openAi = builder.AddAzureOpenAI("openAi") 8 | .AddDeployment(new AzureOpenAIDeployment(azureDeployment, "gpt-4o", "2024-05-13")); 9 | 10 | var backend = builder.AddProject("backend") 11 | .WithReference(openAi) 12 | .WithEnvironment("AzureDeployment", azureDeployment) 13 | .WithEnvironment("AzureEndpoint", azureEndpoint); 14 | 15 | var frontend = builder.AddNpmApp("frontend", "../ChatApp.React") 16 | .WithReference(backend) 17 | .WithHttpEndpoint(env: "PORT") 18 | .WithExternalHttpEndpoints() 19 | .PublishAsDockerFile(); 20 | 21 | builder.Build().Run(); 22 | -------------------------------------------------------------------------------- /ChatApp.AppHost/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "profiles": { 4 | "https": { 5 | "commandName": "Project", 6 | "dotnetRunMessages": true, 7 | "launchBrowser": true, 8 | "applicationUrl": "https://localhost:17036;http://localhost:15063", 9 | "environmentVariables": { 10 | "ASPNETCORE_ENVIRONMENT": "Development", 11 | "DOTNET_ENVIRONMENT": "Development", 12 | "DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21115", 13 | "DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22086" 14 | } 15 | }, 16 | "http": { 17 | "commandName": "Project", 18 | "dotnetRunMessages": true, 19 | "launchBrowser": true, 20 | "applicationUrl": "http://localhost:15063", 21 | "environmentVariables": { 22 | "ASPNETCORE_ENVIRONMENT": "Development", 23 | "DOTNET_ENVIRONMENT": "Development", 24 | "DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19277", 25 | "DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20084" 26 | } 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /ChatApp.AppHost/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /ChatApp.AppHost/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning", 6 | "Aspire.Hosting.Dcp": "Warning" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /ChatApp.React/.eslintrc.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | env: { browser: true, es2020: true }, 4 | extends: [ 5 | 'eslint:recommended', 6 | 'plugin:@typescript-eslint/recommended', 7 | 'plugin:react-hooks/recommended', 8 | ], 9 | ignorePatterns: ['dist', '.eslintrc.cjs'], 10 | parser: '@typescript-eslint/parser', 11 | plugins: ['react-refresh'], 12 | rules: { 13 | 'react-refresh/only-export-components': [ 14 | 'warn', 15 | { allowConstantExport: true }, 16 | ], 17 | }, 18 | } 19 | -------------------------------------------------------------------------------- /ChatApp.React/.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | pnpm-debug.log* 8 | lerna-debug.log* 9 | 10 | node_modules 11 | dist 12 | dist-ssr 13 | *.local 14 | 15 | # Editor directories and files 16 | .vscode/* 17 | !.vscode/extensions.json 18 | .idea 19 | .DS_Store 20 | *.suo 21 | *.ntvs* 22 | *.njsproj 23 | *.sln 24 | *.sw? 25 | -------------------------------------------------------------------------------- /ChatApp.React/README.md: -------------------------------------------------------------------------------- 1 | # Aspire Chat App Frontend 2 | 3 | Welcome to the frontend of the Aspire Chat App. This application is built using React and Vite, providing a modern and efficient framework for building user interfaces. 4 | 5 | This application integrates the `@microsoft/ai-chat-protocol` package, which enables seamless communication with our AI chat backend. 6 | 7 | ## Getting Started 8 | 9 | The application uses the `@microsoft/ai-chat-protocol` package to handle chat interactions. This package provides methods for both streaming and non-streaming requests, allowing for flexible communication with the chat backend. 10 | 11 | To interact with the chat: 12 | 13 | 1. Type your prompt into the text box at the bottom of the chat interface. 14 | 2. Press the "Send" button to submit your prompt. 15 | 3. You can toggle between streaming and non-streaming mode using the button at the bottom. 16 | 17 | When developing prompts for the chat, consider the following: 18 | 19 | - Keep prompts concise and clear 20 | - Use user-friendly language 21 | - Consider all possible user responses 22 | - Handle errors and exceptions gracefully 23 | 24 | Please refer to the `@microsoft/ai-chat-protocol` package documentation for more details on how to use these methods. -------------------------------------------------------------------------------- /ChatApp.React/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Chat Protocol Sample 8 | 9 | 10 |
11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /ChatApp.React/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "chat-sample-react", 3 | "private": true, 4 | "version": "0.0.0", 5 | "type": "module", 6 | "scripts": { 7 | "start": "vite", 8 | "dev": "vite --host", 9 | "build": "tsc && vite build", 10 | "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0", 11 | "preview": "vite preview", 12 | "format": "prettier --write src" 13 | }, 14 | "dependencies": { 15 | "@fluentui/react-components": "9.46.8", 16 | "@microsoft/ai-chat-protocol": "^1.0.0-beta.20240610.1", 17 | "react": "^18.2.0", 18 | "react-dom": "^18.2.0", 19 | "react-markdown": "^9.0.1", 20 | "react-syntax-highlighter": "^15.5.0", 21 | "react-textarea-autosize": "^8.5.3", 22 | "remark-gfm": "^4.0.0" 23 | }, 24 | "devDependencies": { 25 | "@types/node": "^20.14.7", 26 | "@types/react": "^18.2.64", 27 | "@types/react-dom": "^18.2.21", 28 | "@types/react-syntax-highlighter": "^15.5.13", 29 | "@typescript-eslint/eslint-plugin": "^7.1.1", 30 | "@typescript-eslint/parser": "^7.1.1", 31 | "@vitejs/plugin-react": "^4.2.1", 32 | "eslint": "^8.57.0", 33 | "eslint-plugin-react-hooks": "^4.6.2", 34 | "eslint-plugin-react-refresh": "^0.4.7", 35 | "prettier": "^3.2.5", 36 | "typescript": "^5.2.2", 37 | "vite": "^5.1.6" 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /ChatApp.React/public/icon.svg: -------------------------------------------------------------------------------- 1 | Icon-166Artboard 1 -------------------------------------------------------------------------------- /ChatApp.React/src/App.module.css: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Microsoft Corporation. 3 | * Licensed under the MIT License. 4 | */ 5 | 6 | html, 7 | body { 8 | margin: 0; 9 | padding: 0; 10 | height: 100%; 11 | } 12 | 13 | .appContainer { 14 | display: flex; 15 | margin: 0; 16 | padding: 0; 17 | height: 100vh; 18 | overflow: auto; 19 | } 20 | -------------------------------------------------------------------------------- /ChatApp.React/src/App.tsx: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | import { FluentProvider, webLightTheme } from "@fluentui/react-components"; 5 | import Chat from "./Chat.tsx"; 6 | import Readme from "./Readme.tsx"; 7 | import styles from "./App.module.css"; 8 | 9 | function App() { 10 | return ( 11 | 12 | process.env.services__backend__https__0 13 |
14 | 15 | 16 |
17 |
18 | ); 19 | } 20 | 21 | export default App; 22 | -------------------------------------------------------------------------------- /ChatApp.React/src/Chat.module.css: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Microsoft Corporation. 3 | * Licensed under the MIT License. 4 | */ 5 | 6 | .chatWindow { 7 | display: flex; 8 | flex-direction: column; 9 | height: 100%; 10 | } 11 | 12 | .messages { 13 | flex-grow: 1; 14 | overflow-y: auto; 15 | padding: 10px; 16 | } 17 | 18 | .userMessage { 19 | display: flex; 20 | justify-content: flex-end; 21 | } 22 | 23 | .assistantMessage { 24 | display: flex; 25 | justify-content: flex-start; 26 | } 27 | 28 | .messageBubble { 29 | max-width: 60%; 30 | margin: 5px; 31 | padding: 10px; 32 | border-radius: 10px; 33 | } 34 | 35 | .userMessage .messageBubble { 36 | background-color: #dcf8c6; 37 | /* light green */ 38 | } 39 | 40 | .assistantMessage .messageBubble { 41 | background-color: #ece5dd; 42 | /* light gray */ 43 | } 44 | 45 | .inputArea { 46 | display: flex; 47 | border-top: 1px solid #ece5dd; 48 | padding: 10px; 49 | flex-shrink: 0; 50 | align-items: flex-end; 51 | } 52 | 53 | .inputArea textarea { 54 | flex-grow: 1; 55 | border: none; 56 | border-radius: 20px; 57 | padding: 10px; 58 | margin-right: 10px; 59 | resize: none; 60 | } 61 | 62 | .inputArea > div { 63 | display: flex; 64 | gap: 10px; 65 | } 66 | 67 | .inputArea button { 68 | margin-right: 10px; 69 | } 70 | 71 | .caution { 72 | padding: 10px 10px 10px 40px; 73 | border: 1px solid #d1d5da; 74 | background-color: #fdd; 75 | background-image: url("./assets/caution.svg"); 76 | background-repeat: no-repeat; 77 | background-position: 10px center; 78 | background-size: 20px; 79 | color: #24292e; 80 | font-weight: 600; 81 | display: flex; 82 | align-items: center; 83 | border-radius: 5px; 84 | width: 80%; 85 | margin-left: auto; 86 | margin-right: auto; 87 | } 88 | 89 | .buttons { 90 | display: flex; 91 | align-items: center; 92 | } 93 | -------------------------------------------------------------------------------- /ChatApp.React/src/Chat.tsx: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | import { Button, ToggleButton } from "@fluentui/react-components"; 5 | import { 6 | AIChatMessage, 7 | AIChatProtocolClient, 8 | AIChatError, 9 | } from "@microsoft/ai-chat-protocol"; 10 | import { useEffect, useId, useRef, useState } from "react"; 11 | import ReactMarkdown from "react-markdown"; 12 | import TextareaAutosize from "react-textarea-autosize"; 13 | import styles from "./Chat.module.css"; 14 | import gfm from "remark-gfm"; 15 | 16 | type ChatEntry = AIChatMessage | AIChatError; 17 | 18 | function isChatError(entry: unknown): entry is AIChatError { 19 | return (entry as AIChatError).code !== undefined; 20 | } 21 | 22 | export default function Chat({ style }: { style: React.CSSProperties }) { 23 | const client = new AIChatProtocolClient("/api/chat/"); 24 | 25 | const [messages, setMessages] = useState([]); 26 | const [input, setInput] = useState(""); 27 | const [streaming, setStreaming] = useState(false); 28 | const inputId = useId(); 29 | const [sessionState, setSessionState] = useState(undefined); 30 | const messagesEndRef = useRef(null); 31 | 32 | const scrollToBottom = () => { 33 | messagesEndRef.current?.scrollIntoView({ behavior: "smooth" }); 34 | }; 35 | useEffect(scrollToBottom, [messages]); 36 | 37 | const sendMessage = async () => { 38 | const message: AIChatMessage = { 39 | role: "user", 40 | content: input, 41 | }; 42 | const updatedMessages = [...messages, message]; 43 | setMessages(updatedMessages); 44 | setInput(""); 45 | try { 46 | if (streaming) { 47 | const result = await client.getStreamedCompletion([message], { 48 | sessionState: sessionState, 49 | }); 50 | const latestMessage: AIChatMessage = { content: "", role: "assistant" }; 51 | for await (const response of result) { 52 | if (response.sessionState) { 53 | setSessionState(response.sessionState); 54 | } 55 | if (!response.delta) { 56 | continue; 57 | } 58 | if (response.delta.role) { 59 | latestMessage.role = response.delta.role; 60 | } 61 | if (response.delta.content) { 62 | latestMessage.content += response.delta.content; 63 | setMessages([...updatedMessages, latestMessage]); 64 | } 65 | } 66 | } else { 67 | const result = await client.getCompletion([message], { 68 | sessionState: sessionState, 69 | }); 70 | setSessionState(result.sessionState); 71 | setMessages([...updatedMessages, result.message]); 72 | } 73 | } catch (e) { 74 | if (isChatError(e)) { 75 | setMessages([...updatedMessages, e]); 76 | } 77 | } 78 | }; 79 | 80 | const getClassName = (message: ChatEntry) => { 81 | if (isChatError(message)) { 82 | return styles.caution; 83 | } 84 | return message.role === "user" 85 | ? styles.userMessage 86 | : styles.assistantMessage; 87 | }; 88 | 89 | const getErrorMessage = (message: AIChatError) => { 90 | return `${message.code}: ${message.message}`; 91 | }; 92 | 93 | return ( 94 |
95 |
96 | {messages.map((message) => ( 97 |
98 | {isChatError(message) ? ( 99 | <>{getErrorMessage(message)} 100 | ) : ( 101 |
102 | 103 | {message.content} 104 | 105 |
106 | )} 107 |
108 | ))} 109 |
110 |
111 |
112 | setInput(e.target.value)} 116 | onKeyDown={(e) => { 117 | if (e.key === "Enter" && e.shiftKey) { 118 | e.preventDefault(); 119 | sendMessage(); 120 | } 121 | }} 122 | minRows={1} 123 | maxRows={4} 124 | /> 125 | 126 | setStreaming(!streaming)} 129 | > 130 | Streaming 131 | 132 |
133 |
134 | ); 135 | } 136 | -------------------------------------------------------------------------------- /ChatApp.React/src/Readme.tsx: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | import React, { useEffect, useState } from "react"; 5 | import ReactMarkdown from "react-markdown"; 6 | import gfm from "remark-gfm"; 7 | import { Prism } from "react-syntax-highlighter"; 8 | import readmeContent from "../README.md"; 9 | 10 | const components = { 11 | code(props: any) { 12 | const { children, className, node, ...rest } = props; 13 | const match = /language-(\w+)/.exec(className || ""); 14 | return match ? ( 15 | 21 | ) : ( 22 | 23 | {children} 24 | 25 | ); 26 | }, 27 | }; 28 | 29 | function Readme({ style }: { style: React.CSSProperties }) { 30 | const [markdown, setMarkdown] = useState(""); 31 | useEffect(() => { 32 | fetch(readmeContent) 33 | .then((response) => response.text()) 34 | .then((text) => setMarkdown(text)); 35 | }, []); 36 | return ( 37 |
38 | 39 | {markdown} 40 | 41 |
42 | ); 43 | } 44 | 45 | export default Readme; 46 | -------------------------------------------------------------------------------- /ChatApp.React/src/assets/caution.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ChatApp.React/src/globals.d.ts: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | declare module "*.md"; 5 | -------------------------------------------------------------------------------- /ChatApp.React/src/main.tsx: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | import React from "react"; 5 | import ReactDOM from "react-dom/client"; 6 | import App from "./App.tsx"; 7 | 8 | ReactDOM.createRoot(document.getElementById("root")!).render( 9 | 10 | 11 | , 12 | ); 13 | -------------------------------------------------------------------------------- /ChatApp.React/src/vite-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | -------------------------------------------------------------------------------- /ChatApp.React/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES2020", 4 | "useDefineForClassFields": true, 5 | "lib": ["ES2020", "DOM", "DOM.Iterable"], 6 | "module": "ESNext", 7 | "skipLibCheck": true, 8 | 9 | /* Bundler mode */ 10 | "moduleResolution": "bundler", 11 | "allowImportingTsExtensions": true, 12 | "resolveJsonModule": true, 13 | "isolatedModules": true, 14 | "noEmit": true, 15 | "jsx": "react-jsx", 16 | 17 | /* Linting */ 18 | "strict": true, 19 | "noUnusedLocals": true, 20 | "noUnusedParameters": true, 21 | "noFallthroughCasesInSwitch": true 22 | }, 23 | "include": ["src"], 24 | "references": [{ "path": "./tsconfig.node.json" }] 25 | } 26 | -------------------------------------------------------------------------------- /ChatApp.React/tsconfig.node.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "composite": true, 4 | "skipLibCheck": true, 5 | "module": "ESNext", 6 | "moduleResolution": "bundler", 7 | "allowSyntheticDefaultImports": true, 8 | "strict": true 9 | }, 10 | "include": ["vite.config.ts"] 11 | } 12 | -------------------------------------------------------------------------------- /ChatApp.React/vite.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'vite'; 2 | import react from '@vitejs/plugin-react'; 3 | 4 | // https://vitejs.dev/config/ 5 | export default defineConfig({ 6 | plugins: [react()], 7 | assetsInclude: ['**/*.md'], 8 | server: { 9 | port: parseInt(process.env.PORT ?? "5173"), 10 | proxy: { 11 | '/api': { 12 | target: 13 | process.env.services__backend__https__0 || 14 | process.env.services__backend__http__0, 15 | changeOrigin: true, 16 | secure: false, 17 | }, 18 | }, 19 | }, 20 | }); 21 | -------------------------------------------------------------------------------- /ChatApp.ServiceDefaults/ChatApp.ServiceDefaults.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | true 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /ChatApp.ServiceDefaults/Extensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.AspNetCore.Diagnostics.HealthChecks; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using Microsoft.Extensions.Diagnostics.HealthChecks; 5 | using Microsoft.Extensions.Logging; 6 | using OpenTelemetry; 7 | using OpenTelemetry.Metrics; 8 | using OpenTelemetry.Trace; 9 | 10 | namespace Microsoft.Extensions.Hosting; 11 | 12 | // Adds common .NET Aspire services: service discovery, resilience, health checks, and OpenTelemetry. 13 | // This project should be referenced by each service project in your solution. 14 | // To learn more about using this project, see https://aka.ms/dotnet/aspire/service-defaults 15 | public static class Extensions 16 | { 17 | public static IHostApplicationBuilder AddServiceDefaults(this IHostApplicationBuilder builder) 18 | { 19 | builder.ConfigureOpenTelemetry(); 20 | 21 | builder.AddDefaultHealthChecks(); 22 | 23 | builder.Services.AddServiceDiscovery(); 24 | 25 | builder.Services.ConfigureHttpClientDefaults(http => 26 | { 27 | // Turn on resilience by default 28 | http.AddStandardResilienceHandler(); 29 | 30 | // Turn on service discovery by default 31 | http.AddServiceDiscovery(); 32 | }); 33 | 34 | return builder; 35 | } 36 | 37 | public static IHostApplicationBuilder ConfigureOpenTelemetry(this IHostApplicationBuilder builder) 38 | { 39 | builder.Logging.AddOpenTelemetry(logging => 40 | { 41 | logging.IncludeFormattedMessage = true; 42 | logging.IncludeScopes = true; 43 | }); 44 | 45 | builder.Services.AddOpenTelemetry() 46 | .WithMetrics(metrics => 47 | { 48 | metrics.AddAspNetCoreInstrumentation() 49 | .AddHttpClientInstrumentation() 50 | .AddRuntimeInstrumentation(); 51 | }) 52 | .WithTracing(tracing => 53 | { 54 | tracing.AddAspNetCoreInstrumentation() 55 | // Uncomment the following line to enable gRPC instrumentation (requires the OpenTelemetry.Instrumentation.GrpcNetClient package) 56 | //.AddGrpcClientInstrumentation() 57 | .AddHttpClientInstrumentation(); 58 | }); 59 | 60 | builder.AddOpenTelemetryExporters(); 61 | 62 | return builder; 63 | } 64 | 65 | private static IHostApplicationBuilder AddOpenTelemetryExporters(this IHostApplicationBuilder builder) 66 | { 67 | var useOtlpExporter = !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]); 68 | 69 | if (useOtlpExporter) 70 | { 71 | builder.Services.AddOpenTelemetry().UseOtlpExporter(); 72 | } 73 | 74 | // Uncomment the following lines to enable the Azure Monitor exporter (requires the Azure.Monitor.OpenTelemetry.AspNetCore package) 75 | //if (!string.IsNullOrEmpty(builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"])) 76 | //{ 77 | // builder.Services.AddOpenTelemetry() 78 | // .UseAzureMonitor(); 79 | //} 80 | 81 | return builder; 82 | } 83 | 84 | public static IHostApplicationBuilder AddDefaultHealthChecks(this IHostApplicationBuilder builder) 85 | { 86 | builder.Services.AddHealthChecks() 87 | // Add a default liveness check to ensure app is responsive 88 | .AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]); 89 | 90 | return builder; 91 | } 92 | 93 | public static WebApplication MapDefaultEndpoints(this WebApplication app) 94 | { 95 | // Adding health checks endpoints to applications in non-development environments has security implications. 96 | // See https://aka.ms/dotnet/aspire/healthchecks for details before enabling these endpoints in non-development environments. 97 | if (app.Environment.IsDevelopment()) 98 | { 99 | // All health checks must pass for app to be considered ready to accept traffic after starting 100 | app.MapHealthChecks("/health"); 101 | 102 | // Only health checks tagged with the "live" tag must pass for app to be considered alive 103 | app.MapHealthChecks("/alive", new HealthCheckOptions 104 | { 105 | Predicate = r => r.Tags.Contains("live") 106 | }); 107 | } 108 | 109 | return app; 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /ChatApp.WebApi/ChatApp.WebApi.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /ChatApp.WebApi/Controllers/ChatController.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | using System.Text.Json; 5 | using Microsoft.AspNetCore.Mvc; 6 | 7 | using ChatApp.WebApi.Interfaces; 8 | using ChatApp.WebApi.Model; 9 | 10 | namespace ChatApp.WebApi.Controllers; 11 | 12 | [ApiController, Route("api/[controller]")] 13 | public class ChatController : ControllerBase 14 | { 15 | private readonly ISemanticKernelApp _semanticKernelApp; 16 | 17 | public ChatController(ISemanticKernelApp semanticKernelApp) 18 | { 19 | _semanticKernelApp = semanticKernelApp; 20 | } 21 | 22 | [HttpPost] 23 | [Consumes("application/json")] 24 | public async Task ProcessMessage(AIChatRequest request) 25 | { 26 | var session = request.SessionState switch 27 | { 28 | Guid sessionId => await _semanticKernelApp.GetSession(sessionId), 29 | _ => await _semanticKernelApp.CreateSession(Guid.NewGuid()) 30 | }; 31 | var response = await session.ProcessRequest(request); 32 | return Ok(response); 33 | } 34 | 35 | [HttpPost("stream")] 36 | [Consumes("application/json")] 37 | public async Task ProcessStreamingMessage(AIChatRequest request) 38 | { 39 | var session = request.SessionState switch 40 | { 41 | Guid sessionId => await _semanticKernelApp.GetSession(sessionId), 42 | _ => await _semanticKernelApp.CreateSession(Guid.NewGuid()) 43 | }; 44 | var response = Response; 45 | response.Headers.Append("Content-Type", "application/x-ndjson"); 46 | await foreach (var delta in session.ProcessStreamingRequest(request)) 47 | { 48 | await response.WriteAsync($"{JsonSerializer.Serialize(delta)}\r\n"); 49 | await response.Body.FlushAsync(); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /ChatApp.WebApi/Converters/JsonCamelCaseEnumConverter.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | using System.Text.Json; 5 | using System.Text.Json.Serialization; 6 | 7 | namespace ChatApp.WebApi.Converters; 8 | 9 | public class JsonCamelCaseEnumConverter : JsonStringEnumConverter where T : struct, Enum 10 | { 11 | public JsonCamelCaseEnumConverter() : base(JsonNamingPolicy.CamelCase) 12 | { 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /ChatApp.WebApi/Interfaces/ISecretStore.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | namespace ChatApp.WebApi.Interfaces; 5 | 6 | public interface ISecretStore 7 | { 8 | Task GetSecretAsync(string secretName, CancellationToken cancellationToken = default); 9 | } 10 | -------------------------------------------------------------------------------- /ChatApp.WebApi/Interfaces/ISemanticKernelApp.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | namespace ChatApp.WebApi.Interfaces; 5 | 6 | public interface ISemanticKernelApp 7 | { 8 | Task CreateSession(Guid sessionId); 9 | Task GetSession(Guid sessionId); 10 | } 11 | -------------------------------------------------------------------------------- /ChatApp.WebApi/Interfaces/ISemanticKernelSession.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | using ChatApp.WebApi.Model; 5 | 6 | namespace ChatApp.WebApi.Interfaces; 7 | public interface ISemanticKernelSession 8 | { 9 | Guid Id { get; } 10 | Task ProcessRequest(AIChatRequest request); 11 | IAsyncEnumerable ProcessStreamingRequest(AIChatRequest request); 12 | } 13 | -------------------------------------------------------------------------------- /ChatApp.WebApi/Interfaces/IStateStore.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | namespace ChatApp.WebApi.Interfaces; 5 | 6 | public interface IStateStore 7 | { 8 | Task GetStateAsync(Guid sessionId); 9 | Task SetStateAsync(Guid sessionId, T state); 10 | Task RemoveStateAsync(Guid sessionId); 11 | } 12 | -------------------------------------------------------------------------------- /ChatApp.WebApi/Model/AIChatCompletion.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | using System.Text.Json.Serialization; 5 | 6 | namespace ChatApp.WebApi.Model; 7 | 8 | public record AIChatCompletion([property: JsonPropertyName("message")] AIChatMessage Message) 9 | { 10 | [JsonInclude, JsonPropertyName("sessionState"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] 11 | public Guid? SessionState; 12 | 13 | [JsonInclude, JsonPropertyName("context"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] 14 | public BinaryData? Context; 15 | } 16 | -------------------------------------------------------------------------------- /ChatApp.WebApi/Model/AIChatCompletionDelta.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | using System.Text.Json.Serialization; 5 | 6 | namespace ChatApp.WebApi.Model; 7 | 8 | public record AIChatCompletionDelta([property: JsonPropertyName("delta")] AIChatMessageDelta Delta) 9 | { 10 | [JsonInclude, JsonPropertyName("sessionState"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] 11 | public Guid? SessionState; 12 | 13 | [JsonInclude, JsonPropertyName("context"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] 14 | public BinaryData? Context; 15 | } 16 | -------------------------------------------------------------------------------- /ChatApp.WebApi/Model/AIChatMessage.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | using System.Text.Json.Serialization; 5 | 6 | namespace ChatApp.WebApi.Model; 7 | 8 | public struct AIChatMessage 9 | { 10 | [JsonPropertyName("content")] 11 | public string Content { get; set; } 12 | 13 | [JsonPropertyName("role")] 14 | public AIChatRole Role { get; set; } 15 | 16 | [JsonPropertyName("context")] 17 | public BinaryData? Context { get; set; } 18 | } 19 | 20 | -------------------------------------------------------------------------------- /ChatApp.WebApi/Model/AIChatMessageDelta.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | using System.Text.Json.Serialization; 5 | 6 | namespace ChatApp.WebApi.Model; 7 | 8 | public struct AIChatMessageDelta 9 | { 10 | [JsonPropertyName("content")] 11 | public string? Content { get; set; } 12 | 13 | [JsonPropertyName("role")] 14 | public AIChatRole? Role { get; set; } 15 | 16 | [JsonPropertyName("context"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] 17 | public BinaryData? Context { get; set; } 18 | } 19 | -------------------------------------------------------------------------------- /ChatApp.WebApi/Model/AIChatRequest.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | using System.Text.Json.Serialization; 5 | 6 | namespace ChatApp.WebApi.Model; 7 | 8 | public record AIChatRequest([property: JsonPropertyName("messages")] IList Messages) 9 | { 10 | [JsonInclude, JsonPropertyName("sessionState")] 11 | public Guid? SessionState; 12 | 13 | [JsonInclude, JsonPropertyName("context")] 14 | public BinaryData? Context; 15 | } 16 | -------------------------------------------------------------------------------- /ChatApp.WebApi/Model/AIChatRole.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | using System.Text.Json.Serialization; 5 | 6 | using ChatApp.WebApi.Converters; 7 | 8 | namespace ChatApp.WebApi.Model; 9 | 10 | [JsonConverter(typeof(JsonCamelCaseEnumConverter))] 11 | public enum AIChatRole 12 | { 13 | System, 14 | Assistant, 15 | User 16 | } 17 | -------------------------------------------------------------------------------- /ChatApp.WebApi/Program.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | using System.Text.Json; 5 | using System.Text.Json.Serialization; 6 | 7 | using ChatApp.WebApi.Interfaces; 8 | using ChatApp.WebApi.Model; 9 | using ChatApp.WebApi.Services; 10 | 11 | var builder = WebApplication.CreateBuilder(args); 12 | 13 | builder.AddServiceDefaults(); 14 | 15 | builder.AddAzureOpenAIClient("openAi"); 16 | 17 | builder.Services.AddSingleton>(new InMemoryStore()); 18 | builder.Services.AddSingleton(new EnvVarSecretStore()); 19 | builder.Services.AddSingleton(); 20 | 21 | builder.Services 22 | .AddControllers() 23 | .AddJsonOptions(o => o.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase))); 24 | 25 | var app = builder.Build(); 26 | 27 | app.MapDefaultEndpoints(); 28 | 29 | // Configure the HTTP request pipeline. 30 | if (!app.Environment.IsDevelopment()) 31 | { 32 | app.UseExceptionHandler("/Error"); 33 | // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. 34 | app.UseHsts(); 35 | app.UseHttpsRedirection(); 36 | } 37 | 38 | app.UseStaticFiles(); 39 | 40 | app.UseRouting(); 41 | 42 | app.UseAuthorization(); 43 | 44 | app.MapControllers(); 45 | 46 | app.Run(); 47 | -------------------------------------------------------------------------------- /ChatApp.WebApi/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:21376", 8 | "sslPort": 44324 9 | } 10 | }, 11 | "profiles": { 12 | "http": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "applicationUrl": "http://localhost:3000", 17 | "environmentVariables": { 18 | "ASPNETCORE_ENVIRONMENT": "Development" 19 | } 20 | }, 21 | "https": { 22 | "commandName": "Project", 23 | "dotnetRunMessages": true, 24 | "launchBrowser": true, 25 | "applicationUrl": "https://localhost:7281;http://localhost:5094", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | }, 30 | "IIS Express": { 31 | "commandName": "IISExpress", 32 | "launchBrowser": true, 33 | "environmentVariables": { 34 | "ASPNETCORE_ENVIRONMENT": "Development" 35 | } 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /ChatApp.WebApi/Services/EnvVarSecretStore.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | using ChatApp.WebApi.Interfaces; 5 | 6 | namespace ChatApp.WebApi.Services; 7 | 8 | public class EnvVarSecretStore : ISecretStore 9 | { 10 | public Task GetSecretAsync(string secretName, CancellationToken cancellationToken) 11 | { 12 | #if !DEBUG 13 | throw new ApplicationException("EnvVarSecretStore should not be used in production."); 14 | #else 15 | return Task.FromResult(Environment.GetEnvironmentVariable(secretName) ?? ""); 16 | #endif 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /ChatApp.WebApi/Services/InMemoryStore.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | using ChatApp.WebApi.Interfaces; 5 | 6 | public class InMemoryStore : IStateStore 7 | { 8 | private readonly Dictionary _store = new Dictionary(); 9 | 10 | public Task GetStateAsync(Guid sessionId) 11 | { 12 | _store.TryGetValue(sessionId, out var state); 13 | return Task.FromResult(state); 14 | } 15 | 16 | public Task SetStateAsync(Guid sessionId, T state) 17 | { 18 | _store[sessionId] = state; 19 | return Task.CompletedTask; 20 | } 21 | 22 | public Task RemoveStateAsync(Guid sessionId) 23 | { 24 | _store.Remove(sessionId); 25 | return Task.CompletedTask; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /ChatApp.WebApi/Services/KeyVaultSecretStore.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | using Azure.Security.KeyVault.Secrets; 5 | 6 | using ChatApp.WebApi.Interfaces; 7 | 8 | namespace ChatApp.WebApi.Services; 9 | 10 | public class KeyVaultSecretStore : ISecretStore 11 | { 12 | private readonly SecretClient _secretClient; 13 | 14 | public KeyVaultSecretStore(SecretClient secretClient) 15 | { 16 | _secretClient = secretClient; 17 | } 18 | 19 | public async Task GetSecretAsync(string secretName, CancellationToken cancellationToken) 20 | { 21 | KeyVaultSecret secret = await _secretClient.GetSecretAsync(secretName, cancellationToken: cancellationToken); 22 | return secret.Value; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /ChatApp.WebApi/Services/SemanticKernelApp.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | using System.Text; 5 | using Azure.Identity; 6 | using Microsoft.SemanticKernel; 7 | 8 | using ChatApp.WebApi.Interfaces; 9 | using ChatApp.WebApi.Model; 10 | using Azure.AI.OpenAI; 11 | 12 | namespace ChatApp.WebApi.Services; 13 | 14 | internal record AzureOpenAIConfig(string Deployment, string Endpoint); 15 | 16 | internal struct SemanticKernelConfig 17 | { 18 | internal AzureOpenAIConfig AzureOpenAIConfig { get; private init; } 19 | 20 | internal static async Task CreateAsync(ISecretStore secretStore, CancellationToken cancellationToken) 21 | { 22 | var azureDeployment = await secretStore.GetSecretAsync("AzureDeployment", cancellationToken); 23 | var azureEndpoint = await secretStore.GetSecretAsync("AzureEndpoint", cancellationToken); 24 | 25 | return new SemanticKernelConfig 26 | { 27 | AzureOpenAIConfig = new AzureOpenAIConfig(azureDeployment, azureEndpoint), 28 | }; 29 | } 30 | } 31 | 32 | internal class SemanticKernelSession : ISemanticKernelSession 33 | { 34 | private readonly Kernel _kernel; 35 | private readonly IStateStore _stateStore; 36 | 37 | public Guid Id { get; private set; } 38 | 39 | internal SemanticKernelSession(Kernel kernel, IStateStore stateStore, Guid sessionId) 40 | { 41 | _kernel = kernel; 42 | _stateStore = stateStore; 43 | Id = sessionId; 44 | } 45 | 46 | const string prompt = @" 47 | ChatBot can have a conversation with you about any topic. 48 | It can give explicit instructions or say 'I don't know' if it does not know the answer. 49 | 50 | {{$history}} 51 | User: {{$userInput}} 52 | ChatBot:"; 53 | 54 | public async Task ProcessRequest(AIChatRequest message) 55 | { 56 | var chatFunction = _kernel.CreateFunctionFromPrompt(prompt); 57 | var userInput = message.Messages.Last(); 58 | string history = await _stateStore.GetStateAsync(Id) ?? ""; 59 | var arguments = new KernelArguments() 60 | { 61 | ["history"] = history, 62 | ["userInput"] = userInput.Content, 63 | }; 64 | var botResponse = await chatFunction.InvokeAsync(_kernel, arguments); 65 | var updatedHistory = $"{history}\nUser: {userInput.Content}\nChatBot: {botResponse}"; 66 | await _stateStore.SetStateAsync(Id, updatedHistory); 67 | return new AIChatCompletion(Message: new AIChatMessage 68 | { 69 | Role = AIChatRole.Assistant, 70 | Content = $"{botResponse}", 71 | }) 72 | { 73 | SessionState = Id, 74 | }; 75 | } 76 | 77 | public async IAsyncEnumerable ProcessStreamingRequest(AIChatRequest message) 78 | { 79 | var chatFunction = _kernel.CreateFunctionFromPrompt(prompt); 80 | var userInput = message.Messages.Last(); 81 | string history = await _stateStore.GetStateAsync(Id) ?? ""; 82 | var arguments = new KernelArguments() 83 | { 84 | ["history"] = history, 85 | ["userInput"] = userInput.Content, 86 | }; 87 | var streamedBotResponse = chatFunction.InvokeStreamingAsync(_kernel, arguments); 88 | StringBuilder response = new(); 89 | await foreach (var botResponse in streamedBotResponse) 90 | { 91 | response.Append(botResponse); 92 | yield return new AIChatCompletionDelta(Delta: new AIChatMessageDelta 93 | { 94 | Role = AIChatRole.Assistant, 95 | Content = $"{botResponse}", 96 | }) 97 | { 98 | SessionState = Id, 99 | }; 100 | } 101 | var updatedHistory = $"{history}\nUser: {userInput.Content}\nChatBot: {response}"; 102 | await _stateStore.SetStateAsync(Id, updatedHistory); 103 | } 104 | 105 | } 106 | 107 | public class SemanticKernelApp : ISemanticKernelApp 108 | { 109 | private readonly ISecretStore _secretStore; 110 | private readonly IStateStore _stateStore; 111 | private readonly Lazy> _kernel; 112 | private readonly OpenAIClient _openAIClient; 113 | private async Task InitKernel() 114 | { 115 | var config = await SemanticKernelConfig.CreateAsync(_secretStore, CancellationToken.None); 116 | var builder = Kernel.CreateBuilder(); 117 | if (config.AzureOpenAIConfig is AzureOpenAIConfig azureOpenAIConfig) 118 | { 119 | if (azureOpenAIConfig.Deployment is null || azureOpenAIConfig.Endpoint is null) 120 | { 121 | throw new InvalidOperationException("AzureOpenAI is enabled but AzureDeployment and AzureEndpoint are not set."); 122 | } 123 | builder.AddAzureOpenAIChatCompletion(azureOpenAIConfig.Deployment, _openAIClient); 124 | } 125 | return builder.Build(); 126 | } 127 | 128 | public SemanticKernelApp(ISecretStore secretStore, IStateStore stateStore, OpenAIClient openAIClient) 129 | { 130 | _secretStore = secretStore; 131 | _stateStore = stateStore; 132 | _openAIClient = openAIClient; 133 | _kernel = new(() => Task.Run(InitKernel)); 134 | } 135 | 136 | public async Task CreateSession(Guid sessionId) 137 | { 138 | var kernel = await _kernel.Value; 139 | return new SemanticKernelSession(kernel, _stateStore, sessionId); 140 | } 141 | 142 | public async Task GetSession(Guid sessionId) 143 | { 144 | var kernel = await _kernel.Value; 145 | var state = await _stateStore.GetStateAsync(sessionId); 146 | if (state is null) 147 | { 148 | throw new KeyNotFoundException($"Session {sessionId} not found."); 149 | } 150 | return new SemanticKernelSession(kernel, _stateStore, sessionId); 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /ChatApp.WebApi/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "DetailedErrors": true, 3 | "Logging": { 4 | "LogLevel": { 5 | "Default": "Information", 6 | "Microsoft.AspNetCore": "Warning" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /ChatApp.WebApi/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /ChatApp.sln: -------------------------------------------------------------------------------- 1 | Microsoft Visual Studio Solution File, Format Version 12.00 2 | # Visual Studio Version 17 3 | VisualStudioVersion = 17.10.35013.160 4 | MinimumVisualStudioVersion = 10.0.40219.1 5 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ChatApp.AppHost", "ChatApp.AppHost\ChatApp.AppHost.csproj", "{2E8C655A-0094-45A8-A21E-62CE8D763A12}" 6 | EndProject 7 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ChatApp.ServiceDefaults", "ChatApp.ServiceDefaults\ChatApp.ServiceDefaults.csproj", "{40B95131-B4D5-4A17-8AF9-8C23EBB6EFFB}" 8 | EndProject 9 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ChatApp.WebApi", "ChatApp.WebApi\ChatApp.WebApi.csproj", "{0E7A4CA7-2BB1-434D-A34C-1B772055BF81}" 10 | EndProject 11 | Global 12 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 13 | Debug|Any CPU = Debug|Any CPU 14 | Release|Any CPU = Release|Any CPU 15 | EndGlobalSection 16 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 17 | {2E8C655A-0094-45A8-A21E-62CE8D763A12}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 18 | {2E8C655A-0094-45A8-A21E-62CE8D763A12}.Debug|Any CPU.Build.0 = Debug|Any CPU 19 | {2E8C655A-0094-45A8-A21E-62CE8D763A12}.Release|Any CPU.ActiveCfg = Release|Any CPU 20 | {2E8C655A-0094-45A8-A21E-62CE8D763A12}.Release|Any CPU.Build.0 = Release|Any CPU 21 | {40B95131-B4D5-4A17-8AF9-8C23EBB6EFFB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 22 | {40B95131-B4D5-4A17-8AF9-8C23EBB6EFFB}.Debug|Any CPU.Build.0 = Debug|Any CPU 23 | {40B95131-B4D5-4A17-8AF9-8C23EBB6EFFB}.Release|Any CPU.ActiveCfg = Release|Any CPU 24 | {40B95131-B4D5-4A17-8AF9-8C23EBB6EFFB}.Release|Any CPU.Build.0 = Release|Any CPU 25 | {0E7A4CA7-2BB1-434D-A34C-1B772055BF81}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 26 | {0E7A4CA7-2BB1-434D-A34C-1B772055BF81}.Debug|Any CPU.Build.0 = Debug|Any CPU 27 | {0E7A4CA7-2BB1-434D-A34C-1B772055BF81}.Release|Any CPU.ActiveCfg = Release|Any CPU 28 | {0E7A4CA7-2BB1-434D-A34C-1B772055BF81}.Release|Any CPU.Build.0 = Release|Any CPU 29 | EndGlobalSection 30 | GlobalSection(SolutionProperties) = preSolution 31 | HideSolutionNode = FALSE 32 | EndGlobalSection 33 | GlobalSection(ExtensibilityGlobals) = postSolution 34 | SolutionGuid = {7C732D01-B834-4772-9C13-0EA9EA0BD9DB} 35 | EndGlobalSection 36 | EndGlobal 37 | -------------------------------------------------------------------------------- /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 | # Aspire Sample Application 2 | 3 | Welcome to the Aspire Sample Application. This project is a comprehensive example of a chat application built with .NET Aspire, Semantic Kernel, and the `@microsoft/ai-chat-protocol` package. The frontend of the application is developed using React and Vite. 4 | 5 | ## Overview 6 | 7 | The application consists of 2 main Projects: 8 | 9 | - `ChatApp.WebApi`: This is a .NET Web API that handles chat interactions, powered by .NET Aspire and Semantic Kernel. It provides endpoints for the chat frontend to communicate with the chat backend. The `@microsoft/ai-chat-protocol` package is used to handle chat interactions, including streaming and non-streaming requests. 10 | 11 | - `ChatApp.React`: This is a React app that provides the user interface for the chat application. It is built using Vite, a modern and efficient build tool. It uses the `@microsoft/ai-chat-protocol` package to handle chat interactions, allowing for flexible communication with the chat backend. 12 | 13 | The app also includes a class library project, ChatApp.ServiceDefaults, that contains the service defaults used by the service projects. 14 | 15 | ## Pre-requisites 16 | 17 | - .NET 8 SDK 18 | - Optional Visual Studio 2022 17.10 19 | - Node.js 20 20 | 21 | ## Running the app 22 | 23 | If using Visual Studio, open the solution file ChatApp.sln and launch/debug the ChatApp.AppHost project. 24 | 25 | If using the .NET CLI, run dotnet run from the ChatApp.AppHost directory. 26 | 27 | For more information on local provisioning of Aspire applications, refer to the [Aspire Local Provisioning Guide](https://learn.microsoft.com/en-us/dotnet/aspire/deployment/azure/local-provisioning). 28 | 29 | 30 | ## Resources 31 | 32 | - [Aspire Documentation](https://learn.microsoft.com/en-us/dotnet/aspire/) 33 | - [Semantic Kernel Documentation](https://learn.microsoft.com/en-us/dotnet/aspire/semantic-kernel/) 34 | - [Chat Protocol Documentation](https://learn.microsoft.com/en-us/dotnet/aspire/ai-chat-protocol/) 35 | 36 | ## License 37 | 38 | This project is licensed under the terms of the MIT license. See the `LICENSE` file for the full license text. --------------------------------------------------------------------------------