sample main code added (WIP readme file)

This commit is contained in:
“luismanez” 2024-01-02 22:11:30 +01:00
parent d817730c69
commit 8ed37aaa6f
37 changed files with 32767 additions and 0 deletions

View File

@ -0,0 +1,352 @@
require('@rushstack/eslint-config/patch/modern-module-resolution');
module.exports = {
extends: ['@microsoft/eslint-config-spfx/lib/profiles/react'],
parserOptions: { tsconfigRootDir: __dirname },
overrides: [
{
files: ['*.ts', '*.tsx'],
parser: '@typescript-eslint/parser',
'parserOptions': {
'project': './tsconfig.json',
'ecmaVersion': 2018,
'sourceType': 'module'
},
rules: {
// Prevent usage of the JavaScript null value, while allowing code to access existing APIs that may require null. https://www.npmjs.com/package/@rushstack/eslint-plugin
'@rushstack/no-new-null': 1,
// Require Jest module mocking APIs to be called before any other statements in their code block. https://www.npmjs.com/package/@rushstack/eslint-plugin
'@rushstack/hoist-jest-mock': 1,
// Require regular expressions to be constructed from string constants rather than dynamically building strings at runtime. https://www.npmjs.com/package/@rushstack/eslint-plugin-security
'@rushstack/security/no-unsafe-regexp': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/adjacent-overload-signatures': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
//
// CONFIGURATION: By default, these are banned: String, Boolean, Number, Object, Symbol
'@typescript-eslint/ban-types': [
1,
{
'extendDefaults': false,
'types': {
'String': {
'message': 'Use \'string\' instead',
'fixWith': 'string'
},
'Boolean': {
'message': 'Use \'boolean\' instead',
'fixWith': 'boolean'
},
'Number': {
'message': 'Use \'number\' instead',
'fixWith': 'number'
},
'Object': {
'message': 'Use \'object\' instead, or else define a proper TypeScript type:'
},
'Symbol': {
'message': 'Use \'symbol\' instead',
'fixWith': 'symbol'
},
'Function': {
'message': 'The \'Function\' type accepts any function-like value.\nIt provides no type safety when calling the function, which can be a common source of bugs.\nIt also accepts things like class declarations, which will throw at runtime as they will not be called with \'new\'.\nIf you are expecting the function to accept certain arguments, you should explicitly define the function shape.'
}
}
}
],
// RATIONALE: Code is more readable when the type of every variable is immediately obvious.
// Even if the compiler may be able to infer a type, this inference will be unavailable
// to a person who is reviewing a GitHub diff. This rule makes writing code harder,
// but writing code is a much less important activity than reading it.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/explicit-function-return-type': [
1,
{
'allowExpressions': true,
'allowTypedFunctionExpressions': true,
'allowHigherOrderFunctions': false
}
],
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Rationale to disable: although this is a recommended rule, it is up to dev to select coding style.
// Set to 1 (warning) or 2 (error) to enable.
'@typescript-eslint/explicit-member-accessibility': 0,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-array-constructor': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
//
// RATIONALE: The "any" keyword disables static type checking, the main benefit of using TypeScript.
// This rule should be suppressed only in very special cases such as JSON.stringify()
// where the type really can be anything. Even if the type is flexible, another type
// may be more appropriate such as "unknown", "{}", or "Record<k,V>".
'@typescript-eslint/no-explicit-any': 1,
// RATIONALE: The #1 rule of promises is that every promise chain must be terminated by a catch()
// handler. Thus wherever a Promise arises, the code must either append a catch handler,
// or else return the object to a caller (who assumes this responsibility). Unterminated
// promise chains are a serious issue. Besides causing errors to be silently ignored,
// they can also cause a NodeJS process to terminate unexpectedly.
'@typescript-eslint/no-floating-promises': 2,
// RATIONALE: Catches a common coding mistake.
'@typescript-eslint/no-for-in-array': 2,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-misused-new': 2,
// RATIONALE: The "namespace" keyword is not recommended for organizing code because JavaScript lacks
// a "using" statement to traverse namespaces. Nested namespaces prevent certain bundler
// optimizations. If you are declaring loose functions/variables, it's better to make them
// static members of a class, since classes support property getters and their private
// members are accessible by unit tests. Also, the exercise of choosing a meaningful
// class name tends to produce more discoverable APIs: for example, search+replacing
// the function "reverse()" is likely to return many false matches, whereas if we always
// write "Text.reverse()" is more unique. For large scale organization, it's recommended
// to decompose your code into separate NPM packages, which ensures that component
// dependencies are tracked more conscientiously.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-namespace': [
1,
{
'allowDeclarations': false,
'allowDefinitionFiles': false
}
],
// RATIONALE: Parameter properties provide a shorthand such as "constructor(public title: string)"
// that avoids the effort of declaring "title" as a field. This TypeScript feature makes
// code easier to write, but arguably sacrifices readability: In the notes for
// "@typescript-eslint/member-ordering" we pointed out that fields are central to
// a class's design, so we wouldn't want to bury them in a constructor signature
// just to save some typing.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Set to 1 (warning) or 2 (error) to enable the rule
'@typescript-eslint/parameter-properties': 0,
// RATIONALE: When left in shipping code, unused variables often indicate a mistake. Dead code
// may impact performance.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-unused-vars': [
1,
{
'vars': 'all',
// Unused function arguments often indicate a mistake in JavaScript code. However in TypeScript code,
// the compiler catches most of those mistakes, and unused arguments are fairly common for type signatures
// that are overriding a base class method or implementing an interface.
'args': 'none'
}
],
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-use-before-define': [
2,
{
'functions': false,
'classes': true,
'variables': true,
'enums': true,
'typedefs': true
}
],
// Disallows require statements except in import statements.
// In other words, the use of forms such as var foo = require("foo") are banned. Instead use ES6 style imports or import foo = require("foo") imports.
'@typescript-eslint/no-var-requires': 'error',
// RATIONALE: The "module" keyword is deprecated except when describing legacy libraries.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/prefer-namespace-keyword': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Rationale to disable: it's up to developer to decide if he wants to add type annotations
// Set to 1 (warning) or 2 (error) to enable the rule
'@typescript-eslint/no-inferrable-types': 0,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Rationale to disable: declaration of empty interfaces may be helpful for generic types scenarios
'@typescript-eslint/no-empty-interface': 0,
// RATIONALE: This rule warns if setters are defined without getters, which is probably a mistake.
'accessor-pairs': 1,
// RATIONALE: In TypeScript, if you write x["y"] instead of x.y, it disables type checking.
'dot-notation': [
1,
{
'allowPattern': '^_'
}
],
// RATIONALE: Catches code that is likely to be incorrect
'eqeqeq': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'for-direction': 1,
// RATIONALE: Catches a common coding mistake.
'guard-for-in': 2,
// RATIONALE: If you have more than 2,000 lines in a single source file, it's probably time
// to split up your code.
'max-lines': ['warn', { max: 2000 }],
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-async-promise-executor': 2,
// RATIONALE: Deprecated language feature.
'no-caller': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-compare-neg-zero': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-cond-assign': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-constant-condition': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-control-regex': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-debugger': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-delete-var': 2,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-duplicate-case': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-empty': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-empty-character-class': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-empty-pattern': 1,
// RATIONALE: Eval is a security concern and a performance concern.
'no-eval': 1,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-ex-assign': 2,
// RATIONALE: System types are global and should not be tampered with in a scalable code base.
// If two different libraries (or two versions of the same library) both try to modify
// a type, only one of them can win. Polyfills are acceptable because they implement
// a standardized interoperable contract, but polyfills are generally coded in plain
// JavaScript.
'no-extend-native': 1,
// Disallow unnecessary labels
'no-extra-label': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-fallthrough': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-func-assign': 1,
// RATIONALE: Catches a common coding mistake.
'no-implied-eval': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-invalid-regexp': 2,
// RATIONALE: Catches a common coding mistake.
'no-label-var': 2,
// RATIONALE: Eliminates redundant code.
'no-lone-blocks': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-misleading-character-class': 2,
// RATIONALE: Catches a common coding mistake.
'no-multi-str': 2,
// RATIONALE: It's generally a bad practice to call "new Thing()" without assigning the result to
// a variable. Either it's part of an awkward expression like "(new Thing()).doSomething()",
// or else implies that the constructor is doing nontrivial computations, which is often
// a poor class design.
'no-new': 1,
// RATIONALE: Obsolete language feature that is deprecated.
'no-new-func': 2,
// RATIONALE: Obsolete language feature that is deprecated.
'no-new-object': 2,
// RATIONALE: Obsolete notation.
'no-new-wrappers': 1,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-octal': 2,
// RATIONALE: Catches code that is likely to be incorrect
'no-octal-escape': 2,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-regex-spaces': 2,
// RATIONALE: Catches a common coding mistake.
'no-return-assign': 2,
// RATIONALE: Security risk.
'no-script-url': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-self-assign': 2,
// RATIONALE: Catches a common coding mistake.
'no-self-compare': 2,
// RATIONALE: This avoids statements such as "while (a = next(), a && a.length);" that use
// commas to create compound expressions. In general code is more readable if each
// step is split onto a separate line. This also makes it easier to set breakpoints
// in the debugger.
'no-sequences': 1,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-shadow-restricted-names': 2,
// RATIONALE: Obsolete language feature that is deprecated.
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-sparse-arrays': 2,
// RATIONALE: Although in theory JavaScript allows any possible data type to be thrown as an exception,
// such flexibility adds pointless complexity, by requiring every catch block to test
// the type of the object that it receives. Whereas if catch blocks can always assume
// that their object implements the "Error" contract, then the code is simpler, and
// we generally get useful additional information like a call stack.
'no-throw-literal': 2,
// RATIONALE: Catches a common coding mistake.
'no-unmodified-loop-condition': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-unsafe-finally': 2,
// RATIONALE: Catches a common coding mistake.
'no-unused-expressions': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-unused-labels': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-useless-catch': 1,
// RATIONALE: Avoids a potential performance problem.
'no-useless-concat': 1,
// RATIONALE: The "var" keyword is deprecated because of its confusing "hoisting" behavior.
// Always use "let" or "const" instead.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'no-var': 2,
// RATIONALE: Generally not needed in modern code.
'no-void': 1,
// RATIONALE: Obsolete language feature that is deprecated.
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-with': 2,
// RATIONALE: Makes logic easier to understand, since constants always have a known value
// @typescript-eslint\eslint-plugin\dist\configs\eslint-recommended.js
'prefer-const': 1,
// RATIONALE: Catches a common coding mistake where "resolve" and "reject" are confused.
'promise/param-names': 2,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'require-atomic-updates': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'require-yield': 1,
// "Use strict" is redundant when using the TypeScript compiler.
'strict': [
2,
'never'
],
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'use-isnan': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
// Set to 1 (warning) or 2 (error) to enable.
// Rationale to disable: !!{}
'no-extra-boolean-cast': 0,
// ====================================================================
// @microsoft/eslint-plugin-spfx
// ====================================================================
'@microsoft/spfx/import-requires-chunk-name': 1,
'@microsoft/spfx/no-require-ensure': 2,
'@microsoft/spfx/pair-react-dom-render-unmount': 1
}
},
{
// For unit tests, we can be a little bit less strict. The settings below revise the
// defaults specified in the extended configurations, as well as above.
files: [
// Test files
'*.test.ts',
'*.test.tsx',
'*.spec.ts',
'*.spec.tsx',
// Facebook convention
'**/__mocks__/*.ts',
'**/__mocks__/*.tsx',
'**/__tests__/*.ts',
'**/__tests__/*.tsx',
// Microsoft convention
'**/test/*.ts',
'**/test/*.tsx'
],
rules: {}
}
]
};

