Skip to content

Latest commit

 

History

History
355 lines (261 loc) · 13.7 KB

spe-da-vscode.md

File metadata and controls

355 lines (261 loc) · 13.7 KB
title description ms.date ms.localizationpriority
Sharepoint Embedded copilot Tutorial
Sharepoint Embedded copilot Tutorial with the SDK and the VS Code SharePoint Embedded Extension
02/27/2025
high

Tutorial for getting started with SharePoint Embedded copilot

Prerequisites

Note

  1. You will need to create create a SharePoint Embedded application. If you don't have one, you can easily build a sample application using the instructions here.
  2. You must specify a standard container type at creation time. Depending on the purpose, you may or may not need to provide your Azure Subscription ID. A container type set for trial purposes can't be converted for production; or vice versa.
  3. You must use the latest version of SharePoint PowerShell to configure a container type. For permissions and the most current information about Windows PowerShell for SharePoint Embedded, see the documentation at Intro to SharePoint Embedded Management Shell.

Getting started using the SharePoint Embedded SDK

1. Install the SDK into your React repo

# Install the SDK with npm

npm install "https://download.microsoft.com/download/27d10531-b158-40c9-a146-af376c0e7f2a/microsoft-sharepointembedded-copilotchat-react-1.0.7.tgz"

If you want to verify checksums

In MacOS/Linux

version="1.0.7";

url="https://download.microsoft.com/download/27d10531-b158-40c9-a146-af376c0e7f2a/microsoft-sharepointembedded-copilotchat-react-1.0.7.tgz"; 

expected_checksum="A87FF410E8684A3C16456B2092564422BF80DA9FAFF3A684821DACEAEEA23D22"; 

package_path="microsoft-sharepointembedded-copilotchat-react-$version.tgz"; 

curl -o $package_path $url && [ "$(sha256sum $package_path | awk '{ print $1 }')" == "$expected_checksum" ] && npm install $package_path || { echo "Checksum does not match. Aborting installation."; rm $package_path; }

In Windows:

$version = "1.0.7"
$url = "https://download.microsoft.com/download/27d10531-b158-40c9-a146-af376c0e7f2a/microsoft-sharepointembedded-copilotchat-react-1.0.7.tgz"
$expected_checksum = "A87FF410E8684A3C16456B2092564422BF80DA9FAFF3A684821DACEAEEA23D22"
$package_path = "microsoft-sharepointembedded-copilotchat-react-$version.tgz"

Invoke-WebRequest -Uri $url -OutFile $package_path

$calculated_checksum = Get-FileHash -Path $package_path -Algorithm SHA256 | Select-Object -ExpandProperty Hash

if ($calculated_checksum -eq $expected_checksum) {
    Write-Output "Checksum matches. Installing the package..."
    npm install $package_path
} else {
    Write-Output "Checksum does not match. Aborting installation."
}
Remove-Item $package_path

2. Create an authProvider object

This is an object that matches this interface:

export interface IChatEmbeddedApiAuthProvider {
    // The hostname for your tenant. Example: https://m365x10735106.sharepoint.com
    hostname: string;
    // This function will be called when an SPO token is required
    // Scope needed: ${hostname}/Container.Selected
    getToken(): Promise<string>;
}

Example usage in app:

// In your app:
import { IChatEmbeddedApiAuthProvider } from '@microsoft/sharepointembedded-copilotchat-react';

const authProvider: IChatEmbeddedApiAuthProvider = {
    hostname: 'https://m365x10735106.sharepoint.com',
    getToken: requestSPOAccessToken,
};

Example implementation of getToken (you need to customize it):

//
async function requestSPOAccessToken() {
  // Use your app's actual msalConfig
  const msalConfig = {
    auth: {
      clientId: "{Your Entra client ID}", // this can likely point to process.env.REACT_APP_CLIENT_ID if you have set it in your .env file
    },
    cache: {
              // https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/caching.md
              /*
              Cache Location | Cleared on | Shared between windows/tabs | Redirect flow supported
              -----------------   ----------  -------------------------   ------------------------
              sessionStorage | window/tab close | No | Yes
              localStorage | browser close | Yes |   Yes
              memoryStorage | page |  refresh/navigation | No | No
              */
      cacheLocation: 'localStorage',
      storeAuthStateInCookie: false,
    },
  };

  const containerScopes = {
    scopes: [`${authProvider.hostname}/Container.Selected`],
    redirectUri: '/'
  };

  const pca = new msal.PublicClientApplication(msalConfig);
  let containerTokenResponse;

  // Consent FileStorageContainer.Selected scope
  try {
    // attempt silent acquisition first
    containerTokenResponse = await pca.acquireTokenSilent(containerScopes);
    return containerTokenResponse.accessToken;
  } catch (error) {
    if (error instanceof InteractionRequiredAuthError) {
      // fallback to interaction when silent call fails
      containerTokenResponse = await pca.acquireTokenPopup(containerScopes);
      return containerTokenResponse.accessToken;
    }
    else {
      console.log(error);
    }
  }
}

3. Create a React state to store your chatApi in

const [chatApi, setChatApi] = React.useState<ChatEmbeddedAPI|null>(null);

Example:

import React from 'react';
import { ChatEmbedded, ChatEmbeddedAPI, IChatEmbeddedApiAuthProvider } from '@microsoft/sharepointembedded-copilotchat-react';

//...
async function requestSPOAccessToken() {
  //...
}

const authProvider: IChatEmbeddedApiAuthProvider = {
  hostname: 'https://m365x10735106.sharepoint.com',
  getToken: requestSPOAccessToken,
};

