Merge pull request #3478 from joaojmendes/OpenAIChatGPT

New Sample react-chatGPT-app
This commit is contained in:
Hugo Bernier 2023-02-20 22:43:56 -05:00 committed by GitHub
commit 309294ea69
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
76 changed files with 73026 additions and 0 deletions

View File

@ -0,0 +1,39 @@
// For more information on how to run this SPFx project in a VS Code Remote Container, please visit https://aka.ms/spfx-devcontainer
{
"name": "SPFx 1.16.1",
"image": "docker.io/m365pnp/spfx:1.16.1",
// Set *default* container specific settings.json values on container create.
"settings": {},
// Add the IDs of extensions you want installed when the container is created.
"extensions": [
"editorconfig.editorconfig",
"dbaeumer.vscode-eslint"
],
// Use 'forwardPorts' to make a list of ports inside the container available locally.
"forwardPorts": [
4321,
35729
],
"portsAttributes": {
"4321": {
"protocol": "https",
"label": "Manifest",
"onAutoForward": "silent",
"requireLocalPort": true
},
// Not needed for SPFx>= 1.12.1
// "5432": {
// "protocol": "https",
// "label": "Workbench",
// "onAutoForward": "silent"
// },
"35729": {
"protocol": "https",
"label": "LiveReload",
"onAutoForward": "silent",
"requireLocalPort": true
}
},
"postCreateCommand": "bash .devcontainer/spfx-startup.sh",
"remoteUser": "node"
}

View File

@ -0,0 +1,33 @@
echo
echo -e "\e[1;94mInstalling Node dependencies\e[0m"
npm install
## commands to create dev certificate and copy it to the root folder of the project
echo
echo -e "\e[1;94mGenerating dev certificate\e[0m"
gulp trust-dev-cert
# Convert the generated PEM certificate to a CER certificate
openssl x509 -inform PEM -in ~/.rushstack/rushstack-serve.pem -outform DER -out ./spfx-dev-cert.cer
# Copy the PEM ecrtificate for non-Windows hosts
cp ~/.rushstack/rushstack-serve.pem ./spfx-dev-cert.pem
## add *.cer to .gitignore to prevent certificates from being saved in repo
if ! grep -Fxq '*.cer' ./.gitignore
then
echo "# .CER Certificates" >> .gitignore
echo "*.cer" >> .gitignore
fi
## add *.pem to .gitignore to prevent certificates from being saved in repo
if ! grep -Fxq '*.pem' ./.gitignore
then
echo "# .PEM Certificates" >> .gitignore
echo "*.pem" >> .gitignore
fi
echo
echo -e "\e[1;92mReady!\e[0m"
echo -e "\n\e[1;94m**********\nOptional: if you plan on using gulp serve, don't forget to add the container certificate to your local machine. Please visit https://aka.ms/spfx-devcontainer for more information\n**********"

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/no-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: {}
}
]
};

35
samples/react-chatGPT-app/.gitignore vendored Normal file
View File

@ -0,0 +1,35 @@
# 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
*.scss.d.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.4.1"
},
"version": "1.16.1",
"libraryName": "react-chat-gpt-message-extension",
"libraryId": "560953a2-d85c-41de-84f6-4def64002ea1",
"environment": "spo",
"packageManager": "npm",
"solutionName": "react-chat-gpt-message-extension",
"solutionShortDescription": "react-chat-gpt-message-extension description",
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"componentType": "webpart"
}
}

View File