View File

@ -0,0 +1,34 @@
# Logs
logs
*.log
npm-debug.log*
# Dependency directories
node_modules
# Build generated files
dist
lib
release
solution
temp
*.sppkg
.heft
# Coverage directory used by tools like istanbul
coverage
# OSX
.DS_Store
# Visual Studio files
.ntvs_analysis.dat
.vs
bin
obj
# Resx Generated Code
*.resx.ts
# Styles Generated Code
*.scss.ts

View File

@ -0,0 +1,16 @@
!dist
config
gulpfile.js
release
src
temp
tsconfig.json
tslint.json
*.log
.yo-rc.json
.vscode

View File

@ -0,0 +1,21 @@
{
"@microsoft/generator-sharepoint": {
"plusBeta": false,
"isCreatingSolution": true,
"nodeVersion": "16.18.1",
"sdksVersions": {
"@microsoft/microsoft-graph-client": "3.0.2",
"@microsoft/teams-js": "2.12.0"
},
"version": "1.18.2",
"libraryName": "react-azure-openai-api-stream",
"libraryId": "81a244d6-89dc-4a40-9e88-87a2565e6104",
"environment": "spo",
"packageManager": "npm",
"solutionName": "react-azure-openai-api-stream",
"solutionShortDescription": "react-azure-openai-api-stream description",
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"componentType": "webpart"
}
}

