August 24, 2023

Integrating Azure OpenAI into Microsoft Teams using Teams Toolkit: A How-To Guide

Introduction:

In today's digital landscape, effective communication and collaboration are essential for productive teamwork. Microsoft Teams has emerged as a popular platform that brings people together. Now, imagine taking your Microsoft Teams experience to the next level by integrating it with Azure OpenAI, a powerful language model capable of generating human-like responses.


This article will walk you through the integration of Azure OpenAI with Microsoft Teams, enabling users to engage in chat-based conversations and receive intelligent responses within the familiar Teams interface.

Prerequisites:

  • Access to OpenAI Service on Azure (Please be aware that access to Azure OpenAI services is currently limited. If your Azure tenant does not have access, you have the option to apply for access through this link)

  • An M365 account.

  • NodeJS (Tested on Node.js 16.19.0)

  • Latest stable version of Teams Toolkit Visual Studio Code Extension (Tested on version 5.0.1)

Teams Toolkit:

Teams Toolkit is a user-friendly development framework by Microsoft, designed for creating apps, bots, and integrations within Microsoft Teams. It streamlines the process, making it easier to build collaborative solutions.


To install Teams Toolkit Visual Studio Code extensions, follow these steps:

  • Click on the Extensions icon on the left sidebar.

  • Search and install Teams Toolkit.


To scaffold the project, follow these steps within the Teams Toolkit interface:

  • Click on the Teams Toolkit icon located in the left sidebar.

  • Select "Create a New App" and then choose the "Bot" option.

 
  • Now in the next step select "Basic Bot".

  • Move ahead with selecting  "TypeScript" as a Programming Language.

  • Specify the Location and Name of the App for our case it’s "TeamsGPT".


After scaffolding the project, you can test the bot solution by following these steps:

  • From the left menu, select "Run and Debug."

  • Choose the desired run profile.

  • Click on the "Run" button to test the bot solution.

Azure Open AI Model Deployment:

Azure OpenAI is a service provided by Microsoft that allows us to access powerful artificial intelligence models. It enables us to integrate AI capabilities into our applications, making them smarter and more intelligent.


Follow Below Steps to Create an Instance of Azure Open AI:

  • Navigate to Azure Open AI under the Cognitive Service in the Azure Portal.

  • Click on "Create New".

  • Fill all the Details with Name of the Instance and Resource.

  • Click on Next Until Review and Submit tab.

  • Verify all the Details and then Click on Create.


This will Create a Resource Group which contains Azure Open AI Service Instance now Navigate to the Resource Group and Select this Instance.


Follow Below steps to deploy the Model using this Instance:

  • Click on  "Model Deployment" on the Left Hand Side.

  • Then Select "Manage Deployment" and it will take us to the Azure Open AI Studio.

  • Now, Click on "Deployments" on the Left Hand Side.

  • Then Click on "Create new deployment" and it will Prompt us to add the Details for our Model.


In Select a Model Field Add "text-davinci-003" and also same in the Deployment Name and the Click on Create.


Text-davinci-003 model is a language model developed by OpenAI. It is designed to generate human-like text and provide natural language processing capabilities. This model can be used for various tasks such as chatbots, language translation, content generation, and more.


  • Now, Select the Model and Click on Open in Playground.


  • Click on View Code and note down the Endpoint and Key.


Now, coming back to our teams toolkit solution we will store this Endpoint and Key in the Configuration File. Open Config.ts file and Modify the Code as:

const config = {
  botId: process.env.BOT_ID,
  botPassword: process.env.BOT_PASSWORD,
  Endpoint: 'https://XXXX-openai.openai.azure.com/', //Your EndPoint URL
  APIKey: 'XXXX' //Your API Key
};

export default config;

To enable receiving the response back in the Teams interface, modify the implementation of the welcome Adaptive Card logic as follows.


Go to adaptiveCards and then the welcome.json file modify the code as below.

