### Development Server Output Example Source: https://microsoft.github.io/teams-ai/typescript/getting-started/quickstart An example of the output seen in the console when the development server starts. It shows the nodemon process, listening ports for the main application and devtools, and relevant warnings. ```log > quote-agent@0.0.0 dev \ > npx nodemon -w "./src/**" -e ts --exec "node -r ts-node/register -r dotenv/config ./src/index.ts" [nodemon] 3.1.9 [nodemon] to restart at any time, enter `rs` [nodemon] watching path(s): src/** [nodemon] watching extensions: ts [nodemon] starting `node -r ts-node/register -r dotenv/config ./src/index.ts` [WARN] @teams/app/devtools ⚠️ Devtools are not secure and should not be used production environments ⚠️ [INFO] @teams/app/http listening on port 3978 🚀 [INFO] @teams/app/devtools available at http://localhost:3979/devtools ``` -------------------------------- ### Install Teams CLI using npm Source: https://microsoft.github.io/teams-ai/python/getting-started/quickstart Installs the Teams CLI globally using npm. This command-line tool simplifies the creation and management of Teams applications. ```bash npm install -g @microsoft/teams.cli ``` -------------------------------- ### Install .NET Project Dependencies Source: https://microsoft.github.io/teams-ai/csharp/getting-started/quickstart This command restores the necessary NuGet packages for your .NET project, ensuring all dependencies are available for building and running the agent. ```bash dotnet restore ``` -------------------------------- ### Install Agent Dependencies Source: https://microsoft.github.io/teams-ai/typescript/getting-started/quickstart Installs all the necessary Node.js dependencies for the Teams AI agent project. This command should be run from the agent's root directory. ```bash npm install ``` -------------------------------- ### Install Teams CLI using npm Source: https://microsoft.github.io/teams-ai/csharp/getting-started/quickstart This command installs the Teams CLI globally using npm. The Teams CLI is a command-line tool that simplifies the creation and management of Teams applications. ```bash npm install -g @microsoft/teams.cli ``` -------------------------------- ### Migrate Application Class: Teams AI v2 Example Source: https://microsoft.github.io/teams-ai/typescript/migrations/v1 Example of the App class setup in Teams AI v2. This code shows the initialization of the new App class with client credentials and optional local storage. The App class manages its own server setup by default. ```typescript import { App } from '@microsoft.teams.apps'; import { LocalStorage } from '@microsoft.teams.common/storage'; // Define app const app = new App({ clientId: process.env.ENTRA_APP_CLIENT_ID!, clientSecret: process.env.ENTRA_APP_CLIENT_SECRET!, tenantId: process.env.ENTRA_TENANT_ID!, }); // Optionally create local storage const storage = new LocalStorage(); // Listen for errors app.event('error', async (client) => { console.error('Error event received:', client.error); if (client.activity) { await app.send( client.activity.conversation.id, 'An error occurred while processing your message.', ); } }); // App creates local server with route for /api/messages // To reuse your restify or other server, // create a custom `HttpPlugin`. (async () => { // starts the server await app.start(); })(); ``` -------------------------------- ### Run the .NET Agent Development Server Source: https://microsoft.github.io/teams-ai/csharp/getting-started/quickstart This command starts the development server for your Teams AI agent. It will begin listening for requests and provides access to devtools for testing and debugging. ```bash dotnet run ``` -------------------------------- ### Run Python agent development server with UV Source: https://microsoft.github.io/teams-ai/python/getting-started/quickstart Starts the development server for your Teams AI agent using UV. This command runs the main Python script and makes the agent accessible for local testing. ```bash cd quote-agent uv run src\main.py ``` -------------------------------- ### Migrate Application Class: Teams AI v1 Example Source: https://microsoft.github.io/teams-ai/typescript/migrations/v1 Example of the Application class setup in Teams AI v1. This code demonstrates the initialization of the adapter, error handling, and the creation of an HTTP server to listen for incoming requests. It uses restify for the server setup. ```typescript import { ConfigurationServiceClientCredentialFactory, MemoryStorage, TurnContext, } from 'botbuilder'; import { Application, TeamsAdapter } from '@microsoft/teams-ai'; import * as restify from 'restify'; // Create adapter. const adapter = new TeamsAdapter( {}, new ConfigurationServiceClientCredentialFactory({ MicrosoftAppId: process.env.ENTRA_APP_CLIENT_ID, MicrosoftAppPassword: process.env.ENTRA_APP_CLIENT_SECRET, MicrosoftAppType: 'SingleTenant', MicrosoftAppTenantId: process.env.ENTRA_APP_TENANT_ID }) ); // Catch-all for errors. const onTurnErrorHandler = async (context: TurnContext, error: any) => { console.error(`\n [onTurnError] unhandled error: ${error}`); // Send a message to the user await context.sendActivity('The bot encountered an error or bug.'); }; // Set the onTurnError for the singleton CloudAdapter. adapter.onTurnError = onTurnErrorHandler; // Create HTTP server. const server = restify.createServer(); server.use(restify.plugins.bodyParser()); server.listen(process.env.port || process.env.PORT || 3978, () => { console.log(`\n${server.name} listening to ${server.url}`); }); // Define storage and application const app = new Application({ storage: new MemoryStorage() }); // Listen for incoming server requests. server.post('/api/messages', async (req, res) => { // Route received a request to adapter for processing await adapter.process(req, res, async (context) => { // Dispatch to application for routing await app.run(context); }); }); ``` -------------------------------- ### Start Agent Development Server Source: https://microsoft.github.io/teams-ai/typescript/getting-started/quickstart Starts the development server for the Teams AI agent. This command uses nodemon to watch for changes in the 'src' directory and restarts the agent with TypeScript and dotenv support. ```bash npm run dev ``` -------------------------------- ### Install Microsoft Teams AI NuGet Package (C#) Source: https://microsoft.github.io/teams-ai/csharp/in-depth-guides/ai/setup-and-prereqs Installs the Microsoft Teams AI library into your C# project using the .NET CLI. This package is essential for integrating LLMs into your Teams applications. ```bash dotnet add package Microsoft.Teams.AI ``` -------------------------------- ### Navigate to Agent Directory Source: https://microsoft.github.io/teams-ai/typescript/getting-started/quickstart Changes the current directory to the newly created agent's project folder. This is a prerequisite for installing dependencies and running the agent. ```bash cd quote-agent ``` -------------------------------- ### Navigate to Agent Directory Source: https://microsoft.github.io/teams-ai/csharp/getting-started/quickstart Change the current directory to your new agent's project directory to access its files and run commands. ```bash cd Quote.Agent/Quote.Agent ``` -------------------------------- ### Install A2A Package with npm Source: https://microsoft.github.io/teams-ai/typescript/in-depth-guides/ai/a2a This command installs the official A2A SDK for both server and client into your project using npm. Ensure you have Node.js and npm installed. ```bash npm install @microsoft/teams.a2a ``` -------------------------------- ### Create New C# Echo Agent Project Source: https://microsoft.github.io/teams-ai/csharp/getting-started/quickstart This command creates a new directory for your agent, bootstraps the echo agent template files, and generates manifest files required for sideloading the app into Teams. ```bash teams new csharp quote-agent --template echo ``` -------------------------------- ### Start the Bot Application (JavaScript) Source: https://microsoft.github.io/teams-ai/typescript/migrations/BotBuilder/user-authentication This code snippet starts the bot application using an immediately invoked async function expression (IIAFE). It calls the 'app.start()' method, which is responsible for initializing and running the bot's core logic. ```javascript (async () => { await app.start(); })(); ``` -------------------------------- ### Create a new Python echo agent with Teams CLI Source: https://microsoft.github.io/teams-ai/python/getting-started/quickstart Creates a new Teams AI agent project using the 'echo' template. This command sets up the project directory, agent template files, and manifest files. ```bash teams new python quote-agent --template echo ``` -------------------------------- ### Configuration Routes Source: https://microsoft.github.io/teams-ai/typescript/essentials/on-activity/activity-ref Routes related to the application's configuration and setup. ```APIDOC ## Configuration Routes ### Description Manages application configuration and settings. ### Method POST ### Endpoint `/config/fetch` or `/config/submit` or `/tab/fetch` or `/tab/submit` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body Depends on the specific configuration action. ### Request Example ```json { "type": "config.open" } ``` ### Response #### Success Response (200) - **result** (object) - Configuration details or submission status. #### Response Example ```json { "result": { "message": "Configuration updated successfully." } } ``` ``` -------------------------------- ### Start Teams Application Lifecycle Source: https://microsoft.github.io/teams-ai/typescript/getting-started/code-basics This code snippet illustrates how to start the Teams application's lifecycle using an asynchronous immediately-invoked function expression (IIFE). Calling 'app.start()' initializes the application server and prepares it for communication within Teams. ```typescript (async () => { await app.start(); })(); ``` -------------------------------- ### Install Teams AI MCP Client Source: https://microsoft.github.io/teams-ai/typescript/in-depth-guides/ai/mcp/mcp-client Installs the necessary package for the Teams AI MCP Client using npm. This package allows your AI agent to communicate with remote MCP servers. ```bash npm install @microsoft/teams.mcpclient ``` -------------------------------- ### Initialize and Start the Teams Client App Source: https://microsoft.github.io/teams-ai/typescript/in-depth-guides/tabs/using-the-app This snippet demonstrates the basic initialization of the `@microsoft/teams.client` App class. It involves creating an App instance with a client ID and then calling the `start()` method to initialize TeamsJS and related services. ```typescript import { App } from '@microsoft/teams.client'; const app = new App(clientId); await app.start(); ``` -------------------------------- ### Install MCP Server Plugin Source: https://microsoft.github.io/teams-ai/typescript/in-depth-guides/ai/mcp/mcp-server Installs the necessary package for the MCP server plugin. This is the first step to enable MCP server functionality in your application. ```bash npm install @microsoft/teams.mcp ``` -------------------------------- ### Project Structure for Teams AI v2 Source: https://microsoft.github.io/teams-ai/python/in-depth-guides/ai/setup-and-prereqs A typical project structure for a Teams AI v2 application. It includes directories for the Teams app package, source code, and a root-level .env file for environment variables. ```text my-app/ |── appPackage/ # Teams app package files ├── src/ │ └── main.py # Main application code |── .env # Environment variables ``` -------------------------------- ### AI Model Initialization with Environment Variables (Python) Source: https://microsoft.github.io/teams-ai/python/in-depth-guides/ai/setup-and-prereqs Demonstrates how to initialize AI models in Python, automatically loading environment variables or explicitly passing configuration parameters. This is useful for advanced configurations or when environment variables are not automatically loaded. ```python # Automatic (recommended) model = OpenAICompletionsAIModel(model="your-model-name") # Explicit (for advanced use cases) model = OpenAICompletionsAIModel( key="your-api-key", model="your-model-name", azure_endpoint="your-endpoint", # Azure only api_version="your-api-version" # Azure only ) ``` -------------------------------- ### Run Teams Application Source: https://microsoft.github.io/teams-ai/python/getting-started/code-basics Starts the Teams application server by running the App instance. This is typically the last part of the main script, initializing the application to listen for and process activities. ```python import asyncio if __name__ == "__main__": asyncio.run(app.start()) ``` -------------------------------- ### Install Graph API Endpoints Package (npm) Source: https://microsoft.github.io/teams-ai/typescript/essentials/graph Installs the optional @microsoft/teams.graph-endpoints package, which provides request-builder functions and types for calling production-ready Graph APIs. This is typically the first step before making Graph API calls. ```bash npm install @microsoft/teams.graph-endpoints ``` -------------------------------- ### Migrate Message Handler: Teams AI v1 Example Source: https://microsoft.github.io/teams-ai/typescript/migrations/v1 Example of registering a message handler for a specific command ('/hi') and a catch-all message handler in Teams AI v1. The '/hi' handler sends a simple reply, while the catch-all echoes the user's message. ```typescript // triggers when user sends "/hi" or "@bot /hi" app.message("/hi", async (context) => { await context.sendActivity("Hi!"); }); // listen for ANY message to be received app.activity( ActivityTypes.Message, async (context) => { // echo back users request await context.sendActivity( `you said: ${context.activity.text}` ); } ); ``` -------------------------------- ### Install and Use Teams Graph Beta Endpoints Source: https://microsoft.github.io/teams-ai/typescript/essentials/graph This snippet demonstrates how to install and utilize the `@microsoft/teams.graph-endpoints-beta` package to access Microsoft Graph preview APIs. It shows how to fetch current user details from the beta endpoint. ```bash npm install @microsoft/teams.graph-endpoints-beta ``` ```typescript import * as endpointsBeta from '@microsoft/teams.graph-endpoints-beta'; // Gets the current user details from /beta/me, rather than from /v1.0/me. const me = await app.graph.call(endpointsBeta.me.get); ``` -------------------------------- ### Import Core Teams AI Components Source: https://microsoft.github.io/teams-ai/python/in-depth-guides/ai/chat Imports necessary classes for chat generation, message handling, activity context, and AI models from the Microsoft Teams AI library. ```python from microsoft.teams.ai import ChatPrompt from microsoft.teams.api import MessageActivity, MessageActivityInput from microsoft.teams.apps import ActivityContext from microsoft.teams.openai import OpenAICompletionsAIModel ``` -------------------------------- ### Migrate Message Handler: Teams AI v2 Example Source: https://microsoft.github.io/teams-ai/typescript/migrations/v1 Example of registering message handlers in Teams AI v2. It demonstrates handling a specific command ('/hi') and all incoming messages ('on message'). The SDK requires manual sending of typing indicators. ```typescript // triggers when user sends "/hi" or "@bot /hi" app.message('/hi', async (client) => { // SDK does not auto send typing indicators await client.send({ type: 'typing' }); await client.send("Hi!"); }); // listen for ANY message to be received app.on('message', async (client) => { await client.send({ type: 'typing' }); await client.send( `you said "${client.activity.text}"` ); }); ``` -------------------------------- ### Basic Chat Generation with OpenAI Source: https://microsoft.github.io/teams-ai/python/in-depth-guides/ai/chat Demonstrates a simple chat interaction using OpenAICompletionsAIModel and ChatPrompt. It sends user input to the model with specific instructions and replies with the generated content. Assumes 'app' and 'AZURE_OPENAI_MODEL' are defined elsewhere. ```python @app.on_message async def handle_message(ctx: ActivityContext[MessageActivity]): openai_model = OpenAICompletionsAIModel(model=AZURE_OPENAI_MODEL) agent = ChatPrompt(model=openai_model) chat_result = await agent.send( input=ctx.activity.text, instructions="You are a friendly assistant who talks like a pirate." ) result = chat_result.response if result.content: await ctx.send(MessageActivityInput(text=result.content).add_ai_generated()) # Ahoy, matey! 🏴‍☠️ How be ye doin' this fine day on th' high seas? What can this ol’ salty sea dog help ye with? 🚢☠️ ``` -------------------------------- ### Create New Agent with Teams CLI Source: https://microsoft.github.io/teams-ai/welcome Creates a new agent project using the Teams CLI. Supports TypeScript, C#, and Python, with the 'echo' template as an example. ```bash teams new typescript quote-agent --template echo ``` ```bash teams new csharp quote-agent --template echo ``` ```bash teams new python quote-agent --template echo ``` -------------------------------- ### Using Beta Graph Endpoints Source: https://microsoft.github.io/teams-ai/typescript/essentials/graph Demonstrates how to install and use the `@microsoft/teams.graph-endpoints-beta` package to access preview versions of Microsoft Graph APIs. ```APIDOC ## Using Beta Graph Endpoints ### Description This section explains how to leverage the `@microsoft/teams.graph-endpoints-beta` package to interact with preview versions of Microsoft Graph APIs. It highlights the installation process and provides an example of fetching current user details from the `/beta/me` endpoint. ### Installation ```bash npm install @microsoft/teams.graph-endpoints-beta ``` ### Usage Example ```typescript import * as endpointsBeta from '@microsoft/teams.graph-endpoints-beta'; // Gets the current user details from /beta/me, rather than from /v1.0/me. const me = await app.graph.call(endpointsBeta.me.get); ``` ### Key Differences The primary distinction between `@microsoft/teams.graph-endpoints` and `@microsoft/teams.graph-endpoints-beta` lies in the Microsoft Graph API schemas they represent. The `graph.call()` method intelligently routes requests to either `/v1.0` or `/beta`, allowing for the integration of beta endpoints within existing v1.0 API usage. ``` -------------------------------- ### OpenAI API Key Configuration (Environment Variables) Source: https://microsoft.github.io/teams-ai/csharp/in-depth-guides/ai/setup-and-prereqs Configures your application to use OpenAI by setting the API key as an environment variable. This is the primary credential needed to authenticate with OpenAI services. ```env OPENAI_API_KEY=sk-your-openai-api-key ``` -------------------------------- ### OpenAI API Key Environment Variable Configuration Source: https://microsoft.github.io/teams-ai/typescript/in-depth-guides/ai/setup-and-prereqs This code snippet displays the essential key-value pair to be included in your .env file for authentication with OpenAI. It requires your OpenAI API key. ```env OPENAI_API_KEY=sk-your-openai-api-key ``` -------------------------------- ### Example Terminal Output During Debugging Source: https://microsoft.github.io/teams-ai/csharp/getting-started/running-in-teams This is an example of the terminal output when debugging a Teams agent with the Microsoft 365 Agents Toolkit. It shows the application starting, listening on a specific port, and indicating that development tools are available. Note that dev tools are not secure for production. ```bash [INFO] Microsoft.Hosting.Lifetime Now listening on: http://localhost:3978 [WARN] Echo.Microsoft.Teams.Plugins.AspNetCore.DevTools ⚠️ Devtools are not secure and should not be used production environments ⚠️ [INFO] Echo.Microsoft.Teams.Plugins.AspNetCore.DevTools Available at http://localhost:3978/devtools [INFO] Microsoft.Hosting.Lifetime Application started. Press Ctrl+C to shut down. [INFO] Microsoft.Hosting.Lifetime Hosting environment: Development ``` -------------------------------- ### Store Conversation ID on Install (C#) Source: https://microsoft.github.io/teams-ai/csharp/essentials/sending-messages/proactive-messaging This C# code snippet demonstrates how to capture and store a user's conversation ID when they install the Teams application. This ID is essential for sending proactive messages later. It uses an activity handler to get the ID and store it in a persistent storage mechanism. ```csharp // Installation is just one place to get the conversation id. All activities // have the conversation id, so you can use any activity to get it. [Install] public async Task OnInstall([Context] InstallUpdateActivity activity, [Context] IContext.Client client, [Context] IStorage storage) { // Save the conversation id in storage.Set(activity.From.AadObjectId!, activity.Conversation.Id); await client.Send("Hi! I am going to remind you to say something to me soon!"); notificationQueue.AddReminder(activity.From.AadObjectId!, Notifications.SendProactive, 10_000); } ``` -------------------------------- ### Create Teams OAuth App with Graph Template (CLI) Source: https://microsoft.github.io/teams-ai/python/in-depth-guides/user-authentication/quickstart This command bootstraps a new Teams application using the 'graph' template, setting up necessary files for OAuth integration with Microsoft Graph. It creates a project directory, agent template files, and manifest files required for Teams app sideloading. ```bash teams new python oauth-app --template graph ``` -------------------------------- ### Example Terminal Output During Debugging Source: https://microsoft.github.io/teams-ai/python/getting-started/running-in-teams This snippet shows the expected output in your terminal when the Microsoft 365 Agents Toolkit successfully builds, provisions, and starts your Teams AI v2 agent for local debugging. It indicates the HTTP server is running and the application is ready. ```log [INFO] @teams/app Successfully initialized all plugins [INFO] @teams/app.HttpPlugin Starting HTTP server on port 3978 INFO: Started server process [6436] INFO: Waiting for application startup. [INFO] @teams/app.HttpPlugin listening on port 3978 🚀 [INFO] @teams/app Teams app started successfully INFO: Application startup complete.. INFO: Uvicorn running on http://0.0.0.0:3979 (Press CTRL+C to quit) ``` -------------------------------- ### Add Multiple Functions to ChatPrompt - TypeScript Source: https://microsoft.github.io/teams-ai/typescript/in-depth-guides/ai/function-calling Illustrates how to add multiple functions to a ChatPrompt for more complex scenarios in Teams AI v2. The LLM can then choose which function(s) to call based on the conversation context. This example shows functions for getting user location and searching weather, demonstrating how the LLM can chain function calls. ```typescript // activity.text could be something like "what's my weather?" // The LLM will need to first figure out the user's location // Then pass that in to the weatherSearch const prompt = new ChatPrompt({ instructions: 'You are a helpful assistant that can help the user get the weather', model, }) // Include multiple `function`s as part of the prompt .function( 'getUserLocation', 'gets the location of the user', // This function doesn't need any parameters, // so we do not need to provide a schema async () => { const locations = ['Seattle', 'San Francisco', 'New York']; const randomIndex = Math.floor(Math.random() * locations.length); const location = locations[randomIndex]; log.info('Found user location', location); return location; } ) .function( 'weatherSearch', 'search for weather', { type: 'object', properties: { location: { type: 'string', description: 'the name of the location', }, }, required: ['location'], }, async ({ location }: { location: string }) => { const weatherByLocation: Record = { Seattle: { temperature: 65, condition: 'sunny' }, 'San Francisco': { temperature: 60, condition: 'foggy' }, 'New York': { temperature: 75, condition: 'rainy' }, }; const weather = weatherByLocation[location]; if (!weather) { return 'Sorry, I could not find the weather for that location'; } log.info('Found weather', weather); return weather; } ); // The LLM will then produce a final response to be sent back to the user const result = await prompt.send(activity.text); await send(result.content ?? 'Sorry I could not figure it out'); ``` -------------------------------- ### Application Startup and Authentication Source: https://microsoft.github.io/teams-ai/csharp/getting-started/code-basics Illustrates the core code responsible for building and running the Teams application server. This snippet initializes the application and, when configured for Teams, handles authentication for message sending and receiving. ```csharp var app = builder.Build(); app.UseTeams(); app.Run(); ``` -------------------------------- ### Install Teams AI v2 using uv Source: https://microsoft.github.io/teams-ai/python/migrations/v1 This command installs the Microsoft Teams Apps package, which includes Teams AI v2, into your project. It does not overwrite existing Teams AI v1 installations. After migration, the `teams-ai` dependency can be removed from `pyproject.toml`. ```bash uv add microsoft-teams-apps ``` -------------------------------- ### Add Agents Toolkit OAuth Configuration (CLI) Source: https://microsoft.github.io/teams-ai/python/in-depth-guides/user-authentication/quickstart This command integrates the Agents Toolkit OAuth configuration into an existing or newly created Teams application. It adds the necessary files and configurations to handle OAuth authentication flows within the Teams app. ```bash teams config add atk.oauth ``` -------------------------------- ### Install MCP Client Package (dotnet) Source: https://microsoft.github.io/teams-ai/csharp/in-depth-guides/ai/mcp/mcp-client This command installs the Microsoft.Teams.Plugins.External.McpClient package as a prerelease version. This package is essential for integrating the MCP client into your .NET application. ```bash dotnet add package Microsoft.Teams.Plugins.External.McpClient --prerelease ``` -------------------------------- ### Initialize Teams Application with ASP.NET Core Source: https://microsoft.github.io/teams-ai/csharp/getting-started/code-basics Sets up a new Teams application using ASP.NET Core. It configures the application builder with Teams-specific extensions and registers the MainController for handling activities. This is the entry point for the application's execution. ```csharp using Microsoft.Teams.Plugins.AspNetCore.DevTools.Extensions; using Microsoft.Teams.Plugins.AspNetCore.Extensions; using Quote.Agent; var builder = WebApplication.CreateBuilder(args); builder.AddTeams(); builder.AddTeamsDevTools(); builder.Services.AddTransient(); var app = builder.Build(); app.UseTeams(); app.Run(); ``` -------------------------------- ### Install Teams AI Dev Package Source: https://microsoft.github.io/teams-ai/developer-tools/devtools/chat Installs the necessary development package for Teams AI DevTools. This package provides the DevtoolsPlugin for local testing and debugging of your Teams application's chat features. ```bash $: npm install @microsoft/teams.dev ``` -------------------------------- ### Teams AI v1: Setting up AI Components and Actions Source: https://microsoft.github.io/teams-ai/typescript/migrations/v1 This snippet shows how to initialize OpenAI or Azure OpenAI models, set up a PromptManager, define prompt functions, and configure an ActionPlanner and Application in Teams AI v1. It also demonstrates registering action handlers for 'ToggleLights' and 'Pause'. ```typescript const model = new OpenAIModel({ // OpenAI Support apiKey: process.env.OPENAI_KEY!, defaultModel: 'gpt-4o', // Azure OpenAI Support azureApiKey: process.env.AZURE_OPENAI_KEY!, azureDefaultDeployment: 'gpt-4o', azureEndpoint: process.env.AZURE_OPENAI_ENDPOINT!, azureApiVersion: '2023-03-15-preview', // Request logging logRequests: true }); const prompts = new PromptManager({ promptsFolder: path.join(__dirname, '../src/prompts') }); // Define a prompt function for getting the current status of the lights prompts.addFunction('getLightStatus', async (context, memory) => { return memory.getValue('conversation.lightsOn') ? 'on' : 'off'; }); const planner = new ActionPlanner({ model, prompts, defaultPrompt: 'tools' }); // Define storage and application const storage = new MemoryStorage(); const app = new Application({ storage, ai: { planner } }); // Register action handlers app.ai.action('ToggleLights', async (context, state) => { state.conversation.lightsOn = !state.conversation.lightsOn; const lightStatusText = state.conversation.lightsOn ? "on" : "off"; await context.sendActivity(`[lights ${lightStatusText}]`); return `the lights are now ${lightStatusText}$ `; }); interface PauseParameters { time: number; } app.ai.action('Pause', async (context, state, parameters: PauseParameters) => { await context.sendActivity( `[pausing for ${parameters.time / 1000} seconds]`, ); await new Promise((resolve) => setTimeout(resolve, parameters.time)); return `done pausing`; }, ); // Listen for incoming server requests. server.post('/api/messages', async (req, res) => { // Route received a request to adapter for processing await adapter.process(req, res as any, async (context) => { // Dispatch to application for routing await app.run(context); }); }); ``` -------------------------------- ### Store Conversation ID on Install - Python Source: https://microsoft.github.io/teams-ai/python/essentials/sending-messages/proactive-messaging This snippet demonstrates how to store a user's conversation ID when they install the Teams application. It uses an `on_install_add` activity handler to save the ID in a dictionary and schedules a proactive notification. ```python # This would be some persistent storage storage = dict[str, str]() # Installation is just one place to get the conversation_id. All activities have this field as well. @app.on_install_add async def handle_install_add(ctx: ActivityContext[InstalledActivity]): # Save the conversation_id storage[ctx.activity.from_.aad_object_id] = ctx.activity.conversation.id await ctx.send("Hi! I am going to remind you to say something to me soon!") # This queues up the proactive notifaction to be sent in 1 minute notication_queue.add_reminder(ctx.activity.from_.aad_object_id, send_proactive_notification, 60000) ``` -------------------------------- ### Application setup for Teams AI in ASP.NET Core in C# Source: https://microsoft.github.io/teams-ai/csharp/in-depth-guides/ai/best-practices This C# code illustrates how to configure a Microsoft Teams AI application using modern ASP.NET Core patterns. It sets up services, enables Teams integration, developer tools, and OpenAI functionality. Dependencies include Microsoft.Teams.AI.Models.OpenAI.Extensions, Microsoft.Teams.Apps.Extensions, Microsoft.Teams.Plugins.AspNetCore.DevTools.Extensions, and Microsoft.Teams.Plugins.AspNetCore.Extensions. ```csharp using Microsoft.Teams.AI.Models.OpenAI.Extensions; using Microsoft.Teams.Apps.Extensions; using Microsoft.Teams.Plugins.AspNetCore.DevTools.Extensions; using Microsoft.Teams.Plugins.AspNetCore.Extensions; var builder = WebApplication.CreateBuilder(args); builder.Services.AddSingleton(); builder.AddTeams().AddTeamsDevTools().AddOpenAI(); var app = builder.Build(); app.UseTeams(); app.Run(); ``` -------------------------------- ### Install Teams AI v2 using npm Source: https://microsoft.github.io/teams-ai/typescript/migrations/v1 Installs the Teams AI v2 package into your project. This command is used to add the necessary dependencies for the new version of the SDK. After successful migration, the v1 dependency can be removed. ```bash npm install @microsoft.teams.apps ``` -------------------------------- ### Basic Project Structure for Teams Application Source: https://microsoft.github.io/teams-ai/csharp/getting-started/code-basics Illustrates the fundamental directory layout generated when creating a new Teams application. Key directories include 'appPackage' for manifest and icons, and core C# files like 'Program.cs' and 'MainController.cs'. ```text Quote.Agent/ |── appPackage/ # Teams app package files ├── Program.cs # Main application startup code ├── MainController.cs # Main activity handling code ``` -------------------------------- ### Create New Tab App with Teams CLI Source: https://microsoft.github.io/teams-ai/typescript/in-depth-guides/tabs/getting-started Scaffolds a new tab app project with the Microsoft 365 Agents Toolkit using the Teams CLI. This command initializes a project structure suitable for developing AI-powered Teams applications. ```shell teams new typescript my-first-tab-app --atk embed --template tab ``` -------------------------------- ### Configure Teams AI with OpenAI and UtilityPrompt in C# Source: https://microsoft.github.io/teams-ai/csharp/in-depth-guides/ai/function-calling This C# code demonstrates the setup for a Microsoft Teams AI application. It configures the web application to use OpenAI with the `UtilityPrompt` class, enabling AI-driven responses based on the defined utility functions. This involves adding necessary services and middleware to the application pipeline. ```csharp using Microsoft.Teams.AI.Models.OpenAI.Extensions; using Microsoft.Teams.Apps.Extensions; using Microsoft.Teams.Plugins.AspNetCore.Extensions; using UtilityApp; var builder = WebApplication.CreateBuilder(args); builder.Services.AddSingleton(); builder.AddTeams().AddOpenAI(); var app = builder.Build(); app.UseTeams(); app.Run(); ``` -------------------------------- ### Complete TaskSubmit Handler Example (C#) Source: https://microsoft.github.io/teams-ai/csharp/in-depth-guides/dialogs/handling-dialog-submissions A comprehensive example of the `OnTaskSubmit` handler in C# that accommodates multiple dialog submission types, including 'simple_form' from Adaptive Cards and 'webpage_dialog' from rendered webpages. It centralizes the logic for parsing submission data and responding appropriately. ```csharp [TaskSubmit] public async Task OnTaskSubmit([Context] Tasks.SubmitActivity activity, [Context] IContext.Client client, [Context] ILogger log) { var data = activity.Value?.Data as JsonElement?; if (data == null) { log.Info("[TASK_SUBMIT] No data found in the activity value"); return new Response(new MessageTask("No data found in the activity value")); } var submissionType = data.Value.TryGetProperty("submissiondialogtype", out var submissionTypeObj) && submissionTypeObj.ValueKind == JsonValueKind.String ? submissionTypeObj.ToString() : null; string? GetFormValue(string key) { if (data.Value.TryGetProperty(key, out var val)) { if (val is JsonElement element) return element.GetString(); return val.ToString(); } return null; } switch (submissionType) { case "simple_form": var name = GetFormValue("name") ?? "Unknown"; await client.Send($"Hi {name}, thanks for submitting the form!"); return new Response(new MessageTask("Form was submitted")); case "webpage_dialog": var webName = GetFormValue("name") ?? "Unknown"; var email = GetFormValue("email") ?? "No email"; await client.Send($"Hi {webName}, thanks for submitting the form! We got that your email is {email}"); return new Response(new MessageTask("Form submitted successfully")); default: return new Response(new MessageTask("Unknown submission type")); } } ``` -------------------------------- ### Project Structure for Teams AI Application Source: https://microsoft.github.io/teams-ai/typescript/in-depth-guides/ai/setup-and-prereqs This snippet illustrates a typical project directory structure for a Teams AI application. It highlights the location of the Teams app package, main application code (index.ts), and the environment variables file (.env). ```tree my-app/ |── appPackage/ # Teams app package files ├── src/ │ └── index.ts # Main application code |── .env # Environment variables ``` -------------------------------- ### Type-Safe Authoring Example for TextBlock Source: https://microsoft.github.io/teams-ai/python/in-depth-guides/adaptive-cards/building-adaptive-cards Demonstrates type-safe authoring within the `microsoft-teams-cards` library. This example highlights how invalid property values, such as 'huge' for the 'size' attribute of a TextBlock, will result in build errors due to the strict Python types derived from the Adaptive Card schema. ```python # "huge" is not a valid size for TextBlock text_block = TextBlock(text="Test", wrap=True, weight="Bolder", size="huge"), ``` -------------------------------- ### Serve Settings HTML Page Source: https://microsoft.github.io/teams-ai/csharp/in-depth-guides/message-extensions/settings This section provides the HTML code for the settings page and instructions on how to serve it using static files and a specific endpoint. ```APIDOC ## Serve the settings `html` page This is the code snippet for the settings `html` page: ```html Message Extension Settings