View File

@ -0,0 +1,80 @@
# Calling Azure OpenAI API in Stream mode
## Summary
This webpart shows how you can call Azure OpenAI API in Streaming mode, so the webpart shows the data coming from the API in chunks, giving a much better user experience, so you are not waiting for the entire response. It also shows how you can cancel the streaming response at any point, which is useful to safe some tokens (hence money), if the generating response does not look good to you (like when getting AI hallucinations).
[picture of the solution in action, if possible]
## Used SharePoint Framework Version
![version](https://img.shields.io/badge/version-1.18.2-green.svg)
## Applies to
- [SharePoint Framework](https://aka.ms/spfx)
- [Microsoft 365 tenant](https://docs.microsoft.com/en-us/sharepoint/dev/spfx/set-up-your-developer-tenant)
> Get your own free development tenant by subscribing to [Microsoft 365 developer program](http://aka.ms/o365devprogram)
## Prerequisites
- Your Azure Subscription has the Azure OpenAI service available. You will see this message if you try to add Azure OpenAI service in your Subscription (follow the link in the Azure portal to request access).
> Azure OpenAI Service is currently available to customers via an application form. The selected subscription has not been enabled for use of the service and does not have quota for any pricing tiers. Click here to request access to Azure OpenAI service.
- You have created an Azure OpenAI service in your subscription
- Create a Deployment Model (use GPT-3.5-turbo or GPT-4)
- Grab the Azure OpenAI Key, Endpoint and the deployment model created in previous step (go to your _Azure OpenAI service -> Keys and Endpoint_)
## Solution
| Solution | Author(s) |
| ----------- | ------------------------------------------------------- |
| react-azure-openai-api-stream | [Luis Mañez](https://github.com/luismanez) |
## Version history
| Version | Date | Comments |
| ------- | ---------------- | --------------- |
| 1.0 | January 2, 2024 | Initial release |
## Disclaimer
**THIS CODE IS PROVIDED _AS IS_ WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.**
---
## Minimal Path to Awesome
- Install the MS Graph Toolkit for SPFx package. [Follow this](https://learn.microsoft.com/graph/toolkit/get-started/mgt-spfx)
- Clone this repository
- Ensure that you are at the solution folder
- in the command-line run:
- `npm install`
- `gulp serve`
- Add the web part in the SharePoint workbench or any SharePoint page (appending _?debug=true&noredir=true&debugManifestsFile=<https://localhost:4321/temp/manifests.js>_ to the page URL)
- Edit the webpart with your Azure OpenAI API values (see _prerequisites_ section)
## Features
This sample illustrates the following concepts:
- Calling Azure OpenAI _chat/completions_ endpoint in streaming mode
- Keeping chat history during the chat session
- How to cancel an streaming request
- Using MS Graph toolkit with the Person component
- Multiple FluentUI components
> Notice that better pictures and documentation will increase the sample usage and the value you are providing for others. Thanks for your submissions advance.
> Share your web part with others through Microsoft 365 Patterns and Practices program to get visibility and exposure. More details on the community, open-source projects and other activities from http://aka.ms/m365pnp.
## References
- [Getting started with SharePoint Framework](https://docs.microsoft.com/en-us/sharepoint/dev/spfx/set-up-your-developer-tenant)
- [Building for Microsoft teams](https://docs.microsoft.com/en-us/sharepoint/dev/spfx/build-for-teams-overview)
- [Use Microsoft Graph in your solution](https://docs.microsoft.com/en-us/sharepoint/dev/spfx/web-parts/get-started/using-microsoft-graph-apis)
- [Publish SharePoint Framework applications to the Marketplace](https://docs.microsoft.com/en-us/sharepoint/dev/spfx/publish-to-marketplace-overview)
- [Microsoft 365 Patterns and Practices](https://aka.ms/m365pnp) - Guidance, tooling, samples and open-source controls for your Microsoft 365 development

View File

@ -0,0 +1,19 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
"version": "2.0",
"bundles": {
"chat-streaming-web-part": {
"components": [
{
"entrypoint": "./lib/webparts/chatStreaming/ChatStreamingWebPart.js",
"manifest": "./src/webparts/chatStreaming/ChatStreamingWebPart.manifest.json"
}
]
}
},
"externals": {},
"localizedResources": {
"ChatStreamingWebPartStrings": "lib/webparts/chatStreaming/loc/{locale}.js",
"PropertyControlStrings": "node_modules/@pnp/spfx-property-controls/lib/loc/{locale}.js"
}
}

View File

@ -0,0 +1,7 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/deploy-azure-storage.schema.json",
"workingDir": "./release/assets/",
"account": "<!-- STORAGE ACCOUNT NAME -->",
"container": "react-azure-openai-api-stream",
"accessKey": "<!-- ACCESS KEY -->"
}

View File

@ -0,0 +1,40 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
"solution": {
"name": "react-azure-openai-api-stream-client-side-solution",
"id": "81a244d6-89dc-4a40-9e88-87a2565e6104",
"version": "1.0.0.0",
"includeClientSideAssets": true,
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"developer": {
"name": "",
"websiteUrl": "",
"privacyUrl": "",
"termsOfUseUrl": "",
"mpnId": "Undefined-1.18.2"
},
"metadata": {
"shortDescription": {
"default": "react-azure-openai-api-stream description"
},
"longDescription": {
"default": "react-azure-openai-api-stream description"
},
"screenshotPaths": [],
"videoUrl": "",
"categories": []
},
"features": [
{
"title": "react-azure-openai-api-stream Feature",
"description": "The feature that activates elements of the react-azure-openai-api-stream solution.",
"id": "edb1b265-356e-4aec-9a12-0cabfbba9700",
"version": "1.0.0.0"
}
]
},
"paths": {
"zippedPackage": "solution/react-azure-openai-api-stream.sppkg"
}
}

View File

@ -0,0 +1,3 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/core-build/sass.schema.json"
}

View File

@ -0,0 +1,6 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/spfx-serve.schema.json",
"port": 4321,
"https": true,
"initialPage": "https://{tenantDomain}/_layouts/workbench.aspx"
}

View File

@ -0,0 +1,4 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/write-manifests.schema.json",
"cdnBasePath": "<!-- PATH TO CDN -->"
}

View File

@ -0,0 +1,16 @@
'use strict';
const build = require('@microsoft/sp-build-web');
build.addSuppression(`Warning - [sass] The local CSS class 'ms-Grid' is not camelCase and will not be type-safe.`);
var getTasks = build.rig.getTasks;
build.rig.getTasks = function () {
var result = getTasks.call(build.rig);
result.set('serve', result.get('serve-deprecated'));
return result;
};
build.initialize(require('gulp'));

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,46 @@
{
"name": "react-azure-openai-api-stream",
"version": "0.0.1",
"private": true,
"engines": {
"node": ">=16.13.0 <17.0.0 || >=18.17.1 <19.0.0"
},
"main": "lib/index.js",
"scripts": {
"build": "gulp bundle",
"clean": "gulp clean",
"test": "gulp test"
},
"dependencies": {
"@fluentui/react": "^8.106.4",
"@microsoft/mgt-react": "^3.0.1",
"@microsoft/mgt-spfx": "^3.0.1",
"@microsoft/fetch-event-source": "^2.0.1",
"@microsoft/sp-component-base": "1.18.2",
"@microsoft/sp-core-library": "1.18.2",
"@microsoft/sp-lodash-subset": "1.18.2",
"@microsoft/sp-office-ui-fabric-core": "1.18.2",
"@microsoft/sp-property-pane": "1.18.2",
"@microsoft/sp-webpart-base": "1.18.2",
"@pnp/spfx-property-controls": "3.15.1",
"react": "17.0.1",
"react-dom": "17.0.1",
"tslib": "2.3.1"
},
"devDependencies": {
"@microsoft/eslint-config-spfx": "1.18.2",
"@microsoft/eslint-plugin-spfx": "1.18.2",
"@microsoft/rush-stack-compiler-4.7": "0.1.0",
"@microsoft/sp-build-web": "1.18.2",
"@microsoft/sp-module-interfaces": "1.18.2",
"@rushstack/eslint-config": "2.5.1",
"@types/react": "17.0.45",
"@types/react-dom": "17.0.17",
"@types/webpack-env": "~1.15.2",
"ajv": "^6.12.5",
"eslint": "8.7.0",
"eslint-plugin-react-hooks": "4.3.0",
"gulp": "4.0.2",
"typescript": "4.7.4"
}
}

View File

@ -0,0 +1 @@
// A file is required to be in the root of the /src directory by the TypeScript compiler

View File

@ -0,0 +1,26 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "1830f013-dfb8-4e7f-8e7a-8375c1243326",
"alias": "ChatStreamingWebPart",
"componentType": "WebPart",
"version": "*",
"manifestVersion": 2,
"requiresCustomScript": false,
"supportedHosts": ["SharePointWebPart", "TeamsPersonalApp", "TeamsTab", "SharePointFullPage"],
"supportsThemeVariants": true,
"preconfiguredEntries": [{
"groupId": "5c03119e-3074-46fd-976b-c60198311f70",
"group": { "default": "Advanced" },
"title": { "default": "OpenAi Chat in streaming" },
"description": { "default": "This webpart provides an OpenAI chat in streaming mode." },
"officeFabricIconFontName": "Page",
"properties": {
"openAiApiKey": "",
"openAiApiEndpoint": "",
"openAiApiDeployment": ""
}
}]
}

View File

@ -0,0 +1,140 @@
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
type IPropertyPaneConfiguration,
PropertyPaneTextField
} from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import { IReadonlyTheme } from '@microsoft/sp-component-base';
import { PropertyFieldPassword } from '@pnp/spfx-property-controls/lib/PropertyFieldPassword';
import * as strings from 'ChatStreamingWebPartStrings';
import ChatStreaming from './components/ChatStreaming';
import { IChatStreamingProps } from './components/IChatStreamingProps';
import { Providers, SharePointProvider } from '@microsoft/mgt-spfx';
export interface IChatStreamingWebPartProps {
openAiApiKey: string;
openAiApiEndpoint: string;
openAiApiDeploymentName: string;
}
export default class ChatStreamingWebPart extends BaseClientSideWebPart<IChatStreamingWebPartProps> {
private _isDarkTheme: boolean = false;
private _environmentMessage: string = '';
public render(): void {
const element: React.ReactElement<IChatStreamingProps> = React.createElement(
ChatStreaming,
{
openApiOptions: {
apiKey: this.properties.openAiApiKey,
endpoint: this.properties.openAiApiEndpoint,
deploymentName: this.properties.openAiApiDeploymentName
},
isDarkTheme: this._isDarkTheme,
environmentMessage: this._environmentMessage,
hasTeamsContext: !!this.context.sdks.microsoftTeams,
userDisplayName: this.context.pageContext.user.displayName,
httpClient: this.context.httpClient
}
);
ReactDom.render(element, this.domElement);
}
protected onInit(): Promise<void> {
if (!Providers.globalProvider) {
Providers.globalProvider = new SharePointProvider(this.context);
}
return this._getEnvironmentMessage().then(message => {
this._environmentMessage = message;
});
}
private _getEnvironmentMessage(): Promise<string> {
if (!!this.context.sdks.microsoftTeams) { // running in Teams, office.com or Outlook
return this.context.sdks.microsoftTeams.teamsJs.app.getContext()
.then(context => {
let environmentMessage: string = '';
switch (context.app.host.name) {
case 'Office': // running in Office
environmentMessage = this.context.isServedFromLocalhost ? strings.AppLocalEnvironmentOffice : strings.AppOfficeEnvironment;
break;
case 'Outlook': // running in Outlook
environmentMessage = this.context.isServedFromLocalhost ? strings.AppLocalEnvironmentOutlook : strings.AppOutlookEnvironment;
break;
case 'Teams': // running in Teams
case 'TeamsModern':
environmentMessage = this.context.isServedFromLocalhost ? strings.AppLocalEnvironmentTeams : strings.AppTeamsTabEnvironment;
break;
default:
environmentMessage = strings.UnknownEnvironment;
}
return environmentMessage;
});
}
return Promise.resolve(this.context.isServedFromLocalhost ? strings.AppLocalEnvironmentSharePoint : strings.AppSharePointEnvironment);
}
protected onThemeChanged(currentTheme: IReadonlyTheme | undefined): void {
if (!currentTheme) {
return;
}
this._isDarkTheme = !!currentTheme.isInverted;
const {
semanticColors
} = currentTheme;
if (semanticColors) {
this.domElement.style.setProperty('--bodyText', semanticColors.bodyText || null);
this.domElement.style.setProperty('--link', semanticColors.link || null);
this.domElement.style.setProperty('--linkHovered', semanticColors.linkHovered || null);
}
}
protected onDispose(): void {
ReactDom.unmountComponentAtNode(this.domElement);
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneTextField('openAiApiEndpoint', {
label: strings.OpenAiApiEndpointFieldLabel
}),
PropertyPaneTextField('openAiApiDeploymentName', {
label: strings.OpenAiApiDeploymentFieldLabel
}),
PropertyFieldPassword("openAiApiKey", {
key: "openAiApiKey",
label: strings.OpenAiApiKeyFieldLabel,
value: this.properties.openAiApiKey
})
]
}
]
}
]
};
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