{
  "type": "AdaptiveCard",
  "body": [
    {
      "type": "TextBlock",
      "size": "Medium",
      "weight": "Bolder",
      "text": "${title}"
    },
    {
      "type": "TextBlock",
      "text": "${body}",
      "wrap": true
    }
  ],
  "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
  "version": "1.4"
}

Now, the Final Change - modify the teamsBot.ts file as below in order to get the work done.

import {
  TeamsActivityHandler,
  CardFactory,
  TurnContext,
} from "botbuilder";
import rawWelcomeCard from "./adaptiveCards/welcome.json";
import { AdaptiveCards } from "@microsoft/adaptivecards-tools";
import config from "./config";

export class TeamsBot extends TeamsActivityHandler {

  constructor() {
    super();
    
    this.onMessage(async (context, next) => {
      console.log("Running with Message Activity.");
      let text = context.activity.text;
      const removeMentionedText = TurnContext.removeRecipientMention(context.activity);
      if (removeMentionedText) {
        text = removeMentionedText.toLowerCase().replace(/\n|\r/g, "").trim();
      }

      const fetch = require('node-fetch');

      const endpoint = config.Endpoint;
      const apiKey = config.APIKey;

      const prompt = text;
      const maxTokens = 100;
      const temperature = 1;
      const frequencyPenalty = 0;
      const presencePenalty = 0;
      const topP = 0.5;
      const bestOf = 1;
      const stop = null;

      const requestBody = JSON.stringify({
        prompt,
        max_tokens: maxTokens,
        temperature,
        frequency_penalty: frequencyPenalty,
        presence_penalty: presencePenalty,
        top_p: topP,
        best_of: bestOf,
        stop,
      });

      const headers = {
        'Content-Type': 'application/json',
        'api-key': apiKey,
      };

      const response = await fetch(endpoint, {
        method: 'POST',
        headers,
        body: requestBody,
      });

      const data = await response.json();
      if (response.ok) {
        const generatedtext = data.choices[0].text;
        const cardData = {
          title: "Response From Open AI",
          body: generatedtext,
      };
        const card = AdaptiveCards.declare(rawWelcomeCard).render(cardData);
        await context.sendActivity({ attachments: [CardFactory.adaptiveCard(card)] });
      } else {
        throw new Error('Failed to generate Response');
      }

    })
  }
}

Now, Follow Below Steps to Run and Debug the Bot.

  • From the left menu, select "Run and Debug."

  • Choose the desired run profile.

  • Click on the "Run" button to test the bot solution.


Now, Imagine having the ability to effortlessly generate responses and engage in intelligent conversations within the familiar interface of Microsoft Teams.

Conclusion:

With the integration of Azure OpenAI, this becomes a reality. Now, you can ask whatever comes to mind and receive seamless, insightful replies, unlocking a whole new level of communication and collaboration within Teams. Say goodbye to limitations and welcome a world where your thoughts and queries are met with intelligent conversations at your fingertips.


If you have any questions you can reach out our SharePoint Consulting team here.

August 3, 2023

To create terms dynamically in a TermSet and set them in a Managed Metadata column using Power Automate

Introduction: 

In this blog post, we will learn how to dynamically create Terms in a TermSet of a Termstore and set them in a managed metadata column using Microsoft Power Automate.

Requirement:

To obtain information about Skills and Past Projects from the Office 365 user profile and add it to a SharePoint list, we will enable Out-of-the-Box (OOTB) filtering and sorting operations on these fields.
We can use Single line of text OR Multiline of text site column and store information with delimiters, but limitation was, can’t perform OOTB filtering and sorting operation.

To overcome this issue, we are going to use a Managed Metadata site column to store the terms values dynamically. This approach will allow us to perform Out-of-the-Box (OOTB) filtering and sorting operations on the information, providing a more effective solution compared to using Single line of text or Multiline of text site columns with delimiters.

Approach:

Create “Managed Metadata field” with “Allow multiple values” checkbox enabled and “Customize your term set” option selected as shown in below screenshot.