@ -0,0 +1,156 @@
# Chat GPT App
## Summary
This App is a implementation of OpenAI ChatGPT-3. It runs on SharePoint, Teams as Personal or Teams App and Message Extension.
![React-ChatGPT-App](./assets/ChatGPT.png)
![React-ChatGPT-App](./assets/chatGPT.gif)
## Compatibility
| :warning: Important |
|:---------------------------|
| Every SPFx version is optimally compatible with specific versions of Node.js. In order to be able to build this sample, you need to ensure that the version of Node on your workstation matches one of the versions listed in this section. This sample will not work on a different version of Node.|
|Refer to <https://aka.ms/spfx-matrix> for more information on SPFx compatibility. |
This sample is optimally compatible with the following environment configuration:
![SPFx 1.16.1](https://img.shields.io/badge/SPFx-1.16.1-green.svg)
![Node.js v16 | v14 | v12](https://img.shields.io/badge/Node.js-v16%20%7C%20v14%20%7C%20v12-green.svg)
![Compatible with SharePoint Online](https://img.shields.io/badge/SharePoint%20Online-Compatible-green.svg)
![Does not work with SharePoint 2019](https://img.shields.io/badge/SharePoint%20Server%202019-Incompatible-red.svg "SharePoint Server 2019 requires SPFx 1.4.1 or lower")
![Does not work with SharePoint 2016 (Feature Pack 2)](https://img.shields.io/badge/SharePoint%20Server%202016%20(Feature%20Pack%202)-Incompatible-red.svg "SharePoint Server 2016 Feature Pack 2 requires SPFx 1.1")
![Local Workbench Unsupported](https://img.shields.io/badge/Local%20Workbench-Unsupported-red.svg "Local workbench is no longer available as of SPFx 1.13 and above")
![Hosted Workbench Compatible](https://img.shields.io/badge/Hosted%20Workbench-Compatible-green.svg)
![Compatible with Remote Containers](https://img.shields.io/badge/Remote%20Containers-Compatible-green.svg)
## Applies to
* [SharePoint Framework](https://learn.microsoft.com/sharepoint/dev/spfx/sharepoint-framework-overview)
* [Microsoft 365 tenant](https://learn.microsoft.com/sharepoint/dev/spfx/set-up-your-development-environment)
> Get your own free development tenant by subscribing to [Microsoft 365 developer program](http://aka.ms/m365devprogram)
## Prerequisites
The SPFx App has thisPrerequisites:
* Azure Function Deployed to Azure
In the directory **./OpenAIFunctionProject/OpenAI-azure-functions.zip** you will found the project with AzureFunction zip.ed, please copy to local computer unzip and deploy. The Azure Function App needs to be configured with Authentication Provider Microsoft , please see the README.md file on the project.
* OpenAI KEY
The App require your personal API_KEY to call the API to ChatGPT. Please go to [OpenAI](https://platform.openai.com/) and create an Account and get your API KEY.
This API KY needs to be configured on the Azure Function App in Applications Settings. See README.md on Azure Functions Project for more details.
* Configure Tenant Properties.
The App needs the follow tenant properties configured on your tenant :
* "OpenAIFunctionsAppId" this Tenant property has the Azure APPID used to secure your Azure Function APP (see README.md on OpenAIFunctionProject)
To add Tenant property you can use M365 Cli or PowerShell to do it.
sample M365 Cli :
``m365 spo storageentity set --key OpenAIFunctionsAppId --value 6b4a20b2-bf2f-xxxx-xxxx-af960a40c2dc --appCatalogUrl https://xxxxx.sharepoint.com/sites/appcatalog``
sample PnP-PowerShell:
``Set-PnPStorageEntity -Key OpenAIFunctionsAppId -Value 6b4a20b2-bf2f-xxxx-xxxx-af960a40c2dc``
* "OpenAIAzureFunctionUrl", this Tenant property has the URL of Azure Function
sample M365 Cli :
``m365 spo storageentity set --key OpenAIAzureFunctionUrl --value https://openaifunctionsapp.azurewebsites.net/api/OpenAICompletion --appCatalogUrl https://xxxxx.sharepoint.com/sites/appcatalog``
sample PnP-PowerShell:
``Set-PnPStorageEntity -Key OpenAIAzureFunctionUrl -Value https://openaifunctionsapp.azurewebsites.net/api/OpenAICompletion``
* Upload APP to Teams catalog
This App can be used has Teams Message Extension, please go to "teams" directory and upload the zip file to Teams App on M365 Teams Administration.
* Approve the Required App Permissions on SharePoint Admin.
You need to add the required permissions to the App for your Azure App used to secure the Azure Function App, by default the project has the follow defined on the package-solution.json:
``"webApiPermissionRequests": [
{
"resource": "OpenAIFunctionsApp",
"scope": "user_impersonation"
}
],``
This assume you have a Azure App called "OpenAIFunctionsApp", you can change this before bundle and create the package to deploy and after you Azure Functions App configured. <https://admin.teams.microsoft.com/policies/manage-apps>
## Contributors
* [João Mendes](https://github.com/joaojmendes)
## Version history
Version|Date|Comments
-------|----|--------
1.0.0|Feb 19, 2023|Initial release
## Minimal Path to Awesome
* Clone this repository
* in the command line run:
* `npm install`
* `gulp build`
* `gulp bundle --ship`
* `gulp package-solution --ship`
* Add and Deploy Package to AppCatalog
> This sample can also be opened with [VS Code Remote Development](https://code.visualstudio.com/docs/remote/remote-overview). Visit <https://aka.ms/spfx-devcontainer> for further instructions.
## Features
This project shows how to use OpenAPI to ChatGPT and share information on teams message as an adaptive card.
* using React for building SharePoint Framework client-side web parts
* using React components for building ChatGPT web part
* using OpenAI API
* using MSGraph API to send AdaptiveCard to Chat
* Using React Hooks
* using Global State Management (JOTAI)
* using localStorage
* using Fluent UI FrameWork
## References
* [Getting started with SharePoint Framework](https://learn.microsoft.com/sharepoint/dev/spfx/set-up-your-developer-tenant)
* [Building for Microsoft teams](https://learn.microsoft.com/sharepoint/dev/spfx/build-for-teams-overview)
* [Use Microsoft Graph in your solution](https://learn.microsoft.com/sharepoint/dev/spfx/web-parts/get-started/using-microsoft-graph-apis)
* [Publish SharePoint Framework applications to the Marketplace](https://learn.microsoft.com/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
* [Fluent UI version 9](https://github.com/microsoft/fluentui/tree/master/packages/react-components) - Converged Fluent UI components
## Help
We do not support samples, but we this community is always willing to help, and we want to improve these samples. We use GitHub to track issues, which makes it easy for community members to volunteer their time and help resolve issues.
If you're having issues building the solution, please run [spfx doctor](https://pnp.github.io/cli-microsoft365/cmd/spfx/spfx-doctor/) from within the solution folder to diagnose incompatibility issues with your environment.
If you encounter any issues while using this sample, [create a new issue](https://github.com/pnp/sp-dev-fx-webparts/issues/new?assignees=&labels=Needs%3A+Triage+%3Amag%3A%2Ctype%3Abug-suspected%2Csample%3A%20react-chatgpt-app&template=bug-report.yml&sample=react-chatgpt-app&authors=@smaity%20@joaojmendes&title=react-chatgpt-app%20-%20).
For questions regarding this sample, [create a new question](https://github.com/pnp/sp-dev-fx-webparts/issues/new?assignees=&labels=Needs%3A+Triage+%3Amag%3A%2Ctype%3Aquestion%2Csample%3A%20react-chatgpt-app&template=question.yml&sample=react-chatgpt-app&authors=@smaity%20@joaojmendes&title=react-chatgpt-app%20-%20).
Finally, if you have an idea for improvement, [make a suggestion](https://github.com/pnp/sp-dev-fx-webparts/issues/new?assignees=&labels=Needs%3A+Triage+%3Amag%3A%2Ctype%3Aenhancement%2Csample%3A%20react-chatgpt-app&template=question.yml&sample=react-chatgpt-app&authors=@smaity%20@joaojmendes&title=react-chatgpt-app%20-%20).
## 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.**
<img src="https://pnptelemetry.azurewebsites.net/sp-dev-fx-webparts/samples/react-chatgpt-app" />

Binary file not shown.

After

Width:  |  Height:  |  Size: 196 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 MiB

View File

@ -0,0 +1,50 @@
[
{
"name": "pnp-sp-dev-spfx-web-parts-react-chatgpt-app",
"source": "pnp",
"title": "Chat GPT App",
"shortDescription": "This App is a implementation of OpenAI ChatGPT-3. It runs on SharePoint, Teams as Personal or Teams App and Message Extension.",
"url": "https://github.com/pnp/sp-dev-fx-webparts/tree/main/samples/react-chatgpt-app",
"downloadUrl": "https://pnp.github.io/download-partial/?url=https://github.com/pnp/sp-dev-fx-webparts/tree/main/samples/react-chatgpt-app",
"longDescription": [
"This App is a implementation of OpenAI ChatGPT-3. It runs on SharePoint, Teams as Personal or Teams App and Message Extension."
],
"creationDateTime": "2023-02-19",
"updateDateTime": "2023-02-19",
"products": [
"SharePoint"
],
"metadata": [
{
"key": "CLIENT-SIDE-DEV",
"value": "React"
},
{
"key": "SPFX-VERSION",
"value": "1.16.1"
}
],
"thumbnails": [
{
"type": "image",
"order": 100,
"url": "https://github.com/pnp/sp-dev-fx-webparts/raw/main/samples/react-chatgpt-app/assets/ChatGPT.png",
"alt": "Web Part Preview"
}
],
"authors": [
{
"gitHubAccount": "joaojmendes",
"pictureUrl": "https://github.com/joaojmendes.png",
"name": "João Mendes"
}
],
"references": [
{
"name": "Build your first SharePoint client-side web part",
"description": "Client-side web parts are client-side components that run in the context of a SharePoint page. Client-side web parts can be deployed to SharePoint environments that support the SharePoint Framework. You can also use modern JavaScript web frameworks, tools, and libraries to build them.",
"url": "https://docs.microsoft.com/en-us/sharepoint/dev/spfx/web-parts/get-started/build-a-hello-world-web-part"
}
]
}
]

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,18 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
"version": "2.0",
"bundles": {
"chat-gpt-web-part": {
"components": [
{
"entrypoint": "./lib/webparts/chatGpt/ChatGptWebPart.js",
"manifest": "./src/webparts/chatGpt/ChatGptWebPart.manifest.json"
}
]
}
},
"externals": {},
"localizedResources": {
"ChatGptWebPartStrings": "lib/webparts/chatGpt/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-chat-gpt-message-extension",
"accessKey": "<!-- ACCESS KEY -->"
}

View File

@ -0,0 +1,51 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
"solution": {
"name": "react-chat-gpt-app-client-side-solution",
"id": "560953a2-d85c-41de-84f6-4def64002ea1",
"version": "1.0.0.1",
"includeClientSideAssets": true,
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"webApiPermissionRequests": [
{
"resource": "OpenAIFunctionsApp",
"scope": "user_impersonation"
},
{
"resource": "Microsoft Graph",
"scope": "ChatMessage.Send"
}
],
"developer": {
"name": "",
"websiteUrl": "",
"privacyUrl": "",
"termsOfUseUrl": "",
"mpnId": "Undefined-1.16.1"
},
"metadata": {
"shortDescription": {
"default": "react-chat-gpt-app"
},
"longDescription": {
"default": "react-chat-gpt-app"
},
"screenshotPaths": [],
"videoUrl": "",
"categories": []
},
"features": [
{
"title": "react-chat-gpt-message-extension Feature",
"description": "The feature that activates elements of the react-chat-gpt-app solution.",
"id": "9ce00a62-2201-471b-a003-5b56389ea028",
"version": "1.0.0.0"
}
]
},
"paths": {
"zippedPackage": "solution/react-chat-gpt-app.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://enter-your-SharePoint-site/_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,6 @@
{
"$schema": "https://raw.githubusercontent.com/s-KaiNet/spfx-fast-serve/master/schema/config.latest.schema.json",
"cli": {
"isLibraryComponent": false
}
}

View File

@ -0,0 +1,24 @@
/*
* User webpack settings file. You can add your own settings here.
* Changes from this file will be merged into the base webpack configuration file.
* This file will not be overwritten by the subsequent spfx-fast-serve calls.
*/
// you can add your project related webpack configuration here, it will be merged using webpack-merge module
// i.e. plugins: [new webpack.Plugin()]
const webpackConfig = {
}
// for even more fine-grained control, you can apply custom webpack settings using below function
const transformConfig = function (initialWebpackConfig) {
// transform the initial webpack config here, i.e.
// initialWebpackConfig.plugins.push(new webpack.Plugin()); etc.
return initialWebpackConfig;
}
module.exports = {
webpackConfig,
transformConfig
}

22
samples/react-chatGPT-app/gulpfile.js vendored Normal file
View File

@ -0,0 +1,22 @@
'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;
};
/* fast-serve */
const { addFastServe } = require("spfx-fast-serve-helpers");
addFastServe(build);
/* end of fast-serve */
build.initialize(require('gulp'));

70123
samples/react-chatGPT-app/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,57 @@
{
"name": "react-chat-gpt-message-extension",
"version": "0.0.1",
"private": true,
"engines": {
"node": ">=16.13.0 <17.0.0"
},
"main": "lib/index.js",
"scripts": {
"build": "gulp bundle",
"clean": "gulp clean",
"test": "gulp test",
"serve": "gulp bundle --custom-serve --max_old_space_size=4096 && fast-serve"
},
"dependencies": {
"@emotion/react": "^11.10.5",
"@fluentui/react-hooks": "^8.6.16",
"@mantine/core": "^5.10.3",
"@mantine/hooks": "^5.10.3",
"@mantine/notifications": "^5.10.3",
"@microsoft/microsoft-graph-types": "^2.26.0",
"@microsoft/sp-core-library": "1.16.1",
"@microsoft/sp-lodash-subset": "1.16.1",
"@microsoft/sp-office-ui-fabric-core": "1.16.1",
"@microsoft/sp-property-pane": "1.16.1",
"@microsoft/sp-webpart-base": "1.16.1",
"@types/markdown-it": "^12.2.3",
"adaptivecards": "^2.11.2",
"adaptivecards-templating": "^2.3.1",
"axios": "^1.3.2",
"date-fns": "^2.29.3",
"gpt3-tokenizer": "^1.1.5",
"jotai": "^2.0.0",
"markdown-it": "^13.0.1",
"office-ui-fabric-react": "^7.199.1",
"openai": "^3.1.0",
"react": "17.0.1",
"react-dom": "17.0.1",
"tslib": "2.3.1"
},
"devDependencies": {
"@microsoft/eslint-config-spfx": "1.16.1",
"@microsoft/eslint-plugin-spfx": "1.16.1",
"@microsoft/rush-stack-compiler-4.5": "0.2.2",
"@microsoft/sp-build-web": "1.16.1",
"@microsoft/sp-module-interfaces": "1.16.1",
"@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-plugin-react-hooks": "4.3.0",
"gulp": "4.0.2",
"typescript": "4.5.5",
"spfx-fast-serve-helpers": "~1.16.0"
}
}

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,5 @@
import { atom } from 'jotai';
import { IGlobalState } from '../models/IGlobalState';
export const globalState = atom<IGlobalState>({} as IGlobalState);

View File

@ -0,0 +1 @@
export * from './globalState';

View File

@ -0,0 +1,33 @@
/* eslint-disable @typescript-eslint/no-floating-promises */
import * as React from 'react';
import { Provider } from 'jotai';
import { ThemeProvider } from 'office-ui-fabric-react/lib/Theme';
import { MantineProvider } from '@mantine/core';
import { NotificationsProvider } from '@mantine/notifications';
import {
useMantineThemeFromFluentTheme,
} from '../../hooks/useMantineThemeFromFluentTheme';
import { IChatGptProps } from '../../models/IChatGptProps';
import { ChatGptControl } from './ChatGptControl';
export const ChatGpt: React.FunctionComponent<IChatGptProps> = (props: React.PropsWithChildren<IChatGptProps>) => {
const { theme } = props;
const mantineTheme = useMantineThemeFromFluentTheme(theme);
return (
<>
<MantineProvider theme={mantineTheme} withCSSVariables={false}>
<ThemeProvider theme={theme}>
<Provider>
<NotificationsProvider position="top-right" zIndex={2077}>
<ChatGptControl {...props} />
</NotificationsProvider>
</Provider>
</ThemeProvider>
</MantineProvider>
</>
);
};

View File

@ -0,0 +1,100 @@
/* eslint-disable @typescript-eslint/no-floating-promises */
import * as React from 'react';
import { useAtom } from 'jotai';
import { Stack } from 'office-ui-fabric-react';
import { globalState } from '../../atoms/globalState';
import {
APPID_TENANT_PROPERTY,
AZURE_FUNCTION_URL_TENANT_PROPERTY,
} from '../../constants/constants';
import { useSpAPI } from '../../hooks/useSpAPI';
import { IChatGptProps } from '../../models/IChatGptProps';
import { ErrorMessage } from '../ErrorMessage/ErrorMessage';
import { Header } from '../Header/Header';
import { Loading } from '../LoadingAnswer/Loading';
import { RenderMessages } from '../RenderMessages/RenderMessages';
import {
RenderPreviewChatInfo,
} from '../RenderPreviewChatInfo/RenderPreviewChatInfo';
import { useChatGptStyles } from './useChatGptStyles';
export const ChatGptControl: React.FunctionComponent<IChatGptProps> = (
props: React.PropsWithChildren<IChatGptProps>
) => {
const { context } = props;
const [appGlobalState, setAppGlobalState] = useAtom(globalState);
const { containerStyles } = useChatGptStyles();
const { hasTeamsContext, chatId } = appGlobalState;
const { getTenantProperty } = useSpAPI(context);
const [isLoading, setIsLoading] = React.useState(true);
const [error, setError] = React.useState<Error | undefined>(undefined);
const isInChat = React.useMemo((): boolean => {
return hasTeamsContext && !!chatId;
}, [chatId, hasTeamsContext]);
const isPreviewChatId = React.useMemo((): boolean => {
if (isInChat) {
return chatId.toLowerCase().indexOf("preview") !== -1;
}
return false;
}, [chatId, isInChat]);
React.useEffect(() => {
setAppGlobalState((prevState) => {
return { ...prevState, ...props };
});
}, [props]);
React.useEffect(() => {
(async () => {
try {
const appId = await getTenantProperty(APPID_TENANT_PROPERTY);
const OpenAIAzureFunctionUrl = await getTenantProperty(AZURE_FUNCTION_URL_TENANT_PROPERTY);
if (!appId && !OpenAIAzureFunctionUrl) {
throw new Error("ChatGpt is not configured");
}
setError(undefined);
setAppGlobalState((preveState) => {
return { ...preveState, appId, AzureFunctionUrl: OpenAIAzureFunctionUrl };
});
} catch (error) {
if (!DEBUG) {
console.log("[ChatGptControl] Error: ", error.message);
}
setError(error);
} finally {
setIsLoading(false);
}
})();
}, [getTenantProperty, setAppGlobalState]);
if (isLoading) {
return (
<Stack horizontal horizontalAlign="center" tokens={{ childrenGap: 30 }}>
<Loading isLoading={isLoading} />
</Stack>
);
}
if (error) {
const showError = !!error;
const errorMessage = error?.message;
return (
<Stack horizontal horizontalAlign="center" tokens={{ childrenGap: 30 }}>
<ErrorMessage errorMessage={errorMessage} showError={showError} />
</Stack>
);
}
return (
<>
<Stack tokens={{ childrenGap: 20 }} styles={containerStyles}>
<Header isInChat={isInChat} />
<RenderPreviewChatInfo isPreviewChatId={isPreviewChatId} />
<RenderMessages isShowMessages={!isPreviewChatId} />
</Stack>
</>
);
};

View File

@ -0,0 +1,2 @@
export * from './ChatGpt';

View File

@ -0,0 +1,338 @@
/* eslint-disable @typescript-eslint/explicit-function-return-type */
import * as React from 'react';
import { useAtom } from 'jotai';
import { DefaultEffects } from 'office-ui-fabric-react/lib/Styling';
import { ITextFieldStyles } from 'office-ui-fabric-react/lib/TextField';
import { IButtonStyles } from '@fluentui/react/lib/Button';
import { IStackStyles } from '@fluentui/react/lib/Stack';
import {
mergeStyles,
mergeStyleSets,
} from '@fluentui/react/lib/Styling';
import { ITextStyles } from '@fluentui/react/lib/Text';
import { globalState } from '../../atoms';
import { IGlobalState } from '../../models/IGlobalState';
export const useChatGptStyles = () => {
const [appGlobalState] = useAtom(globalState);
const { theme, hasTeamsContext, chatId } = appGlobalState || ({} as IGlobalState);
const isInChat = React.useMemo(() => {
return hasTeamsContext && chatId;
}, [chatId, hasTeamsContext]);
const nameStyles: ITextStyles = React.useMemo(() => {
return {
root: {
color: theme?.semanticColors?.bodyText,
fontWeight: 700,
},
};
}, [theme]);
const containerStyles: IStackStyles = React.useMemo(() => {
return {
root: {
borderRadius: isInChat ? "unset" : 8,
borderWidth: isInChat ? "unset" : 1,
borderStyle: isInChat ? "unset" : "solid",
borderColor: isInChat ? "unset" : theme?.palette?.neutralLighter,
borderTopStyle: isInChat ? "solid" : "none",
borderTopWidth: isInChat ? 1 : "unset",
borderTopColor: isInChat ? theme?.palette.neutralQuaternaryAlt : "unset",
marginTop: isInChat ? 20 : 0,
maxWidth: 700,
width: "100%",
height: 600,
overflowY: "auto",
overflowX: "hidden",
/* backgroundColor: theme?.palette?.neutralLighterAlt, */
boxShadow: isInChat ? "unset" : DefaultEffects.elevation4,
wordBreak: "break-word",
paddingBottom: 20,
},
};
}, [theme]);
const scrollableContainerStyles: IStackStyles = React.useMemo(() => {
return {
root: {
padding: 10,
height: 500,
overflowY: "auto",
overflowX: "hidden",
"::-webkit-scrollbar-thumb": {
backgroundColor: theme?.palette.themeLight,
},
"::-webkit-scrollbar": {
height: 10,
width: 7,
},
"scrollbar-color": theme?.semanticColors.bodyFrameBackground,
"scrollbar-width": "thin",
},
};
}, [theme]);
const answerContainerStyles: IStackStyles = React.useMemo(() => {
return {
root: {
width: "100%",
":nth-child(1n)": {
marginTop: 20,
},
},
};
}, [theme]);
const questionStyles: IStackStyles = React.useMemo(() => {
return {
root: {
marginTop: 20,
paddingTop: 10,
paddingLeft: 20,
paddingRight: 20,
paddingBottom: 10,
width: "fit-content",
boxShadow: DefaultEffects.elevation4,
backgroundColor: theme?.palette?.neutralLight,
maxWidth:470,
},
};
}, [theme]);
const answerStyles: IStackStyles = React.useMemo(() => {
return {
root: {
paddingTop: 10,
paddingLeft: 20,
paddingRight: 20,
paddingBottom: 10,
boxShadow: DefaultEffects.elevation4,
width: "fit-content",
/* backgroundColor: theme?.semanticColors?.bodyBackground, */
backgroundColor: theme?.palette?.neutralLighterAlt,
},
};
}, [theme]);
const stackBottomStyles: Partial<IStackStyles> = React.useMemo(() => {
return {
root: {
padding: "0px 16px",
color: theme?.semanticColors?.bodySubtext,
position: "absolute",
bottom: 10,
width: "100%",
},
};
}, [theme]);
const imageOAtyles: IStackStyles = React.useMemo(() => {
return {
root: {
width: 32,
height: 32,
borderRadius: "50%",
backgroundColor: theme?.palette?.themePrimary,
color: theme?.palette?.white,
textAlign: "center",
verticalAlign: "middle",
fontWeight: 700,
fontSize: 12,
lineHeight: 36,
},
};
}, [theme]);
const headerContainertyles: IStackStyles = React.useMemo(() => {
return {
root: {
backgroundColor: theme?.palette.neutralLighterAlt,
},
};
}, [theme]);
const buttonIconStyles: IButtonStyles = React.useMemo(() => {
return {
root: { transform: "rotate(-30deg)" },
};
}, [theme]);
const messageChatInfoStyles: ITextStyles = React.useMemo(() => {
return {
root: {
color: theme?.semanticColors?.bodySubtext,
fontWeight: 700,
},
};
}, [theme]);
const messageChatInfoContainerStyles: IStackStyles = React.useMemo(() => {
return {
root: { height: "100%" },
};
}, [theme]);
const textFieldStyles: Partial<ITextFieldStyles> = React.useMemo(() => {
return {
root: { marginBottom: 7, width: "100%", minHeight: 32 },
field: {
padding: 10,
minHeight: 32,
height: 40,
borderStyle: "solid",
borderWidth: 1,
borderColor: theme?.palette.neutralQuaternaryAlt,
borxerRadius: 5,
":focus": {
borderBottomStyle: "solid",
borderBottomWidth: 2,
borderBottomColor: theme?.palette.themePrimary,
},
},
fieldGroup: {
minHeight: 32,
":after": {
minHeight: 32,
content: "",
borderBottomStyle: "solid",
borderBottomWidth: 2,
borderBottomColor: theme?.palette.themePrimary,
},
borderWidth: 0,
},
wrapper: {
minHeight: 32,
":focus": {
borderBottomStyle: "solid",
borderBottomWidth: 2,
borderBottomColor: theme?.palette.themePrimary,
},
},
suffix: {
backgroundColor: theme?.palette.neutralLight,
},
};
}, [theme]);
const sendButtonStyles: IButtonStyles = React.useMemo(() => {
return {
root: {
backgroundColor: theme?.palette.themePrimary,
color: theme?.palette.white,
width: 50,
minWidth: 50,
height: 32,
borderStyle: "solid",
borderWidth: 1,
borderColor: theme?.palette.neutralQuaternaryAlt,
},
rootHovered: {
backgroundColor: theme?.palette.themeDark,
color: theme?.palette.white,
borderStyle: "solid",
borderWidth: 1,
borderColor: theme?.palette.themePrimary,
},
rootPressed: {
backgroundColor: theme?.palette.themeDark,
color: theme?.palette.white,
},
};
}, [theme]);
const messageErrorContainerStyles: IStackStyles = React.useMemo(() => {
return {
root: {
width:'100%',
},
};
}, [theme]);
const controlStyles = React.useMemo(() => {
return mergeStyleSets({
imageOPAILogo: mergeStyles({
borderRadius: "50%",
backgroundColor: theme?.palette?.themePrimary,
color: theme?.palette?.white,
textAlign: "center",
verticalAlign: "middle",
fontWeight: 700,
fontSize: 12,
lineHeight: 36,
}),
scrollableContainerStyles: mergeStyles({
paddingLeft: 20,
paddingRight: 20,
paddingBottom: 10,
height: 500,
overflowY: "auto",
overflowX: "hidden",
"::-webkit-scrollbar-thumb": {
backgroundColor: theme?.palette.themeLight,
width: 5,
},
"::-webkit-scrollbar": {
height: 10,
width: 5,
},
"scrollbar-color": theme?.semanticColors.bodyFrameBackground,
"scrollbar-width": "thin",
}),
answerStyles: {
whiteSpace: "pre-wrap",
overflowWrap: "break-word",
wordBreak: "break-word",
paddingTop:10
},
bigLogo: {
padding: 1,
backgroundColor: theme?.palette?.white,
width: 92,
height: 92,
border: "2px solid",
borderColor: theme?.palette?.neutralLighter,
borderRadius: "50%",
objectFit: "cover",
color: theme?.palette.themePrimary,
textAlign: "center",
verticalAlign: "middle",
fontWeight: 700,
},
separator: mergeStyles({
height: "1px",
backgroundColor: theme?.palette?.neutralLight,
opacity: theme?.isInverted ? "0.2" : "1",
width: "100%",
}),
});
}, [theme]);
return {
scrollableContainerStyles,
containerStyles,
sendButtonStyles,
controlStyles,
textFieldStyles,
stackBottomStyles,
nameStyles,
imageOAtyles,
questionStyles,
answerStyles,
answerContainerStyles,
headerContainertyles,
buttonIconStyles,
messageChatInfoStyles,
messageChatInfoContainerStyles,
messageErrorContainerStyles
};
};

View File

@ -0,0 +1,28 @@
import * as React from 'react';
import {
MessageBar,
MessageBarType,
} from 'office-ui-fabric-react/lib/MessageBar';
import { Stack } from 'office-ui-fabric-react/lib/Stack';
import { IErrorMessageProps } from '../../models/IErrorMessageProps';
import { useChatGptStyles } from '../ChatGpt/useChatGptStyles';
export const ErrorMessage: React.FunctionComponent<IErrorMessageProps> = (
props: React.PropsWithChildren<IErrorMessageProps>
) => {
const { showError, errorMessage, children } = props;
const { messageErrorContainerStyles} = useChatGptStyles();
if (!showError) return null;
return (
<>
<Stack verticalAlign="center" tokens={{ padding: 10, childrenGap: 10 }} styles={messageErrorContainerStyles}>
<MessageBar messageBarType={MessageBarType.error} isMultiline={true}>
{errorMessage}
{children}
</MessageBar>
</Stack>
</>
);
};

View File

@ -0,0 +1,38 @@
import * as React from 'react';
import * as strings from 'ChatGptWebPartStrings';
import {
Stack,
Text,
} from 'office-ui-fabric-react';
import { useChatGptStyles } from '../ChatGpt/useChatGptStyles';
import { OpenAIImage } from '../OpenAIImage/OpenAIImage';
export interface IHeaderProps {
isInChat: boolean;
}
export const Header: React.FunctionComponent<IHeaderProps> = (props: React.PropsWithChildren<IHeaderProps>) => {
const {headerContainertyles ,nameStyles, controlStyles } = useChatGptStyles();
const { isInChat } = props;
if (isInChat) return null;
return (
<>
<Stack horizontalAlign="stretch" tokens={{ childrenGap: 10 }} styles={headerContainertyles}>
<Stack horizontal horizontalAlign="start" tokens={{ padding: 15, childrenGap: 15 }} >
<OpenAIImage showImageOnly />
<Stack.Item align="center">
<Text variant="large" block styles={nameStyles}>
Open AI
</Text>
<Text variant="small" block>
{strings.ChatGPTAppPoweredByLabel}
</Text>
</Stack.Item>
</Stack>
<div className={controlStyles.separator} />
</Stack>
</>
);
};

View File

@ -0,0 +1,21 @@
import * as React from 'react';
import { Stack } from 'office-ui-fabric-react';
import { Loader } from '@mantine/core';
export interface ILoadingProps {
isLoading: boolean;
}
export const Loading: React.FunctionComponent<ILoadingProps> = (props: React.PropsWithChildren<ILoadingProps>) => {
const { isLoading } = props;
if (!isLoading) return null;
return (
<>
<Stack tokens={{padding: 5}} horizontalAlign={"start"}>
<Loader variant="dots" />
</Stack>
</>
);
};

View File

@ -0,0 +1,35 @@
/* eslint-disable @typescript-eslint/no-var-requires */
import * as React from 'react';
import * as strings from 'ChatGptWebPartStrings';
import { Stack } from 'office-ui-fabric-react/lib/Stack';
import { Text } from 'office-ui-fabric-react/lib/Text';
import { IOpenAIImageProps } from '../../models/IOpenAIImageProps';
import { useChatGptStyles } from '../ChatGpt/useChatGptStyles';
const logo = require("../../../assets/ChatGPTLogo.png");
export const OpenAIImage: React.FunctionComponent<IOpenAIImageProps> = (
props: React.PropsWithChildren<IOpenAIImageProps>
) => {
const { nameStyles, controlStyles } = useChatGptStyles();
const { showImageOnly, width, height } = props;
return (
<Stack tokens={{ childrenGap: 10 }} horizontalAlign="start" verticalAlign="center" horizontal>
<img
src={logo}
alt="Open AI"
className={controlStyles.imageOPAILogo}
style={{ width: width ?? 32, height: height ?? 32 }}
/>
{showImageOnly ? null : (
<Text variant="large" block styles={nameStyles}>
{strings.CgatGPTAppOpenAILabel}
</Text>
)}
</Stack>
);
};

View File

@ -0,0 +1,103 @@
import * as React from 'react';
import * as strings from 'ChatGptWebPartStrings';
import { format } from 'date-fns';
import { useAtom } from 'jotai';
import {
Stack,
StackItem,
Text,
} from 'office-ui-fabric-react';
import { showNotification } from '@mantine/notifications';
import { CARD } from '../../adaptiveCards/chatGPTAnswerCard';
import { globalState } from '../../atoms';
import { useAdaptiveCardsUtils } from '../../hooks/useAdaptiveCardsUtils';
import { useGraphAPI } from '../../hooks/useGraphAPI';
import { useSendMessageToTeams } from '../../hooks/useSendMessageToTeams';
import { IAdaptativeCardData } from '../../models/IAdaptivecardData';
import { IRenderAnswerProps } from '../../models/IRenderAnswerProps';
import { useChatGptStyles } from '../ChatGpt/useChatGptStyles';
import { ErrorMessage } from '../ErrorMessage/ErrorMessage';
import { OpenAIImage } from '../OpenAIImage/OpenAIImage';
import { SendMessageToChat } from '../SendMessageToChat/SendMessageToChat';
export const RenderAnswer: React.FunctionComponent<IRenderAnswerProps> = (
props: React.PropsWithChildren<IRenderAnswerProps>
) => {
const { answer } = props;
const { answerStyles, nameStyles, answerContainerStyles, controlStyles } = useChatGptStyles();
const [appGlobalState] = useAtom(globalState);
const { lastConversation, context, chatId } = appGlobalState;
const [error, setError] = React.useState<Error | undefined>(undefined);
const { sendMessage } = useGraphAPI(context);
const { createAdaptiveCard } = useAdaptiveCardsUtils();
const { sendAdativeCardToUsers } = useSendMessageToTeams(context);
const hasError = React.useMemo(() => error !== undefined, [error]);
const onSendMessageToChat = React.useCallback(async () => {
if (answer && chatId) {
try {
const cardData: IAdaptativeCardData = { date: format(new Date(), "PPpp"), answer: answer };
const card = createAdaptiveCard(cardData, CARD);
console.log("carddata", cardData);
console.log("card", card);
await sendAdativeCardToUsers(card, cardData, chatId);
showNotification({
title: strings.ChatGPTAppNotificationTitle,
message: strings.ChatGPTAppNotificationMessage,
autoClose: 3500,
});
} catch (error) {
if (DEBUG) {
console.log("[RenderAnswer.sendMessageToChat], error:", error.message);
}
setError(error);
}
}
}, [answer, chatId, sendMessage, sendAdativeCardToUsers, createAdaptiveCard]);
const islastConversation = React.useMemo(() => lastConversation === "answer", [lastConversation]);
return (
<>
<Stack
tokens={{ childrenGap: 10 }}
horizontalAlign="start"
verticalAlign="start"
horizontal
styles={answerContainerStyles}
>
{islastConversation ? null : (
<Stack styles={{ root: { paddingTop: 6 } }}>
<OpenAIImage showImageOnly={true} width={26} height={26} />
</Stack>
)}
<Stack styles={answerStyles} tokens={{ childrenGap: 5 }} horizontalAlign={"stretch"}>
<Stack horizontal horizontalAlign="start" verticalAlign="center" tokens={{ childrenGap: 10 }}>
<Text variant="medium" block styles={nameStyles}>
{strings.CgatGPTAppOpenAILabel}
</Text>
<Text variant="small" block>
{format(new Date(), "HH:mm")}
</Text>
<Stack horizontal horizontalAlign="end" grow={3}>
<SendMessageToChat onSendMessage={onSendMessageToChat} />
</Stack>
</Stack>
<Stack horizontalAlign="start" tokens={{ childrenGap: 10 }}>
<div
dangerouslySetInnerHTML={{ __html: answer?.replace("\n\n", " ") }}
className={controlStyles.answerStyles}
/>
<StackItem align="stretch">
<ErrorMessage errorMessage={error?.message} showError={hasError} />
</StackItem>
</Stack>
</Stack>
</Stack>
</>
);
};

View File

@ -0,0 +1,134 @@
import * as React from 'react';
import { useAtom } from 'jotai';
import { ActionButton } from 'office-ui-fabric-react/lib/Button';
import { IIconProps } from 'office-ui-fabric-react/lib/Icon';
import { Stack } from 'office-ui-fabric-react/lib/Stack';
import { TextField } from 'office-ui-fabric-react/lib/TextField';
import { globalState } from '../../atoms/globalState';
import { useChatGpt } from '../../hooks';
import { useChatGptStyles } from '../ChatGpt/useChatGptStyles';
import { ErrorMessage } from '../ErrorMessage/ErrorMessage';
import { Loading } from '../LoadingAnswer/Loading';
import { RenderAnswer } from '../RenderAnswer/RenderAnswer';
import { RenderQuestion } from '../RenderQuestion/RenderQuestion';
export interface IRenderMessagesProps {
isShowMessages: boolean;
}
export const RenderMessages: React.FunctionComponent<IRenderMessagesProps> = (
props: React.PropsWithChildren<IRenderMessagesProps>
) => {
const { isShowMessages } = props;
const [appGlobalState] = useAtom(globalState);
const { context, appId, AzureFunctionUrl } = appGlobalState;
const { textFieldStyles, controlStyles, buttonIconStyles } = useChatGptStyles();
const [conversation, setConversation] = React.useState<React.ReactNode[]>([]);
const [textToAsk, setTextToAsk] = React.useState<string>("");
const [isLoading, setIsLoading] = React.useState<boolean>(false);
const { getCompletion } = useChatGpt(context, appId, AzureFunctionUrl);
const scrollRef = React.useRef<HTMLDivElement>(null);
const [error, setError] = React.useState<Error | undefined>(undefined);
const hasError = React.useMemo(() => error !== undefined, [error]);
const onTextChange = React.useCallback(
(ev: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>, newText: string) => {
setTextToAsk(newText);
},
[]
);
const addQuestion = React.useCallback(
(question: string) => {
const newQuestion = <RenderQuestion question={question} key={conversation.length + 1} />;
setConversation((prev) => {
return [...prev, newQuestion];
});
setTimeout(() => {
scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: "smooth" });
}, 100);
},
[conversation]
);
const addAnswer = React.useCallback(
(answer: string) => {
const newAnswer = <RenderAnswer answer={answer} key={conversation.length + 1} />;
setConversation((prev) => {
return [...prev, newAnswer];
});
setTimeout(() => {
scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: "smooth" });
}, 100);
},
[conversation]
);
const onSubmit = React.useCallback(async () => {
try {
setIsLoading(true);
addQuestion(textToAsk);
const response = await getCompletion(textToAsk);
addAnswer(response);
setError(undefined);
} catch (error) {
setError(error);
} finally {
setIsLoading(false);
setTextToAsk("");
}
}, [textToAsk]);
const actionButtonIconProps: IIconProps = React.useMemo(() => {
return { iconName: "send", styles: buttonIconStyles };
}, [buttonIconStyles]);
const onButtonClick = React.useCallback(
async (ev) => {
await onSubmit();
},
[onSubmit]
);
if (!isShowMessages) {
return null;
}
return (
<>
<div className={controlStyles.scrollableContainerStyles} ref={scrollRef}>
{conversation}
</div>
<Stack tokens={{ padding: 20, childrenGap: 10 }}>
<Loading isLoading={isLoading} />
<Stack horizontal tokens={{ childrenGap: 5 }} >
{hasError ? (
<ErrorMessage errorMessage={error?.message} showError={hasError} />
) : (
<>
<TextField
multiline
value={textToAsk}
resizable={false}
autoAdjustHeight
styles={textFieldStyles}
onChange={onTextChange}
/>
<Stack horizontalAlign="end">
<ActionButton
disabled={!textToAsk.length || isLoading}
iconProps={actionButtonIconProps}
allowDisabledFocus
onClick={onButtonClick}
/>
</Stack>
</>
)}
</Stack>
</Stack>
</>
);
};

View File

@ -0,0 +1,37 @@
import * as React from 'react';
import * as strings from 'ChatGptWebPartStrings';
/* eslint-disable @typescript-eslint/no-var-requires */
import { Stack } from 'office-ui-fabric-react/lib/Stack';
import { Text } from 'office-ui-fabric-react/lib/Text';
import {
IRenderPreviewChatInfoProps,
} from '../../models/IRenderPreviewChatInfoProps';
import { useChatGptStyles } from '../ChatGpt/useChatGptStyles';
const logo = require("../../../assets/ChatGPTLogo.png");
export const RenderPreviewChatInfo: React.FunctionComponent<IRenderPreviewChatInfoProps> = (
props: React.PropsWithChildren<IRenderPreviewChatInfoProps>
) => {
const { controlStyles, messageChatInfoStyles, messageChatInfoContainerStyles} = useChatGptStyles();
const { isPreviewChatId } = props;
if (!isPreviewChatId) { return null; }
return (
<>
<Stack verticalAlign="center" tokens={{ childrenGap: 30 }} styles={messageChatInfoContainerStyles}>
<Stack.Item align="center">
<img src={logo} className={controlStyles.bigLogo} alt="Open AI" />
</Stack.Item>
<Stack.Item align="center">
<Text variant="mediumPlus" styles={messageChatInfoStyles}>
{strings.ChatGPTAppPreviewChatInfoMessage}
</Text>
</Stack.Item>
</Stack>
</>
);
};

View File

@ -0,0 +1,32 @@
import * as React from 'react';
import { format } from 'date-fns';
import {
FontWeights,
Stack,
Text,
} from 'office-ui-fabric-react';
import { IRenderQuestionProps } from '../../models/IRenderQuestionProps';
import { useChatGptStyles } from '../ChatGpt/useChatGptStyles';
export const RenderQuestion: React.FunctionComponent<IRenderQuestionProps> = (
props: React.PropsWithChildren<IRenderQuestionProps>
) => {
const { questionStyles } = useChatGptStyles();
const { question } = props;
return (
<>
<Stack horizontalAlign="end" >
<Stack tokens={{ childrenGap: 10 }} styles={questionStyles}>
<Text variant="small" block styles={{root: {fontWeight: FontWeights.semilight }}}>
{format(new Date(), "HH:mm")}
</Text>
<Text variant="medium" block>
{question}
</Text>
</Stack>
</Stack>
</>
);
};

View File

@ -0,0 +1,48 @@
import * as React from 'react';
import { useAtom } from 'jotai';
import { IconButton } from 'office-ui-fabric-react/lib/Button';
import { IIconProps } from 'office-ui-fabric-react/lib/Icon';
import { TooltipHost } from 'office-ui-fabric-react/lib/Tooltip';
import { useId } from '@fluentui/react-hooks';
import { globalState } from '../../atoms/globalState';
export interface ISendMessageProps {
onSendMessage: () => void;
}
export const SendMessageToChat: React.FunctionComponent<ISendMessageProps> = (
props: React.PropsWithChildren<ISendMessageProps>
) => {
const [appGlobalState] = useAtom(globalState);
const { hasTeamsContext, chatId, } = appGlobalState;
const { onSendMessage } = props;
const shareIcon: IIconProps = React.useMemo(() => {return { iconName: "Share" }}, []);
const calloutProps = React.useMemo(() => { return { gapSpace: 0 }}, []);
const tooltipId = useId("tooltip");
const isInChat = React.useMemo(() => {
return hasTeamsContext && chatId;
}, [chatId, hasTeamsContext]);
if (!isInChat) {
return null;
}
return (
<>
<TooltipHost
content="Share this answer on chat"
id={tooltipId}
calloutProps={calloutProps}
setAriaDescribedBy={false}
>
<IconButton iconProps={shareIcon} aria-label="share" onClick={onSendMessage}/>
</TooltipHost>
</>
);
};

View File

@ -0,0 +1 @@
export * from './ChatGpt';

View File

@ -0,0 +1,2 @@
export const APPID_TENANT_PROPERTY = "OpenAIFunctionsAppId";
export const AZURE_FUNCTION_URL_TENANT_PROPERTY = "OpenAIAzureFunctionUrl";

View File

@ -0,0 +1 @@
export * from './useChatGpt';

View File

@ -0,0 +1,41 @@
/* eslint-disable @typescript-eslint/explicit-function-return-type */
/* eslint-disable @typescript-eslint/no-explicit-any */
import * as React from 'react';
import * as adaptiveCards from 'adaptivecards';
import * as adaptativeCardTemplating from 'adaptivecards-templating';
import * as markdownit from 'markdown-it/lib';
import { isEmpty } from '@microsoft/sp-lodash-subset';
const onProcessMarkdownHandler = (md:any, result: { outputHtml: string; didProcess: boolean; }) => {
// Don't stop parsing if there is invalid Markdown
try {
result.outputHtml = new markdownit().render(md);
result.didProcess = true;
}
catch (error) {
console.error("Error parsing Markdown", error);
result.didProcess = false;
}
};
export const useAdaptiveCardsUtils = function () {
const createAdaptiveCard = React.useCallback((adaptiveCardData, card) => {
const adaptiveCardToRender = new adaptiveCards.AdaptiveCard();
adaptiveCardToRender.version = new adaptiveCards.Version(1, 3);
adaptiveCards.AdaptiveCard.onProcessMarkdown = onProcessMarkdownHandler;
if (isEmpty(adaptiveCardData)) return undefined;
const template = new adaptativeCardTemplating.Template(card);
const cardPayload = template.expand({
$root: { ...adaptiveCardData },
});
// Parse the card payloa
adaptiveCardToRender.parse(cardPayload);
const adpativeCard = adaptiveCardToRender.toJSON();
// save on global state
return adpativeCard;
}, []);
return { createAdaptiveCard: createAdaptiveCard };
};

View File

@ -0,0 +1,54 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
import * as React from 'react';
/* eslint-disable @typescript-eslint/explicit-function-return-type */
import { BaseComponentContext } from '@microsoft/sp-component-base';
import {
AadHttpClient,
IHttpClientOptions,
} from '@microsoft/sp-http';
/* const APPID = "6b4a20b2-bf2f-4cbb-a162-af960a40c2dc";
const AZURE_FUNCTION_URL = "https://openaifunctionsapp.azurewebsites.net/api/OpenAICompletion"; */
export const useChatGpt = (context: BaseComponentContext, appId: string, AzureFunctionUrl: string) => {
const client = React.useMemo(() => {
if (context) {
return async () => {
const client = await context.aadHttpClientFactory.getClient(appId);
return client;
};
}
return undefined;
}, [context]);
const getCompletion = React.useCallback(
async (query: string): Promise<string> => {
try {
if (!client) return;
const options: IHttpClientOptions = {
headers: { "Content-Type": "application/json;odata=verbose", Accept: "application/json;odata=verbose" },
mode: "cors",
body: JSON.stringify({ prompt: query }),
method: "POST",
};
const response = await (await client()).post(AzureFunctionUrl, AadHttpClient.configurations.v1, options);
const answer = await response.json();
if (response.status === 200) {
return answer?.choices[0].text;
} else {
console.log("[getCompletion] error:", answer);
throw new Error("Error on executing the request, please try again later.");
}
} catch (error) {
if (!DEBUG) {
console.log("[getCompletion] error:", error);
}
throw error;
}
},
[client]
);
return { getCompletion };
};

View File

@ -0,0 +1,34 @@
import * as React from 'react';
/* eslint-disable no-unused-expressions */
/* eslint-disable @typescript-eslint/explicit-function-return-type */
import {
Chat,
ChatMessage,
} from '@microsoft/microsoft-graph-types';
import { BaseComponentContext } from '@microsoft/sp-component-base';
export const useGraphAPI = (context: BaseComponentContext) => {
const sendMessage = React.useCallback(async (chatId: string, message: string):Promise<ChatMessage> => {
const client = await context.msGraphClientFactory.getClient("3");
const response:ChatMessage = await client.api(`/chats/${chatId}/messages`)
.post({
body: {
content: `${message} (source: ChatGPT)` ,
},
});
return response;
},[context]);
const getChatInfo = React.useCallback(async (chatId:string):Promise<Chat> => {
const client = await context.msGraphClientFactory.getClient("3");
const response:Chat = await client.api(`/chats/${chatId}?$expand=members`)
.get();
return response;
},[context]);
return {sendMessage, getChatInfo}
};

View File

@ -0,0 +1,87 @@
import * as React from 'react';
import {
Depths,
MotionTimings,
} from 'office-ui-fabric-react';
import { MantineThemeOverride } from '@mantine/core';
import { IReadonlyTheme } from '@microsoft/sp-component-base';
export function useMantineThemeFromFluentTheme(theme: IReadonlyTheme): MantineThemeOverride {
const mantineTheme: MantineThemeOverride = React.useMemo(() => {
return {
black: theme.palette.black,
white: theme.palette.white,
defaultRadius: "sm",
colors: {
"gray": [
theme.palette.neutralLighterAlt,
theme.palette.neutralLighter,
theme.palette.neutralLight,
theme.palette.neutralQuaternaryAlt,
theme.palette.neutralTertiaryAlt,
theme.palette.neutralTertiary,
theme.palette.neutralSecondary,
theme.palette.neutralPrimaryAlt,
theme.palette.neutralPrimary,
theme.palette.neutralDark,
],
"theme": [
theme.palette.white,
theme.palette.themeLighterAlt,
theme.palette.themeLighter,
theme.palette.themeLight,
theme.palette.themeTertiary,
theme.palette.themeSecondary,
theme.palette.themePrimary,
theme.palette.themeDarkAlt,
theme.palette.themeDark,
theme.palette.themeDarker,
]
},
primaryColor: 'theme',
fontFamily: theme.fonts.medium.fontFamily,
headings: { fontFamily: theme.fonts.large.fontFamily },
transitionTimingFunction: MotionTimings.decelerate,
fontSizes: {
xs: 12,
sm: 14,
md: 16,
lg: 18,
xl: 20
},
spacing: {
xl: 32,
lg: 20,
md: 16,
sm: 8,
xs: 4
},
radius: {
xl: 32,
lg: 16,
md: 8,
sm: 4,
xs: 2
},
shadows: {
xl: theme.effects.elevation64,
lg: theme.effects.elevation16,
md: theme.effects.elevation8,
sm: theme.effects.elevation4,
xs: Depths.depth0
},
breakpoints: {
xl: 1366,
lg: 1024,
md: 640,
sm: 480,
xs: 320
}
}
}, [theme]);
return mantineTheme;
}

View File

@ -0,0 +1,136 @@
import * as React from 'react';
import { BaseComponentContext } from '@microsoft/sp-component-base';
import { Guid } from '@microsoft/sp-core-library';
import { isEmpty } from '@microsoft/sp-lodash-subset';
import { IAdaptativeCardData } from '../models/IAdaptivecardData';
import { HostedContents } from '../models/IChatMessage';
/* eslint-disable @typescript-eslint/explicit-function-return-type */
export const useSendMessageToTeams = (context: BaseComponentContext) => {
const graphClient = React.useMemo(() => {
return async () => {
const client = await context.msGraphClientFactory.getClient("3");
return client;
};
}, [context]);
const getHostedContent = React.useCallback(async (adaptiveCard: object, adaptiveCardData: IAdaptativeCardData) => {
try {
const hostedContents: HostedContents[] = [];
const adaptativeCardStringify = JSON.stringify(adaptiveCard);
// implement your logic to get the hosted content replace all the images with the hosted content Base64 string
return { hostedContents: hostedContents, adaptativeCardStringify: adaptativeCardStringify };
} catch (error) {
if (DEBUG) {
console.error(`[SendMessage.getHostedContent]: error=${error}`);
throw error;
}
}
}, []);
const getSendMessagePayload = React.useCallback(
async (adaptiveCard: object, adaptiveCardData: IAdaptativeCardData) => {
const guid = Guid.newGuid().toString();
const attachments = [];
if (isEmpty(adaptiveCard)) {
return;
}
const body = {
contentType: "html",
content: '<attachment id="'.concat(guid, '"></attachment>'),
};
const { hostedContents, adaptativeCardStringify } = await getHostedContent(adaptiveCard, adaptiveCardData);
attachments.push({
id: guid,
contentType: "application/vnd.microsoft.card.adaptive",
contentUrl: null,
name: null,
content: adaptativeCardStringify,
thumbnailUrl: null,
});
return { body: body, attachments: attachments, hostedContents: hostedContents };
},
[]
);
/* const createChatMembers = React.useCallback((receiverEmail: string) => {
try {
const currentUser = context.pageContext.user.email;
const chatMembers = [
{
"@odata.type": "#microsoft.graph.aadUserConversationMember",
roles: ["owner"],
"user@odata.bind": `https://graph.microsoft.com/v1.0/users('${currentUser}')`,
},
{
"@odata.type": "#microsoft.graph.aadUserConversationMember",
roles: ["owner"],
"user@odata.bind": `https://graph.microsoft.com/v1.0/users('${receiverEmail}')`,
},
];
return chatMembers;
} catch (error) {
if (DEBUG) {
console.error(`[SendMessage.createChatMembers]: error=${error}`);
throw error;
}
}
}, []); */
/*
const createChat = React.useCallback(
async (receiverEmail) => {
try {
const members = createChatMembers(receiverEmail);
const chat = await (await graphClient()).api("/chats").post({ chatType: "oneOnOne", members: members });
return chat;
} catch (error) {
if (DEBUG) {
console.error("[SendMessage.createChat]: error=", error);
throw error;
}
}
},
[graphClient]
);
*/
const sendMessage = React.useCallback(
async (adaptiveCard: object, adaptiveCardData: IAdaptativeCardData, chatId: string) => {
try {
const { body, attachments, hostedContents } = await getSendMessagePayload(adaptiveCard, adaptiveCardData);
const chatMessagePayload = {
subject: "OpenAI Answer",
body: body,
attachments: attachments,
hostedContents: hostedContents,
};
const chatMessage = await (await graphClient()).api(`/chats/${chatId}/messages`).post(chatMessagePayload);
return chatMessage;
} catch (error) {
if (DEBUG) {
console.error("[SendMessage]: error=", error);
throw error;
}
}
},
[graphClient]
);
const sendAdativeCardToUsers = React.useCallback(
async (adaptiveCard: object, adaptiveCardData: IAdaptativeCardData, chatId: string) => {
try {
await sendMessage(adaptiveCard, adaptiveCardData, chatId);
} catch (error) {
if (DEBUG) {
console.error(`[SendMessage.sendAdativeCardToUsers]: error=${error.message}`);
throw error;
}
}
},
[graphClient]
);
return { sendAdativeCardToUsers };
};

View File

@ -0,0 +1,47 @@
import * as React from 'react';
/* eslint-disable @typescript-eslint/explicit-function-return-type */
import { BaseComponentContext } from '@microsoft/sp-component-base';
import {
IHttpClientOptions,
SPHttpClient,
} from '@microsoft/sp-http';
export const useSpAPI = (context: BaseComponentContext) => {
const getAppCatalog = React.useCallback(async (): Promise<string> => {
const spHttpClient = context?.spHttpClient;
const tenant = window.location.hostname.split(".")[0];
const url = `https://${tenant}.sharepoint.com/_api/SP_TenantSettings_Current `;
const options: IHttpClientOptions = {
headers: { "Content-Type": "application/json;odata=verbose" },
mode: "cors",
method: "GET",
};
const results = await spHttpClient?.get(url, SPHttpClient.configurations.v1, options);
const response = await results?.json();
return response?.CorporateCatalogUrl;
}, [context]);
const getTenantProperty = React.useCallback(
async (key: string): Promise<string> => {
const spHttpClient = context?.spHttpClient;
const appCatalog = await getAppCatalog();
if (!appCatalog) return Promise.reject("appCatalog is undefined");
if (!key) return Promise.reject("key is undefined");
const url = `${appCatalog}/_api/web/GetStorageEntity('${key}')`;
const options: IHttpClientOptions = {
headers: { "Content-Type": "application/json;odata=verbose" },
mode: "cors",
method: "GET",
};
const results = await spHttpClient?.get(url, SPHttpClient.configurations.v1, options);
const response = await results?.json();
return response?.Value ?? undefined;
},
[context]
);
return { getAppCatalog, getTenantProperty };
};

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,4 @@
export interface IAdaptativeCardData {
date: string;
answer: string;
}

View File

@ -0,0 +1,15 @@
import { ITheme } from 'office-ui-fabric-react/lib/Styling';
import {
BaseComponentContext,
IReadonlyTheme,
} from '@microsoft/sp-component-base';
export interface IChatGptProps {
title: string;
isDarkTheme: boolean;
hasTeamsContext: boolean;
context: BaseComponentContext;
theme: ITheme | IReadonlyTheme ;
chatId: string;
}

View File

@ -0,0 +1,93 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
export interface HostedContents {
"@microsoft.graph.temporaryId": string;
contentBytes: string;
contentType: string;
}
export interface AddConversationMember {
"@odata.type": string;
"user@odata.bind": string;
visibleHistoryStartDateTime?: string;
roles: string[];
}
export interface AddConversationMemberResults {
"@odata.context": string;
id: string;
topic?: any;
createdDateTime: string;
lastUpdatedDateTime: string;
chatType: string;
}
export interface IChatMessage {
"@odata.context": string;
id: string;
replyToId?: any;
etag: string;
messageType: string;
createdDateTime: string;
lastModifiedDateTime: string;
lastEditedDateTime?: any;
deletedDateTime?: any;
subject: string;
summary?: any;
importance: string;
locale: string;
policyViolation?: any;
from: From;
body: Body;
attachments: Attachment[];
mentions: Mention[];
reactions: IReaction[];
}
export interface IReaction {
reactionType: string;
user: User;
createdDateTime: string;
}
export interface Mention {
id: number;
mentionText: string;
mentioned: From;
}
export interface Attachment {
id: string;
contentType: string;
contentUrl: string;
content?: any;
name: string;
thumbnailUrl?: any;
}
export interface Body {
contentType: string;
content: string;
}
export interface From {
application?: any;
device?: any;
conversation?: any;
user: User;
}
export interface User {
id: string;
displayName: string;
userIdentityType: string;
}
export interface HostedContents {
"@microsoft.graph.temporaryId": string;
contentBytes: string;
contentType: string;
}
export interface AddConversationMember {
"@odata.type": string;
"user@odata.bind": string;
visibleHistoryStartDateTime?: string;
roles: string[];
}
export interface AddConversationMemberResults {
"@odata.context": string;
id: string;
topic?: any;
createdDateTime: string;
lastUpdatedDateTime: string;
chatType: string;
}

View File

@ -0,0 +1,4 @@
export interface IErrorMessageProps {
showError: boolean;
errorMessage: string;
}

View File

@ -0,0 +1,16 @@
import { ITheme } from '@fluentui/react';
import {
BaseComponentContext,
IReadonlyTheme,
} from '@microsoft/sp-component-base';
export interface IGlobalState {
theme: ITheme | IReadonlyTheme ;
context: BaseComponentContext;
lastConversation?: string;
isDarkTheme: boolean;
hasTeamsContext: boolean;
chatId: string;
appId: string;
AzureFunctionUrl: string;
}

View File

@ -0,0 +1,5 @@
export interface IOpenAIImageProps {
showImageOnly?: boolean;
width?: number;
height?: number;
}

View File

@ -0,0 +1,3 @@
export interface IRenderAnswerProps {
answer: string;
}

View File

@ -0,0 +1,3 @@
export interface IRenderPreviewChatInfoProps {
isPreviewChatId: boolean;
}

View File

@ -0,0 +1,3 @@
export interface IRenderQuestionProps {
question: string;
}

View File

@ -0,0 +1,7 @@
export * from './IChatGptProps';
export * from './IErrorMessageProps';
export * from './IGlobalState';
export * from './IOpenAIImageProps';
export * from './IRenderAnswerProps';
export * from './IRenderPreviewChatInfoProps';
export * from './IRenderQuestionProps';

View File

@ -0,0 +1,24 @@
{
"themePrimary": "#6264a7",
"themeLighterAlt": "#f7f7fb",
"themeLighter": "#e1e1f1",
"themeLight": "#c8c9e4",
"themeTertiary": "#989ac9",
"themeSecondary": "#7173b0",
"themeDarkAlt": "#585a95",
"themeDark": "#4a4c7e",
"themeDarker": "#37385d",
"neutralLighterAlt": "#0b0b0b",
"neutralLighter": "#151515",
"neutralLight": "#252525",
"neutralQuaternaryAlt": "#2f2f2f",
"neutralQuaternary": "#373737",
"neutralTertiaryAlt": "#595959",
"neutralTertiary": "#c8c8c8",
"neutralSecondary": "#d0d0d0",
"neutralPrimaryAlt": "#dadada",
"neutralPrimary": "#ffffff",
"neutralDark": "#f4f4f4",
"black": "#f8f8f8",
"white": "#000000"
}

View File

@ -0,0 +1,24 @@
{
"themePrimary": "#7f85f5",
"themeLighterAlt": "#05050a",
"themeLighter": "#141527",
"themeLight": "#262849",
"themeTertiary": "#4c5093",
"themeSecondary": "#7075d7",
"themeDarkAlt": "#8c91f6",
"themeDark": "#9da2f7",
"themeDarker": "#b6baf9",
"neutralLighterAlt": "#282828",
"neutralLighter": "#313131",
"neutralLight": "#3f3f3f",
"neutralQuaternaryAlt": "#484848",
"neutralQuaternary": "#4f4f4f",
"neutralTertiaryAlt": "#6d6d6d",
"neutralTertiary": "#c8c8c8",
"neutralSecondary": "#d0d0d0",
"neutralPrimaryAlt": "#dadada",
"neutralPrimary": "#ffff",
"neutralDark": "#f4f4f4",
"black": "#ffffff",
"white": "#1f1f1f"
}

View File

@ -0,0 +1,24 @@
{
"themePrimary": "#6264a7",
"themeLighterAlt": "#f7f7fb",
"themeLighter": "#e1e1f1",
"themeLight": "#c8c9e4",
"themeTertiary": "#989ac9",
"themeSecondary": "#7173b0",
"themeDarkAlt": "#585a95",
"themeDark": "#4a4c7e",
"themeDarker": "#37385d",
"neutralLighterAlt": "#ecebe9",
"neutralLighter": "#e8e7e6",
"neutralLight": "#dedddc",
"neutralQuaternaryAlt": "#cfcecd",
"neutralQuaternary": "#c6c5c4",
"neutralTertiaryAlt": "#bebdbc",
"neutralTertiary": "#b5b4b2",
"neutralSecondary": "#9d9c9a",
"neutralPrimaryAlt": "#868482",
"neutralPrimary": "#252423",
"neutralDark": "#565453",
"black": "#3e3d3b",
"white": "#f3f2f1"
}

View File

@ -0,0 +1,14 @@
/* eslint-disable @typescript-eslint/explicit-function-return-type */
import GPT3Tokenizer from 'gpt3-tokenizer';
export const getTokens = (text: string, type?: "gpt3" | "codex"): string => {
const tokenizer = new GPT3Tokenizer({ type: type ?? "gpt3" }); // or 'codex'
const str = text;
const encoded: { bpe: number[]; text: string[] } = tokenizer.encode(str);
let stringResponse = "";
for (const token of encoded.text) {
stringResponse += token;
}
return stringResponse;
};

View File

@ -0,0 +1,2 @@
export * from "./OpenAIUtils";
export * from "./registrySVGIcons";

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,28 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "63fc66c0-10be-43fc-a499-b4a7cc8c0cae",
"alias": "ChatGptWebPart",
"componentType": "WebPart",
// The "*" signifies that the version should be taken from the package.json
"version": "*",
"manifestVersion": 2,
// If true, the component can only be installed on sites where Custom Script is allowed.
// Components that allow authors to embed arbitrary script code should set this to true.
// https://support.office.com/en-us/article/Turn-scripting-capabilities-on-or-off-1f2c515f-5d7e-448a-9fd7-835da935584f
"requiresCustomScript": false,
"supportedHosts": ["SharePointWebPart", "TeamsPersonalApp", "TeamsTab", "SharePointFullPage"],
"supportsThemeVariants": true,
"preconfiguredEntries": [{
"groupId": "5c03119e-3074-46fd-976b-c60198311f70", // Advanced
"group": { "default": "Advanced" },
"title": { "default": "ChatGPT" },
"description": { "default": "ChatGPT description" },
"officeFabricIconFontName": "Page",
"properties": {
"description": "ChatGPT"
}
}]
}

View File

@ -0,0 +1,138 @@
/* eslint-disable @typescript-eslint/no-var-requires */
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { loadTheme } from 'office-ui-fabric-react/lib/Styling';
import { IReadonlyTheme } from '@microsoft/sp-component-base';
import { Version } from '@microsoft/sp-core-library';
//import { SPComponentLoader } from '@microsoft/sp-loader';
import {
IPropertyPaneConfiguration,
PropertyPaneTextField,
} from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import { ChatGpt } from '../../components/ChatGpt';
import { IChatGptProps } from '../../models/IChatGptProps';
import { registerSVGIcons } from '../../utils/registrySVGIcons';
const teamsDefaultTheme = require("../../teamsThemes/TeamsDefaultTheme.json");
const teamsDarkTheme = require("../../teamsThemes/TeamsDarkTheme.json");
const teamsContrastTheme = require("../../teamsThemes/TeamsContrastTheme.json");
export interface IBirthdaysTimelineWebPartProps {
title: string;
}
export default class ChatGptWebPart extends BaseClientSideWebPart<IChatGptProps> {
private _isDarkTheme: boolean = false;
private _isTeams: boolean = false;
private _teamId: string = "";
private _channelId: string = "";
private _chatId: string = "";
private _parentMessageId: string = "";
private _currentTheme: IReadonlyTheme | undefined;
private _applyTheme = (theme: string): void => {
this.context.domElement.setAttribute("data-theme", theme);
document.body.setAttribute("data-theme", theme);
if (theme === "dark") {
loadTheme({
palette: teamsDarkTheme,
});
}
if (theme === "default") {
loadTheme({
palette: teamsDefaultTheme,
});
}
if (theme === "contrast") {
loadTheme({
palette: teamsContrastTheme,
});
}
};
public render(): void {
const element: React.ReactElement<IChatGptProps> = React.createElement(ChatGpt, {
title: this.properties.title ?? "OpenAPI Chat",
isDarkTheme: this._isDarkTheme,
hasTeamsContext: this.context.sdks.microsoftTeams ? true : false,
theme: this._currentTheme,
context: this.context,
chatId: this._chatId,
});
ReactDom.render(element, this.domElement);
}
protected async onInit(): Promise<void> {
// SPComponentLoader.loadCss("https://fonts.googleapis.com/css2?family=Dancing+Script&display=swap");
registerSVGIcons(this._currentTheme);
if (this.context.sdks.microsoftTeams) {
// in teams ?
const teamsContext = await this.context.sdks.microsoftTeams?.teamsJs.app.getContext();
this._isTeams = true;
this._chatId = teamsContext.chat?.id;
this._teamId = teamsContext.team?.groupId;
this._channelId = teamsContext.channel?.id;
this._parentMessageId = teamsContext.app.parentMessageId;
console.log("chatId", this._chatId);
console.log("teamId", this._teamId);
console.log("channelId", this._channelId);
console.log("parentMessageId", this._parentMessageId);
console.log("isTeams", this._isTeams);
this._applyTheme(teamsContext.app.theme || "default");
this.context.sdks.microsoftTeams.teamsJs.app.registerOnThemeChangeHandler(this._applyTheme);
}
return super.onInit();
}
protected onThemeChanged(currentTheme: IReadonlyTheme | undefined): void {
if (!currentTheme) {
return;
}
this._isDarkTheme = !!currentTheme.isInverted;
this._currentTheme = currentTheme;
}
protected onDispose(): void {
ReactDom.unmountComponentAtNode(this.domElement);
}
protected get dataVersion(): Version {
return Version.parse("1.0");
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description:"description",
},
groups: [
{
groupName: "Group Name",
groupFields: [
PropertyPaneTextField("title", {
label: "Title",
value: this.properties.title ?? "OpenAPI Chat",
}),
],
},
],
},
],
};
}
}

View File

@ -0,0 +1,12 @@
define([], function() {
return {
CgatGPTAppOpenAILabel: " Open AI",
ChatGPTAppNotificationMessage: "Answer was sent to chat",
ChatGPTAppNotificationTitle: "Sent to chat",
ChatGPTAppPoweredByLabel: "Powered by OpenAI, GPT-3",
ChatGPTAppPreviewChatInfoMessage: " Please create a mesage first and after return here",
PropertyPaneDescription: "ChatGPT App",
BasicGroupName: "Properties",
DescriptionFieldLabel: "OpenAI API Key"
}
});

View File

@ -0,0 +1,15 @@
declare interface IChatGptWebPartStrings {
PropertyPaneDescription: string;
BasicGroupName: string;
DescriptionFieldLabel: string;
CgatGPTAppOpenAILabel: string;
ChatGPTAppNotificationMessage: string;
ChatGPTAppNotificationTitle: string;
ChatGPTAppPoweredByLabel: string;
ChatGPTAppPreviewChatInfoMessage: string;
}
declare module "ChatGptWebPartStrings" {
const strings: IChatGptWebPartStrings;
export = strings;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

View File

@ -0,0 +1,83 @@
{
"$schema": "https://developer.microsoft.com/en-us/json-schemas/teams/v1.13/MicrosoftTeams.schema.json",
"manifestVersion": "1.13",
"packageName": "ChatGPT",
"id": "63fc66c0-10be-43fc-a499-b4a7cc8c0cae",
"version": "1.0.0.1",
"developer": {
"name": "SPFx + Teams Dev",
"websiteUrl": "https://products.office.com/en-us/sharepoint/collaboration",
"privacyUrl": "https://privacy.microsoft.com/en-us/privacystatement",
"termsOfUseUrl": "https://www.microsoft.com/en-us/servicesagreement"
},
"name": {
"short": "ChatGPT"
},
"description": {
"short": "ChatGPT",
"full": "ChatGPT"
},
"icons": {
"outline": "63fc66c0-10be-43fc-a499-b4a7cc8c0cae_outline.png",
"color": "63fc66c0-10be-43fc-a499-b4a7cc8c0cae_color.png"
},
"accentColor": "#004578",
"configurableTabs": [
{
"configurationUrl": "https://{teamSiteDomain}{teamSitePath}/_layouts/15/TeamsLogon.aspx?SPFX=true&dest={teamSitePath}/_layouts/15/teamshostedapp.aspx%3FopenPropertyPane=true%26teams%26componentId=63fc66c0-10be-43fc-a499-b4a7cc8c0cae%26forceLocale={locale}",
"canUpdateConfiguration": true,
"scopes": [
"team"
]
}
],
"staticTabs": [
{
"entityId": "63fc66c0-10be-43fc-a499-b4a7cc8c0cae",
"name": "ChatGPT",
"contentUrl": "https://{teamSiteDomain}/_layouts/15/TeamsLogon.aspx?SPFX=true&dest=/_layouts/15/teamshostedapp.aspx%3Fteams%26personal%26componentId=63fc66c0-10be-43fc-a499-b4a7cc8c0cae%26forceLocale={locale}",
"websiteUrl": "https://products.office.com/en-us/sharepoint/collaboration",
"scopes": ["personal"]
}
],
"validDomains": [
"*.login.microsoftonline.com",
"*.sharepoint.com",
"*.sharepoint-df.com",
"spoppe-a.akamaihd.net",
"spoprod-a.akamaihd.net",
"resourceseng.blob.core.windows.net",
"msft.spoppe.com"
],
"webApplicationInfo": {
"resource": "https://{teamSiteDomain}",
"id": "00000003-0000-0ff1-ce00-000000000000"
},
"composeExtensions": [
{
"botId": "7b26d356-e7fd-4445-a5aa-b262aa718687",
"canUpdateConfiguration":true,
"commands": [
{
"id": "augOpenSPFxWebpart",
"type": "action",
"title": "OpenAI GPT-3",
"description": "OpenAI GPT-3",
"initialRun": false,
"fetchTask": false,
"context": [
"message",
"commandBox",
"compose"
],
"taskInfo": {
"title": "OpenAI GPT-3",
"height": "650",
"width": "700",
"url": "https://{teamSiteDomain}/_layouts/15/TeamsLogon.aspx?SPFX=true&dest=/_layouts/15/teamstaskhostedapp.aspx%3Fteams%26personal%26componentId=63fc66c0-10be-43fc-a499-b4a7cc8c0cae%26forceLocale={locale}"
}
}
]
}
]
}

View File

@ -0,0 +1,36 @@
{
"extends": "./node_modules/@microsoft/rush-stack-compiler-4.5/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,
"strictNullChecks": 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"
]
}