View File

@ -0,0 +1,58 @@
import { Stack } from "@fluentui/react";
import { Icon } from '@fluentui/react';
import * as React from "react";
export interface IAssistantResponseProps {
message: string;
}
export default class AssistantResponse extends React.Component<
IAssistantResponseProps,
{}
> {
public render(): React.ReactElement<IAssistantResponseProps> {
return (
<Stack horizontal tokens={{ childrenGap: 30, padding: 10 }}>
<Stack.Item>
<Icon iconName="Robot" styles={{ root: { fontSize: '22px' } }} />
</Stack.Item>
<Stack.Item
grow
styles={{ root: { display: "flex", justifyContent: "flex-start" } }}
>
<div
style={{
position: "relative",
borderRadius: "5px",
padding: "5px",
backgroundColor: "white",
fontFamily:
'"Segoe UI", "Segoe UI Web (West European)", "Segoe UI", -apple-system, BlinkMacSystemFont, Roboto, "Helvetica Neue", sans-serif;',
fontSize: "14px",
fontWeight: "400",
boxShadow: "0px 4px 8px rgba(0, 0, 0, 0.1)",
maxWidth: "85%",
minWidth: "350px"
}}
>
<p style={{ minWidth: '100px' }}>{this.props.message}</p>
<div
style={{
content: '""',
position: "absolute",
left: "-10px",
top: "10px", // changed right to left
width: "0",
height: "0",
borderTop: "10px solid transparent",
borderBottom: "10px solid transparent",
borderRight: "10px solid white", // changed borderLeft to borderRight
}}
/>
</div>
</Stack.Item>
</Stack>
);
}
}