Below are the steps in Power Automate to dynamically create Terms in a TermSet of a Termstore and then create an item in a SharePoint list with those terms in a Managed Metadata field.

Step 1: Add an action “Initialize Variable”, Name it as “Initialize variable Skills” as shown in below screenshot. This will be used to store JSON for use in SharePoint list Item creation.

 


Step 2: Add “Get user profile (V2)” action with user principal name or Email ID in “User (UPN)” as shown below.

 


Step 3: Append value to “Skills” variable as shown in below screenshot.


 Step 4: Add below set of actions to process each element in “Skills” array (which we retrieved in Step-2).
 



Step 5: Then we need to add an action called “Send an HTTP request to SharePoint” to retrieve terms from TermSet.

Uri - _api/v2.1/termStore/groups/97ac8ae5-1608-4047-8951-585b3a2640c5/sets/e0af947c-6cef-4766-8c79-9c454cc5a323/children.

In Uri, “97ac8ae5-1608-4047-8951-585b3a2640c5” is Termstore ID and “e0af947c-6cef-4766-8c79-9c454cc5a323” is TermSet ID in which we need to store or create terms.

 


Step 6: To compare the current item in the loop with the term name, we need to filter the values retrieved in Step-5 to check if they are "equal to" the term name.

string (item ()? ['labels'][0] ['name']) expression is used in comparison as shown in below screenshot.

 


Step 7: Add the following set of actions to form JSON or create JSON data for the "Skills" variable. The condition, as shown in the below screenshot, checks whether the term is present in the "Skills" TermSet or not, using the expression length(body('Filter_skills_array')). If the term is not present, we are adding a POST call to create a new term and then appending the values to the "Skills" variable. On the other hand, if the term is already present, we simply append the values to the "Skills" variable.


 
Step 8: If the condition is "Yes," indicating that the term is present in the "Skills" TermSet of the Termstore, then we simply append the values to the "Skills" variable.

Note: Value will be appended in JSON format as - 
{
“value”: “Sharepoint|3198df72-311b-4757-9246-052296af2”
}

Where, the expression in below screenshot consists of “{current term name in loop}|body('Filter_skills_array')[0]['id']”

 


Step 9: If the condition is "No," meaning that the term is not present in the "Skills" TermSet of the Termstore, in such a case, we need to create the term using a POST call with the action called "Send an HTTP request to SharePoint," as shown in the below screenshot.

Uri - _api/v2.1/termStore/groups/97ac8ae5-1608-4047-8951-585b3a2640c5/sets/e0af947c-6cef-4766-8c79-9c454cc5a323/children.

In Uri, “97ac8ae5-1608-4047-8951-585b3a2640c5” is Termstore ID and “e0af947c-6cef-4766-8c79-9c454cc5a323” is TermSet ID in which we need to store or create terms.



Step 10: Add “Compose” action to fetch and store term ID from Step-9, as shown below.

 


Step 11: After that, append the JSON value, as shown in the below screenshot, with the term name and ID from the "Step-10" compose action.



Step 12: Add the below action after completing the Condition and loop actions to append the closing of JSON in the "Skills" variable.

 


Step 13: Add the below action to parse the JSON, enabling us to create and store the data in a SharePoint list item.

Schema: {
    "type": "array",
    "items": {
        "type": "object",
        "properties": {
            "Value": {
                "type": "string"
            }
        },
        "required": [
            "Value"
        ]
    }
}

 


Step 14: Use Step-13 parsed JSON in “Create Item” action as shown in below screenshot.

 


Finally, we can see that terms have been added to the "Skills" TermSet using Power Automate flow.
 


Also, terms have been added to the "Skills" Managed Metadata field in the SharePoint list as well.

 


Additionally, we can view the "Skills" managed metadata field from the list settings, where we have dynamically appended terms using Power Automate






If you have any questions you can reach out our SharePoint Consulting team here.