Message Extension Settings

``` Save it in the `index.html` file in the same folder as where your app is initialized. You can serve it by adding the following code to your app: ```csharp // In your startup configuration (Program.cs or Startup.cs) app.UseStaticFiles(); app.MapGet("/tabs/settings", async context => { var html = await File.ReadAllTextAsync("wwwroot/settings.html"); context.Response.ContentType = "text/html"; await context.Response.WriteAsync(html); }); ``` **Note:** This will serve the HTML page to the `${BOT_ENDPOINT}/tabs/settings` endpoint as a tab. ``` -------------------------------- ### Teams AI v1 Authentication Setup and Event Handling (JavaScript) Source: https://microsoft.github.io/teams-ai/typescript/migrations/v1 Demonstrates setting up authentication with MemoryStorage and configuring auto-sign-in logic for a Microsoft Teams AI v1 application. It includes handlers for sign-in success and failure events, and message handlers for '/signout', '/signin', and '/help' commands. ```javascript const storage = new MemoryStorage(); const app = new Application({ storage: new MemoryStorage(), authentication: { autoSignIn: (context) => { const activity = context.activity; // No auth when user wants to sign in if (activity.text === "/signout") { return Promise.resolve(false); } // No auth for "/help" if (activity.text === "/help") { return Promise.resolve(false); } // Manually sign in (for illustrative purposes) if (activity.text === "/signin") { return Promise.resolve(false); } // For all other messages, require sign in return Promise.resolve(true); }, settings: { graph: { connectionName: process.env.OAUTH_CONNECTION_NAME!, title: "Sign in", text: "Please sign in to use the bot.", endOnInvalidMessage: true, tokenExchangeUri: process.env.TOKEN_EXCHANGE_URI!, enableSso: true, }, }, } }); app.message( "/signout", async (context, state) => { await app.authentication.signOutUser(context, state); // Echo back users request await context.sendActivity(`You have signed out`); } ); app.message( "/signin", async (context, state) => { let token = state.temp.authTokens['graph']; if (!token) { const res = await app.authentication.signInUser(context, state); if (res.error) { console.log(res.error); return; } token = state.temp.authTokens['graph']; } if (token) { // Echo back users request await context.sendActivity(`You are already authenticated!`); return; } // Sign in is pending... } ); app.message( "/help", async (context, state) => { await context.sendActivity(`your help text`); } ); app.authentication.get('graph') .onUserSignInSuccess(async (context, state) => { // Successfully logged in await context.sendActivity('Successfully logged in'); await context.sendActivity( `Token string length: ${state.temp.authTokens['graph']!.length}`, ); }); app.authentication .get('graph') .onUserSignInFailure(async (context, _state, error) => { // Failed to login await context.sendActivity( `Failed to login with error: ${error.message}`, ); }); ``` -------------------------------- ### Store Conversation ID on Install (JavaScript) Source: https://microsoft.github.io/teams-ai/csharp/essentials/sending-messages/proactive-messaging This JavaScript code snippet illustrates how to store a user's conversation ID upon installation of the Teams application. This stored ID is crucial for enabling future proactive messaging. The code utilizes an event handler to retrieve and save the conversation ID. ```javascript app.OnInstall(async context => { // Save the conversation id in context.Storage.Set(activity.From.AadObjectId!, activity.Conversation.Id); await context.Send("Hi! I am going to remind you to say something to me soon!"); notificationQueue.AddReminder(activity.From.AadObjectId!, Notifications.SendProactive, 10_000); }); ``` -------------------------------- ### Lifecycle Routes Source: https://microsoft.github.io/teams-ai/typescript/essentials/on-activity/activity-ref Routes triggered by application lifecycle events such as installation, removal, and updates. ```APIDOC ## Lifecycle Routes ### Description Handles events related to the application's lifecycle. ### Method POST ### Endpoint `/install/add` or `/install/remove` or `/install/update` or `/handoff/action` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **type** (string) - The lifecycle event type (e.g., `install.add`). ### Request Example ```json { "type": "install.add" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the status of the lifecycle event. #### Response Example ```json { "status": "processed" } ``` ``` -------------------------------- ### Teams AI v2 Authentication Setup and Message Handling (JavaScript) Source: https://microsoft.github.io/teams-ai/typescript/migrations/v1 Illustrates setting up authentication for a Microsoft Teams AI v2 application using OAuth configurations. It includes message handlers for '/signout' and '/help', and a default message handler that prompts users to sign in if they are not already authenticated. ```javascript const app = new App({ oauth: { // oauth configurations /** * The name of the auth connection to use. * It should be the same as the OAuth connection name defined in the Azure Bot configuration. */ defaultConnectionName: 'graph' }, logger: new ConsoleLogger('@tests/auth', { level: 'debug' }) }); app.message('/signout', async (client) => { if (!client.isSignedIn) return; await client.signout(); // call signout for your auth connection... await client.send('you have been signed out!'); }); app.message('/help', async (client) => { await client.send("your help text") }); app.on('message', async (client) => { if (!client.isSignedIn) { await client.signin({ // Customize the OAuth card text (only renders in OAuth flow, not SSO) oauthCardText: 'Sign in to your account', signInButtonText: 'Sign in' }); // call signin for your auth connection... return; } const me = await client.userGraph.me.get(); log.info(`user "${me.displayName}" already signed in!`); }); app.event('signin', async (client) => { const me = await client.userGraph.me.get(); await client.send(`user "${me.displayName}" signed in.`); await client.send(`Token string length: ${client.token.token.length}`); }); ``` -------------------------------- ### Initialize Teams App with DevTools Plugin Source: https://microsoft.github.io/teams-ai/python/getting-started/code-basics Initializes the main application instance using the App class from the Teams AI SDK and includes the DevToolsPlugin for development purposes. This is the entry point for the application's core functionality. ```python from microsoft.teams.api import MessageActivity, TypingActivityInput from microsoft.teams.apps import ActivityContext, App, AppOptions from microsoft.teams.devtools import DevToolsPlugin app = App(plugins=[DevToolsPlugin()]) ``` -------------------------------- ### Error Log for Missing Service Principal in C# Source: https://microsoft.github.io/teams-ai/csharp/getting-started/running-in-teams/deployment-guide This snippet displays a typical error log encountered when an Azure Bot Service application has a single-tenant configuration ('msaAppType: "SingleTenant"') but lacks a corresponding Service Principal in the Azure tenant. The error indicates an 'invalid_client' issue with AADSTS7000229, guiding the user to create the missing Service Principal. ```log [ERROR] Echobot Failed to get bot token on app startup. [ERROR] Echobot { [ERROR] Echobot "error": "invalid_client", [ERROR] Echobot "error_description": "AADSTS7000229: The client application 78b9b9b6-6a3d-4c8f-9a53-95701700b726 is missing service principal in the tenant 50612dbb-0237-4969-b378-8d42590f9c00. See instructions here: https://go.microsoft.com/fwlink/?linkid=2225119 Trace ID: 2965b26b-acdd-4cd7-8943-728a92074900 Correlation ID: 5a27b7c5-4754-4f0d-ac66-0bf9eec02fd9 Timestamp: 2025-09-18 02:26:20Z", [ERROR] Echobot "error_codes": [ [ERROR] Echobot 7000229 [ERROR] Echobot ], [ERROR] Echobot "timestamp": "2025-09-18 02:26:20Z", [ERROR] Echobot "trace_id": "2965b26b-acdd-4cd7-8943-728a92074900", [ERROR] Echobot "correlation_id": "5a27b7c5-4754-4f0d-ac66-0bf9eec02fd9", [ERROR] Echobot "error_uri": "https://login.microsoftonline.com/error?code=7000229" [ERROR] Echobot } ```