View File

@ -0,0 +1,33 @@
@import '~@fluentui/react/dist/sass/References.scss';
.chatStreaming {
overflow: hidden;
color: "[theme:bodyText, default: #323130]";
color: var(--bodyText);
&.teams {
font-family: $ms-font-family-fallbacks;
}
}
.welcome {
text-align: left;
}
.welcomeImage {
width: 100%;
max-width: 420px;
}
.links {
a {
text-decoration: none;
color: "[theme:link, default:#03787c]";
color: var(--link); // note: CSS Custom Properties support is limited to modern browsers only
&:hover {
text-decoration: underline;
color: "[theme:linkHovered, default: #014446]";
color: var(--linkHovered); // note: CSS Custom Properties support is limited to modern browsers only
}
}
}

View File

@ -0,0 +1,180 @@
import * as React from 'react';
//import styles from './ChatStreaming.module.scss';
import type { IChatStreamingProps } from './IChatStreamingProps';
import { IChatStreamingState } from './IChatStreamingState';
import { cloneDeep } from '@microsoft/sp-lodash-subset';
import { fetchEventSource } from '@microsoft/fetch-event-source';
import CompletionsRequestBuilder from '../models/CompletionsRequestBuilder';
import { Spinner, SpinnerSize, Stack } from '@fluentui/react';
import MessagesList from './MessagesList';
import UserMessage from './UserMessage';
import { IChatMessage } from '../models/IChatMessage';
//import { ICompletionsRequest } from '../Models/ICompletionsRequest';
export default class ChatStreaming extends React.Component<IChatStreamingProps, IChatStreamingState> {
private _signal: AbortSignal;
private _controller: AbortController;
constructor(props: IChatStreamingProps) {
super(props);
this.state = {
userQuery: '',
sessionMessages: [],
thinking: false
}
this._controller = new AbortController();
this._signal = this._controller.signal;
}
public render(): React.ReactElement<IChatStreamingProps> {
const content = this._validateWebPartProperties() ? (
<Stack tokens={{ childrenGap: 20 }} style={{ minHeight: "100%" }}>
<Stack.Item
grow={1}
styles={{
root: { minHeight: "200px", height: "100%", position: "relative" },
}}
>
<MessagesList messages={this.state.sessionMessages} />
</Stack.Item>
{this.state.thinking && (
<Stack.Item>
<Spinner
size={SpinnerSize.large}
label="Wait till our super cool AI system answers your question..."
ariaLive="assertive"
labelPosition="right"
/>
</Stack.Item>
)}
<Stack.Item>
<UserMessage
textFieldValue={this.state.userQuery}
onMessageChange={this._onUserQueryChange}
sendQuery={this._onQuerySent}
controller={this._controller}
/>
</Stack.Item>
</Stack>
) : (
<div>Please configure the OpenAI API settings in Webpart panel</div>
);
return (
content
);
}
private _onQuerySent = async (): Promise<void> => {
this.setState({
thinking: true
});
this.state.sessionMessages.push({
role: 'user', text: this.state.userQuery
});
await this._chatAsStream();
this.setState({
thinking: false
});
}
private _onUserQueryChange = (newQuery: string): void => {
this.setState({
userQuery: newQuery
});
}
private _chatAsStream = async (): Promise<void> => {
const openAiApiOptions = this.props.openApiOptions;
const endpoint: string = `${openAiApiOptions.endpoint}/openai/deployments/${openAiApiOptions.deploymentName}/chat/completions?api-version=2023-06-01-preview`;
const setStreamChunk = (text: string): void => {
const currentChatGptMessages: IChatMessage[] = cloneDeep(this.state.sessionMessages);
if (text !== undefined && text !== null && text.length > 0) {
const lastSessionMessage = currentChatGptMessages[currentChatGptMessages.length - 1];
if (lastSessionMessage.role === 'user') {
currentChatGptMessages.push({
role: 'assistant',
text: text
});
} else {
lastSessionMessage.text += text;
}
this.setState({
sessionMessages: currentChatGptMessages,
thinking: false,
userQuery: ''
});
}
};
const requestBuilder: CompletionsRequestBuilder = new CompletionsRequestBuilder();
this.state.sessionMessages.map(m => {
if (m.role === 'assistant') {
requestBuilder.addAssistantMessage(m.text);
} else {
requestBuilder.addUserMessage(m.text);
}
});
await fetchEventSource(endpoint, {
method: "POST",
headers: {
"Accept": "text/event-stream",
"Content-type": "application/json",
"api-key": openAiApiOptions.apiKey
},
body: requestBuilder.buildAsJson(),
async onopen(res) {
console.log(res);
},
onmessage(event) {
//console.log(event.data);
if (event.data === "[DONE]") {
console.log("Stream done");
return;
}
const data = JSON.parse(event.data);
const text: string =
data.choices && data.choices.length > 0 && data.choices[0] && data.choices[0].delta ?
data.choices[0].delta.content
: '';
setStreamChunk(text);
//console.log(text);
},
onclose() {
console.log("Connection closed by the server");
},
onerror(err) {
console.log("There was an error from server", err);
},
signal: this._signal
});
}
private _validateWebPartProperties(): boolean {
if (!this.props.openApiOptions.apiKey) {
return false;
}
if (!this.props.openApiOptions.endpoint) {
return false;
}
if (!this.props.openApiOptions.deploymentName) {
return false;
}
return true;
}
}

