What is a Bot and Its Advantages?
A bot is a software application designed to automate tasks, often simulating human interaction. Bots are widely used in customer support, data retrieval, and task automation, making workflows efficient and reducing manual effort. With advancements in AI, bots can now engage in intelligent conversations and provide personalized assistance.
Advantages of Bots:
- Efficiency: Automates repetitive tasks, saving time and resources.
- 24/7 Availability: Provides uninterrupted support to users.
- Scalability: Handles multiple interactions simultaneously.
- Cost-Effective: Reduces the need for extensive human resources.
This tutorial is part of a series. To understand it fully, make sure to check out Part 1: Azure Configuration for Your Bot.
This blog covers the points of: Bot Configuration and Deployment
- Add the Bot Framework v4 SDK Templates to Visual Studio.
- Create an Echo Bot Solution in Visual Studio.
- Configure the OpenAI API in the Echo Bot Solution.
- Test the Bot Locally in BotFramework-Emulator.
- Deploy the Bot to Azure App Service.
- Create a manifest.json for Microsoft Teams.
- Add the App to Microsoft Teams.
- Add the Bot Framework v4 SDK Templates to Visual Studio.
- Click on the 'Download' link to open the Bot Framework v4 SDK page.
- Once the page opens, find the green "Download" button.
- Click the green button to download the Bot SDK.
- After the download is complete, install the SDK on your system.
- This template includes default bot configurations, making it easier to get started with your bot development.
- Create an Echo Bot Solution in Visual Studio.
- Open Visual Studio and choose "Create a new project."
- Search bar in search ‘bot’.
- Select template ‘Echo Bot (Bot Framework V4)’
- Add a Project name and create a project.
- Configure the OpenAI API in the Echo Bot Solution.
- Add Dependencies: Install the System.Net.Http and Newtonsoft.Json packages via NuGet for handling HTTP requests and JSON.
- Implement the ChatGPT Service:
- Go to solution explore and Open file EchoBot.cs
- Add a new method in the following code to interact with the OpenAI API: Note: Please double-check your API and API key to ensure they are working. (This code uses the Azure OpenAI API.)// New method to implement for retrieving OpenAI API responses and returning them in the//proper formatprivate async Task<string> GPTResponseAsync(string userQuery){// API key for accessing Azure OpenAI service (replace this with your actual key)string apiKey = "API_KEY";// Endpoint URL of the Azure OpenAI deployment with the correct API versionstring endPoint = "AZURE_API";// Creating an HttpClient to send HTTP requests to the APIvar client = new HttpClient();// Preparing an HTTP POST request with the specified endpointvar request = new HttpRequestMessage(HttpMethod.Post, endPoint);// Adding the API key to the request header for authenticationrequest.Headers.Add("api-key", apiKey);// Constructing the request body in JSON format// - `messages`: Contains the conversation with roles (`system`, `user`, `assistant`)// - `max_tokens`: Defines the maximum response length// - `temperature`: Controls the randomness of the response (higher values make output// more creative)// - `top_p`, `frequency_penalty`, `presence_penalty`: Other parameters to fine-tune// the response generationvar content = new StringContent($@"{{""messages"": [{{""role"": ""system"",""content"": ""You are an AI assistant designed to help people discover information.""}}, {{""role"": ""user"",""content"": ""{userQuery}""}}, {{""role"": ""assistant"",""content"": ""Hello! How can I assist you today?""}}],""max_tokens"": 800,""temperature"": 0.7,""frequency_penalty"": 0,""presence_penalty"": 0,""top_p"": 0.95,""stop"": null}}", null, "application/json");// Setting the content of the request to the JSON string prepared aboverequest.Content = content;// Sending the request asynchronously and awaiting the responsevar response = await client.SendAsync(request);// Ensuring the response status code is successful (2xx), throwing an error if notresponse.EnsureSuccessStatusCode();// Reading the response content as a stringvar result = await response.Content.ReadAsStringAsync();// Parsing the result string into a JSON objectvar resultObject = JObject.Parse(result);// Returning the assistant's response from the JSON objectreturn Convert.ToString(resultObject["choices"][0]["message"]["content"]);}
- Integrate ChatGPT with the Bot:
- In your bot's main dialogue or message handler (e.g., EchoBot.cs), integrate the ChatGPT service:
- Method Purpose: This method is triggered whenever a user sends a message in the conversation (e.g., in Microsoft Teams). It takes the message, forwards it to OpenAI's GPT API, and sends the response back to the user.
- TurnContext: This object contains all the relevant details about the conversation, including the message sent by the user. turnContext.Activity.Text gets the message text that the user sent.
- GPTResponseAsync: The method sends the user's message to the GPT model hosted on Azure OpenAI and waits for the AI's response. It returns the response, which will be sent back to the user.
- MessageFactory.Text: This creates a new message to be sent back to the user. The same text is passed twice; the first parameter is what will be displayed, and the second is for any formatting or processing.
- CancellationToken: This parameter is used to manage the cancellation of asynchronous tasks. It ensures that the operation can be cancelled if needed without blocking the application. protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext,CancellationToken cancellationToken){//var replyText = $"Echo: {turnContext.Activity.Text}";var gptResponse = await GPTResponseAsync(turnContext.Activity.Text);await turnContext.SendActivityAsync(MessageFactory.Text(gptResponse, gptResponse),cancellationToken);}
- Test the Bot Locally in BotFramework-Emulator.
- Go to the following link to directly 'download' BotFramework-Emulator exe file.
- Once the Bot Framework Emulator is downloaded, install it.
- Run your Project When successfully running the solution open the Bot window and copy the URL.
- Open the Emulator > “Open Bot” > set your URL plus “api/messages” > Connect
- Test your bot.
- Deploy the Bot to Azure App Service.
- Prerequisite
- Azure Tenant ID
- MicrosoftAppId
- MicrosoftAppPassword
- Azure Tenant ID: Azure Portal > Azure Active Directory > Overview > Directory ID (copy this value)
- Microsoft App ID: Azure Portal > All services > Bot Services (or Azure Bot) > [Your Bot] > Settings > Microsoft App ID (copy this value)
- Microsoft App Password: Azure Portal > All services > Bot Services (or Azure Bot) > [Your Bot] > Settings > Manage > Certificates & secrets > New client secret > Add (copy the value of the newly created client secret)
- Open the Visual Studio solution(6) for your Echo Bot and navigate to the appsettings.json file. Add the following configuration (paste the IDs)
- Visual Studio > Solution Explorer > Right-click on your project > Publish > Add New Profile > Azure
- Sign in to Azure (if required) and select Created app service for the bot. then Finish
- Click on 'Publish' to deploy the app to Azure App Service.
- Create a manifest.json for Microsoft Teams.
- Create a new file named manifest.json in your project folder.
- Add the following basic structure to your manifest.json file: Need more information click manifest.json{"$schema": "https://developer.microsoft.com/en-us/json-schemas/teams/v1.16/MicrosoftTeams.schema.json","manifestVersion": "1.16","version": "1.0.9","id": "<YOUR_TEAMS_APP_ID>","packageName": "com.microsoft.teams.extension","developer": {"name": "Teams App, Inc.","websiteUrl": "<YOUR_WEBSITE_URL>","privacyUrl": "<YOUR_WEBSITE_URL>","termsOfUseUrl": "<YOUR_WEBSITE_URL>"},"icons": {"color": "color.png","outline": "outline.png"},"name": {"short": "Gangbox ChatBot","full": "Gangbox ChatBot"},"description": {"short": "This is AI Chatbot.","full": "This is AI Chatbot."},"accentColor": "#FFFFFF","bots": [{"botId": "<YOUR_TEAMS_APP_ID>","scopes": ["personal","team","groupchat"],"supportsFiles": false,"isNotificationOnly": false,"commandLists": [{"scopes": ["personal","team","groupchat"],"commands": [{"title": "welcome","description": "Resend welcome card of this Bot"},{"title": "learn","description": "Learn about Adaptive Card and Bot Command"}]}]}],"composeExtensions": [],"configurableTabs": [],"staticTabs": [],"permissions": ["identity","messageTeamMembers"],"validDomains": []}
- Replace Placeholders
- id: Your bot's Microsoft App ID.
- developer: Fill in details about your name/company and URLs for your website, privacy policy, and terms of use.
- botId: The same as your Microsoft App ID.
- icons: Add the paths to your bot's icon images (color and outline versions).
Add two images (icon files) in your folder:
- color.png (192x192 pixels)
- outline.png (32x32 pixels) - Compress Files into a Zip
Include the following files in a zip file:
- manifest.json
- color.png
- outline.png
The zip file will be your Teams app package. - Add the App to Microsoft Teams.
Thank you for reading! We hope this guide helped you successfully configure your bot. Feel free to share your thoughts or questions in the comments below!
If you have any questions you can reach out our SharePoint Consulting team here.