function App() {
  const [chatApi, setChatApi] = React.useState<ChatEmbeddedAPI|null>(null);

  return (
    //...
  );
}

4. Add the ChatEmbedded component into your react app

import React from 'react';
import { ChatEmbedded, ChatEmbeddedAPI, IChatEmbeddedApiAuthProvider } from '@microsoft/sharepointembedded-copilotchat-react';

//...
async function requestSPOAccessToken() {
  //...
}

const authProvider: IChatEmbeddedApiAuthProvider = {
  hostname: 'https://m365x10735106.sharepoint.com',
  getToken: requestSPOAccessToken,
};

function App() {
  const [chatApi, setChatApi] = React.useState<ChatEmbeddedAPI|null>(null);

  return (
    //...
    <ChatEmbedded
      onApiReady={setChatApi}
      authProvider={authProvider}
      containerId={container.id}
      style={{ width: 'calc(100% - 4px)', height: 'calc(100vh - 8px)' }}
    />
    //...
  );
}

5. Use the chatApi object in your state to open the chat and run it

In the example above, call it this way to open the chat.

await chatApi.openChat();

You may choose to pass in launch configurations

import { IconName, IconStyle } from './sdk/types';

//...
const zeroQueryPrompts = {
  headerText: "This is my Starter Prompt",
  promptSuggestionList: [{
    suggestionText: 'Hello',
    iconRegular: { name: IconName.ChatBubblesQuestion, style: IconStyle.Regular },
    iconHover: { name: IconName.ChatBubblesQuestion, style: IconStyle.Filled },
  }]
};

const launchConfig: ChatLaunchConfig = {
  header: 'My Awesome Chat',
  zeroQueryPrompts,
  suggestedPrompts: ["What are my files?",],
  instruction: "Response must be in the tone of a pirate",
  locale: "en",
};

await chatApi.openChat(launchConfig);

Full example:

import React from 'react';
import { ChatEmbedded, ChatEmbeddedAPI, IChatEmbeddedApiAuthProvider } from '@microsoft/sharepointembedded-copilotchat-react';

//...
async function requestSPOAccessToken() {
  //...
}

const authProvider: IChatEmbeddedApiAuthProvider = {
  hostname: 'https://m365x10735106.sharepoint.com',
  getToken: requestSPOAccessToken,
};

function App() {
  const [chatApi, setChatApi] = React.useState<ChatEmbeddedAPI|null>(null);

  React.useEffect(() => {
    const openChat = async () => {
      if (!chatApi) {
        return;
      }

      await chatApi.openChat();
    };

    openChat();
  }, [chatApi]);


  return (
    //...
    <ChatEmbedded
      onApiReady={(api) => setChatApi(api)}
      authProvider={authProvider}
      containerId={container.id}
      style={{ width: 'calc(100% - 4px)', height: 'calc(100vh - 8px)' }}
    />
    //...
  );
}

6. Your AI chat should be loaded successfully

Getting started using the SharePoint Embedded Visual Studio Code Extension

Quick Start

Note

When using standard container types with the VS Code extension, DisableDiscoverability and Grant admin consent features are currently not supported. This will need to be done using the SPO Admin Powershell.

  1. Follow this guide up to the Load Sample App section with the Visual Studio Code Extension

  2. Within the extension, right click on the owning application, and select Run sample apps -> Typescript + React + Azure Functions

    Using the SPE VS Code extension to create a TypeScript React Azure Functions project

  3. Allow for the extension to copy and create client secrets

    [!CAUTION] Caution for production environments, storing secrets in plain text poses a security risk.

    SPE VS Code notification alerting it will copy app secrets in plain text on local machine

    If the application does not already have a client secret, the extension will ask to create one for you.

    SPE VS Code notification prompting user to allow it to create a secret for the application if it does not exist.

  4. Select a folder to host the application, this will clone the following repository for SharePoint Embedded Samples into the folder

    windows File Explorer folder to save project on local machine

    Next, when prompted, open the folder

    VS Code extension with the SPE React Typescript + Azure Functions sample application cloned on local machine and open in VS Code

  5. Navigate to react-client\src\components\ChatSideBar.tsx and uncomment this section

    VS Code file explorer with ChatSideBar.tsx in open window with relevant code to uncomment highlighted

  6. Navigate to react-client\src\routes\App.tsx and set the react state of the showSidebar variable to true

    VS Code file explorer with App.tsx open with line of showSidebar variable useState function input changed from false to true to enable showing chat side bar

  7. You can follow the instructions of the README.md file in the root of the project for further npm commands. Run npm run start in the root of the project to start your application with the SPE copilot functionality enabled.

    [!NOTE] npm run start Should be done in the root folder of the sample project. \SharePoint-Embedded-Samples\Samples\spe-typescript-react-azurefunction

    VS Code terminal in root folder of SPE Typescript project cloned earlier and npm run start command typed in

  8. Sign in with a user who has an M365 Copilot license enabled.

    SPE Typescript App running in Edge with sign in buttons

  9. Navigate to the containers page, create one if you do not have any yet

    SPE Typescript App running in edge in /containers sub page with modal of user c reatign a container called ContosoCompanyContainer

    After it has been created, you will see it here:

    SPE Typescript App running in edge with a created container from above ContosoCompanyContainer

  10. Click the container and upload your files. Once a container has been created and you have navigated inside it, your copilot chat experience will become enabled.

    SPE Typescript App running in edge inside a created container page of ContosoCompanyContainer

Examples

The SharePoint Embedded Samples repository has examples for how to use SharePoint Embedded in your custom applications.