View File

@ -0,0 +1,11 @@
import IOpenAiApiOptions from "../models/IOpenApiOptions";
import {HttpClient} from '@microsoft/sp-http';
export interface IChatStreamingProps {
openApiOptions: IOpenAiApiOptions;
isDarkTheme: boolean;
environmentMessage: string;
hasTeamsContext: boolean;
userDisplayName: string;
httpClient: HttpClient;
}

View File

@ -0,0 +1,7 @@
import { IChatMessage } from "../models/IChatMessage";
export interface IChatStreamingState {
userQuery: string;
sessionMessages: IChatMessage[];
thinking: boolean;
}

View File

@ -0,0 +1,40 @@
import * as React from "react";
import UserQuestion from "./UserQuestion";
import AssistantResponse from "./AssistantResponse";
import { IChatMessage } from "../models/IChatMessage";
import { ScrollablePane, ScrollbarVisibility } from '@fluentui/react';
export interface IMessagesListProps {
messages: IChatMessage[];
}
export default class MessagesList extends React.Component<IMessagesListProps, {}> {
public componentDidUpdate(): void {
const scrollContainers = document.querySelectorAll(".ms-ScrollablePane--contentContainer");
const lastScrollContainer = scrollContainers[scrollContainers.length - 1] as HTMLElement;
if (lastScrollContainer) {
lastScrollContainer.scrollTop = lastScrollContainer.scrollHeight;
}
}
public render(): React.ReactElement<IMessagesListProps> {
const output = this.props.messages.map((m, i) => {
if (m.role === 'user') {
return <UserQuestion key={i} message={m.text} />
}
return <AssistantResponse key={i} message={m.text} />
});
return (
<div style= {{ backgroundColor: '#f3f3f3', minHeight: '200px' }}>
<ScrollablePane scrollbarVisibility={ScrollbarVisibility.auto} style={{ padding: '20px' }}>
{output}
</ScrollablePane>
</div>
);
}
}

View File

@ -0,0 +1,67 @@
import { IconButton, Stack, TextField } from '@fluentui/react';
import * as React from 'react';
export interface IUserMessageProps {
onMessageChange: (query: string) => void;
sendQuery: () => Promise<void>;
controller: AbortController;
textFieldValue: string;
}
export default class UserMessage extends React.Component<IUserMessageProps, {}> {
private _onChange = (
ev: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>,
newText: string
): void => {
this.props.onMessageChange(newText);
};
private _handleClick = async (): Promise<void> => {
await this.props.sendQuery();
};
private _keyDownHandler = async (e: KeyboardEvent): Promise<void> => {
if (e.ctrlKey && e.code === "Enter") {
await this._handleClick();
}
};
public componentDidMount(): void {
window.addEventListener("keydown", this._keyDownHandler);
}
public componentWillUnmount(): void {
window.removeEventListener("keydown", this._keyDownHandler);
}
public render(): React.ReactElement<IUserMessageProps> {
return (
<Stack horizontal tokens={{ childrenGap: 5 }}>
<Stack.Item grow={1}>
<TextField
multiline
autoAdjustHeight
value={this.props.textFieldValue}
onChange={this._onChange}
label="User message"
placeholder="Type user query here."
/>
</Stack.Item>
<Stack.Item align="end">
<IconButton
iconProps={{ iconName: "Send" }}
title="Send"
ariaLabel="Send"
onClick={this._handleClick}
/>
<IconButton
iconProps={{ iconName: 'Stop' }}
title="Stop generating"
ariaLabel="Stop"
onClick={() => this.props.controller.abort()}
/>
</Stack.Item>
</Stack>
);
}
}

View File

@ -0,0 +1,57 @@
import { Stack } from "@fluentui/react";
import { Person } from "@microsoft/mgt-react/dist/es6/spfx";
import { ViewType } from "@microsoft/mgt-spfx";
import * as React from "react";
export interface IUserQuestionProps {
message: string;
}
export default class UserQuestion extends React.Component<
IUserQuestionProps,
{}
> {
public render(): React.ReactElement<IUserQuestionProps> {
return (
<Stack horizontal horizontalAlign="end" tokens={{ childrenGap: 30, padding: 5 }}>
<Stack.Item
styles={{ root: { display: "flex", justifyContent: 'flex-end', alignItems: 'flex-end' } }}
>
<div
style={{
position: "relative",
borderRadius: "5px",
padding: "5px",
backgroundColor: "white",
fontFamily:
'"Segoe UI", "Segoe UI Web (West European)", "Segoe UI", -apple-system, BlinkMacSystemFont, Roboto, "Helvetica Neue", sans-serif;',
fontSize: "14px",
fontWeight: "400",
boxShadow: "0px 4px 8px rgba(0, 0, 0, 0.1)",
maxWidth: "85%",
minWidth: "350px"
}}
>
<p style={{ minWidth: '100px' }}>{this.props.message}</p>
<div
style={{
content: '""',
position: "absolute",
right: "-10px",
top: "10px",
width: "0",
height: "0",
borderTop: "10px solid transparent",
borderBottom: "10px solid transparent",
borderLeft: "10px solid white",
}}
/>
</div>
</Stack.Item>
<Stack.Item>
<Person personQuery="me" view={ViewType.image} avatarSize="auto" />
</Stack.Item>
</Stack>
);
}
}

View File

@ -0,0 +1,22 @@
define([], function () {
return {
PropertyPaneDescription: "Description",
BasicGroupName: "OpenAI API Settings",
OpenAiApiEndpointFieldLabel: "OpenAI API Endpoint",
OpenAiApiKeyFieldLabel: "OpenAI API Key",
OpenAiApiDeploymentFieldLabel: "OpenAI API Deployment Name",
AppLocalEnvironmentSharePoint:
"The app is running on your local environment as SharePoint web part",
AppLocalEnvironmentTeams:
"The app is running on your local environment as Microsoft Teams app",
AppLocalEnvironmentOffice:
"The app is running on your local environment in office.com",
AppLocalEnvironmentOutlook:
"The app is running on your local environment in Outlook",
AppSharePointEnvironment: "The app is running on SharePoint page",
AppTeamsTabEnvironment: "The app is running in Microsoft Teams",
AppOfficeEnvironment: "The app is running in office.com",
AppOutlookEnvironment: "The app is running in Outlook",
UnknownEnvironment: "The app is running in an unknown environment",
};
});

View File

@ -0,0 +1,21 @@
declare interface IChatStreamingWebPartStrings {
PropertyPaneDescription: string;
BasicGroupName: string;
OpenAiApiEndpointFieldLabel: string;
OpenAiApiKeyFieldLabel: string;
OpenAiApiDeploymentFieldLabel: string;
AppLocalEnvironmentSharePoint: string;
AppLocalEnvironmentTeams: string;
AppLocalEnvironmentOffice: string;
AppLocalEnvironmentOutlook: string;
AppSharePointEnvironment: string;
AppTeamsTabEnvironment: string;
AppOfficeEnvironment: string;
AppOutlookEnvironment: string;
UnknownEnvironment: string;
}
declare module 'ChatStreamingWebPartStrings' {
const strings: IChatStreamingWebPartStrings;
export = strings;
}

View File

@ -0,0 +1,41 @@
import { ICompletionsRequest } from "./ICompletionsRequest";
export default class CompletionsRequestBuilder {
private _completionsRequest: ICompletionsRequest
public constructor() {
this._completionsRequest = {
messages: [{
role: "system",
content: "You are an AI assistant that helps users of an intranet."}
],
temperature: 0,
top_p: 1,
max_tokens: 800,
stream: true
}
}
public addUserMessage(content: string): void {
this._completionsRequest.messages.push({
role: "user",
content: content
});
}
public addAssistantMessage(content: string): void {
this._completionsRequest.messages.push({
role: "assistant",
content: content
});
}
public build(): ICompletionsRequest {
return this._completionsRequest;
}
public buildAsJson(): string {
return JSON.stringify(this._completionsRequest);
}
}

View File

@ -0,0 +1,4 @@
export interface IChatMessage {
role: 'user' | 'assistant';
text: string;
}

View File

@ -0,0 +1,12 @@
export interface ICompletionsRequest {
messages: ICompletionsMessage[];
temperature: number;
top_p: number;
max_tokens: number;
stream: boolean;
}
export interface ICompletionsMessage {
role: "user" | "assistant" | "system";
content: string;
}

View File

@ -0,0 +1,19 @@
export interface ICompletionsResponse {
id: string
model: string
created: number
object: string
choices: Choice[]
}
export interface Choice {
index: number
messages: Message[]
}
export interface Message {
index: number
role: "assistant" | "tool"
content: string
end_turn: boolean
}

View File

@ -0,0 +1,5 @@
export default interface IOpenAiApiOptions {
apiKey: string;
endpoint: string;
deploymentName: string;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 249 B

View File

@ -0,0 +1,35 @@
{
"extends": "./node_modules/@microsoft/rush-stack-compiler-4.7/includes/tsconfig-web.json",
"compilerOptions": {
"target": "es5",
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"jsx": "react",
"declaration": true,
"sourceMap": true,
"experimentalDecorators": true,
"skipLibCheck": true,
"outDir": "lib",
"inlineSources": false,
"noImplicitAny": true,
"typeRoots": [
"./node_modules/@types",
"./node_modules/@microsoft"
],
"types": [
"webpack-env"
],
"lib": [
"es5",
"dom",
"es2015.collection",
"es2015.promise"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx"
]
}