### Install Teams App CLI and Sync Source: https://github.com/microsoft/teams-agent-accelerator-templates/blob/main/python/memory-sample-agent/README.md Shell commands to install the Teams application CLI globally and synchronize the project environment. These are initial setup steps before running the application. ```shell npm install -g @microsoft/teamsapp-cli uv sync ``` -------------------------------- ### Install Playwright Browsers Source: https://github.com/microsoft/teams-agent-accelerator-templates/blob/main/python/computer-use-agent/README.md Installs the necessary browsers required by Playwright for automated browser testing and interaction. This command should be run in the project's environment. ```bash playwright install ``` -------------------------------- ### Start Teams App Test Tool Source: https://github.com/microsoft/teams-agent-accelerator-templates/blob/main/python/memory-sample-agent/README.md Command to start the Teams App Test Tool. This will launch a test website for debugging the application in a simulated Teams environment. ```shell node src/devTools/teamsapptester/node_modules/@microsoft/teams-app-test-tool/cli.js start ``` -------------------------------- ### .NET Application Setup for Teams Bot Source: https://context7.com/microsoft/teams-agent-accelerator-templates/llms.txt Initializes the .NET web application builder for a Microsoft Teams bot. This is the entry point for the application, setting up the necessary services and configuration. It relies on the standard .NET `WebApplicationBuilder`. ```.NET using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.ChatCompletion; using Microsoft.SemanticKernel.Connectors.OpenAI; using Microsoft.Teams.AI; using Microsoft.Bot.Builder; using System.ComponentModel; using System.Text.Json; // Application setup public class Program { public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); // ... further application setup } } ``` -------------------------------- ### Environment Setup for Data Analyst Agent (Bash) Source: https://github.com/microsoft/teams-agent-accelerator-templates/blob/main/js/data-analyst-agent/README.md This snippet guides the user through setting up the environment variables for the data analyst agent. It involves copying a sample environment file and updating it with specific configurations like bot IDs, passwords, and API keys for Azure OpenAI or OpenAI. ```bash cp sample.env .env # Update .env with your configuration details (BOT_ID, BOT_PASSWORD, OpenAI/Azure OpenAI settings) ``` -------------------------------- ### Install Dependencies using npm Source: https://github.com/microsoft/teams-agent-accelerator-templates/blob/main/js/data-analyst-agent-v2/README.md Installs the necessary project dependencies using the Node Package Manager (npm). This command should be run after cloning the repository to set up the project environment. ```bash npm install ``` -------------------------------- ### Clone Repository and Install Dependencies (Bash) Source: https://github.com/microsoft/teams-agent-accelerator-templates/blob/main/js/data-analyst-agent/README.md This snippet shows how to clone the project repository and install the necessary Node.js dependencies using npm. It's a standard first step for setting up the project locally. ```bash git clone https://github.com/microsoft/teams-agent-accelerator-samples cd js/data-analyst-agent npm install ``` -------------------------------- ### Run Python Application Source: https://github.com/microsoft/teams-agent-accelerator-templates/blob/main/python/memory-sample-agent/README.md Command to run the main Python application script. Successful execution will start a local server on http://localhost:3978. ```shell python src/app.py ``` -------------------------------- ### Install Teams App Test Tool Source: https://github.com/microsoft/teams-agent-accelerator-templates/blob/main/python/memory-sample-agent/README.md Shell commands to create a directory and install the Teams App Test Tool locally within the project. This tool is used for debugging and testing the Teams application. ```shell mkdir -p src/devTool/teamsapptester npm i @microsoft/teams-app-test-tool --prefix "src/devTools/teamsapptester" ``` -------------------------------- ### Deploy and Publish Teams App Source: https://context7.com/microsoft/teams-agent-accelerator-templates/llms.txt Configures the deployment and publishing phases for a Teams application. This includes installing Node.js dependencies, building the application, deploying to Azure App Service, and publishing the app package to the Teams store. ```yaml deploy: # Install dependencies - uses: cli/runNpmCommand with: args: install --no-audit # Build application - uses: cli/runNpmCommand with: args: run build --if-present # Deploy to Azure App Service - uses: azureAppService/zipDeploy with: artifactFolder: . ignoreFile: .webappignore resourceId: ${{BOT_AZURE_APP_SERVICE_RESOURCE_ID}} publish: # Publish to Teams store - uses: teamsApp/publishAppPackage with: appPackagePath: ./appPackage/build/appPackage.${{TEAMSFX_ENV}}.zip writeToEnvironmentFile: publishedAppId: TEAMS_APP_PUBLISHED_APP_ID ``` -------------------------------- ### Local Bot Deployment with Teams Toolkit Source: https://github.com/microsoft/teams-agent-accelerator-templates/blob/main/js/data-analyst-agent-v2/README.md Starts the local bot server and initiates a debug session using the Teams Toolkit extension in Visual Studio Code. This option includes tunneling for external access and automatically loads the bot into Teams. ```bash Press F5 in Visual Studio Code ``` -------------------------------- ### Debug in Teams (VSCode) Source: https://github.com/microsoft/teams-agent-accelerator-templates/blob/main/python/memory-sample-agent/README.md Instructions to debug the application directly within Microsoft Teams using VSCode. This involves starting the local server, sideloading the bot, and setting up a tunnel. ```shell uv sync .venv\Scripts\Activate # Then use VSCode's 'Run and Debug' tab and select 'Debug in Teams (Edge)' ``` -------------------------------- ### Instantiate Repository Service - C# Source: https://github.com/microsoft/teams-agent-accelerator-templates/blob/main/dotnet/dex-agent/README.md Demonstrates how to instantiate a concrete repository service implementation, such as GitHubService, which depends on various components like storage, adapter, and a plugin. This is typically done during application startup. ```csharp GitHubPlugin plugin = new(client, config); return new GitHubService(storage, adapter, plugin); ``` -------------------------------- ### Deploy to Azure App Service Source: https://github.com/microsoft/teams-agent-accelerator-templates/blob/main/python/memory-sample-agent/README.md Action within the VSCode Teams Toolkit extension to deploy the application to the provisioned Azure App Service instance. This step includes running the startup script. ```shell # Within VSCode Teams Toolkit extension: Lifecycle -> Deploy ``` -------------------------------- ### Provision Teams App and Bot Resources Source: https://context7.com/microsoft/teams-agent-accelerator-templates/llms.txt Defines the provisioning steps for creating a Teams app registration, an Azure AD app for bot authentication, deploying Azure infrastructure using Bicep, creating the bot service resource, validating the manifest, zipping the app package, and updating the Teams app. ```yaml version: 1.0.0 projectId: 12345678-1234-1234-1234-123456789abc environmentFolderPath: ./env provision: # Create Teams app registration - uses: teamsApp/create with: name: DataAnalystBot-${{APP_NAME_SUFFIX}} writeToEnvironmentFile: teamsAppId: TEAMS_APP_ID # Create Azure AD app for bot authentication - uses: botAadApp/create with: name: DataAnalystBot-${{APP_NAME_SUFFIX}} writeToEnvironmentFile: botId: BOT_ID botPassword: SECRET_BOT_PASSWORD # Deploy Azure infrastructure - uses: arm/deploy with: subscriptionId: ${{AZURE_SUBSCRIPTION_ID}} resourceGroupName: ${{AZURE_RESOURCE_GROUP_NAME}} templates: - path: ./infra/azure.bicep parameters: ./infra/azure.parameters.json deploymentName: Deploy-${{TEAMSFX_ENV}}-${{TIMESTAMP}} bicepCliVersion: v0.9.1 # Create bot service resource - uses: botFramework/create with: botId: ${{BOT_ID}} name: DataAnalystBot messagingEndpoint: ${{BOT_ENDPOINT}}/api/messages description: "AI-powered data analyst for Teams" channels: - name: msteams # Validate manifest - uses: teamsApp/validateManifest with: manifestPath: ./appPackage/manifest.json # Zip app package - uses: teamsApp/zipAppPackage with: manifestPath: ./appPackage/manifest.json outputZipPath: ./appPackage/build/appPackage.${{TEAMSFX_ENV}}.zip outputJsonPath: ./appPackage/build/manifest.${{TEAMSFX_ENV}}.json # Update Teams app - uses: teamsApp/update with: appPackagePath: ./appPackage/build/appPackage.${{TEAMSFX_ENV}}.zip ``` -------------------------------- ### Configure Semantic Kernel and Bot Services (C#) Source: https://context7.com/microsoft/teams-agent-accelerator-templates/llms.txt Configures the Semantic Kernel for AI interactions and sets up the bot's core services, including LLM integration and plugin addition. It also initializes the bot application, storage, and message handling logic. Dependencies include Semantic Kernel, Azure OpenAI, and Microsoft Bot Framework. ```csharp builder.Services.AddTransient(sp => { var config = sp.GetRequiredService(); var kernelBuilder = Kernel.CreateBuilder(); // Add LLM kernelBuilder.AddAzureOpenAIChatCompletion( deploymentName: config.Azure.OpenAIDeploymentName, modelId: config.Azure.OpenAIModelId, apiKey: config.Azure.OpenAIApiKey, endpoint: config.Azure.OpenAIEndpoint ); // Add plugins var githubPlugin = new GitHubPlugin(config.GitHubToken); kernelBuilder.Plugins.AddFromObject(githubPlugin, "GitHubPlugin"); return kernelBuilder.Build(); }); // Configure bot builder.Services.AddTransient(sp => { var storage = new MemoryStorage(); var app = new ApplicationBuilder() .WithStorage(storage) .Build(); var kernel = sp.GetRequiredService(); var orchestrator = new KernelOrchestrator(kernel, storage, config); // Message handler app.OnActivity(ActivityTypes.Message, async (context, state, ct) => { await orchestrator.GetChatMessageContentAsync(context); }); // Adaptive card action handlers app.AdaptiveCards.OnActionSubmit("filter_prs", async (context, state, data, ct) => { var filters = data.ToObject(); var args = new KernelArguments { ["labels"] = filters.Labels, ["status"] = filters.Status }; await kernel.InvokeAsync("GitHubPlugin", "FilterPRs", args); }); return app; }); var app = builder.Build(); app.MapPost("/api/messages", async (HttpRequest req, IBot bot) => { await bot.OnTurnAsync(req); }); app.Run(); ``` -------------------------------- ### Clone Repository using Git Source: https://github.com/microsoft/teams-agent-accelerator-templates/blob/main/js/data-analyst-agent-v2/README.md Clones the Teams Agent Accelerator Samples repository from GitHub to your local machine. This is the initial step to obtain the project files. ```bash git clone https://github.com/microsoft/teams-agent-accelerator-samples cd js/data-analyst-agent-v2 ``` -------------------------------- ### Add Template to Gallery Configuration (JSON) Source: https://github.com/microsoft/teams-agent-accelerator-templates/blob/main/docs/README.md This JSON object is added to the `frontMatter.content.pageFolders` list in `frontmatter.json` to register a new template. The `path` property should point to the template's README.md file directory, and `title` provides a display name for the template in the gallery. ```json { "path": "[[workspace]]/python/memory-sample-agent", "title": "memory-sample-agent" } ``` -------------------------------- ### Copy Environment File Source: https://github.com/microsoft/teams-agent-accelerator-templates/blob/main/js/data-analyst-agent-v2/README.md Copies the sample environment file to a new file named '.env'. This file will store sensitive configurations like API keys and bot credentials. ```bash cp sample.env .env ``` -------------------------------- ### JavaScript Agent Framework: BaseAgent Class for Tool Calling Source: https://context7.com/microsoft/teams-agent-accelerator-templates/llms.txt Demonstrates the BaseAgent class for building LLM-powered agents with function registration and chat interface capabilities. It showcases defining response schemas, initializing the agent with system prompts and tools like SQL execution, and handling user queries. Dependencies include the '@teams.sdk/ai' library. ```typescript import { BaseAgent } from './core/base-agent'; import { JsonSchema } from './types'; // Define response structure const responseSchema: JsonSchema = { type: 'object', properties: { text: { type: 'string' }, data: { type: 'array', items: { type: 'object' } } } }; // Initialize agent with system prompt and tools const dataAnalyst = new BaseAgent({ systemMessage: `You are an expert data analyst for AdventureWorks database. When users ask questions, translate them to SQL queries using execute_sql function. Present results in clear, formatted tables with insights.`, responseSchema: responseSchema, logger: logger, maxLoops: 20 }) .function('execute_sql', 'Execute SQL query against AdventureWorks database', { type: 'object', properties: { query: { type: 'string', description: 'Valid SELECT query' } }, required: ['query'] }, async ({ query }) => { // Validate query safety if (!/^SELECT/i.test(query.trim()) || /DELETE|DROP|INSERT|UPDATE/i.test(query)) { throw new Error('Only SELECT queries allowed'); } const db = await initializeDatabase(); const results = await db.all(query); return JSON.stringify({ rows: results.length, data: results }); }); // Chat with the agent const userQuery = "What were the top 5 products by sales in 2021?"; const response = await dataAnalyst.chat(userQuery); // Response: { text: "Here are the top 5...", data: [...], card: AdaptiveCard } ``` -------------------------------- ### Azure Deployment Configuration Source: https://github.com/microsoft/teams-agent-accelerator-templates/blob/main/js/data-analyst-agent-v2/README.md Sets up the environment for deploying the bot to Azure using Teams Toolkit. It involves creating specific environment files with Azure OpenAI credentials and then using the Toolkit for provisioning and deployment. ```bash Create an empty .env.dev file in the env folder. Create a .env.dev.user file in the env folder with: SECRET_AZURE_OPENAI_API_KEY= SECRET_AZURE_OPENAI_API_BASE= // Example: https://-eastus2.openai.azure.com/ SECRET_AZURE_OPENAI_API_VERSION= // Example: 2024-08-01-preview ``` -------------------------------- ### Create and Configure Dev Tunnel Source: https://github.com/microsoft/teams-agent-accelerator-templates/blob/main/python/computer-use-agent/README.md Demonstrates how to create, configure ports for, and grant anonymous access to a dev tunnel using the devtunnel CLI. This is useful for exposing local services to the internet. ```bash devtunnel create devtunnel port create -p devtunnel access create -p --anonymous ``` -------------------------------- ### Build Memory Module Source: https://github.com/microsoft/teams-agent-accelerator-templates/blob/main/python/memory-sample-agent/README.md Command to build the memory module into a distribution file. The output artifact is expected to be 'dist/teams_memory-0.1.0.tar.gz'. ```shell uv build packages/teams_memory ``` -------------------------------- ### Publish App Package Source: https://github.com/microsoft/teams-agent-accelerator-templates/blob/main/python/memory-sample-agent/README.md Action within the VSCode Teams Toolkit extension to create an application package (`.zip`) after successful deployment. This package is used for sideloading the app into Teams. ```shell # Within VSCode Teams Toolkit extension: Lifecycle -> Publish ``` -------------------------------- ### OpenAI Configuration Source: https://github.com/microsoft/teams-agent-accelerator-templates/blob/main/python/memory-sample-agent/README.md Configuration parameters for connecting to OpenAI services. Requires API key, model names for GPT and embeddings. This is an alternative to Azure OpenAI configuration. ```env OPENAI_MODEL_NAME=gpt-4o OPENAI_API_KEY= OPENAI_EMBEDDING_MODEL_NAME=text-embedding-3-small ``` -------------------------------- ### Environment Configuration (.env.local) Source: https://context7.com/microsoft/teams-agent-accelerator-templates/llms.txt Defines environment variables for local development and application configuration, including bot credentials, LLM settings, database connection, feature flags, and Teams app IDs. ```bash # .env.local - Local development BOT_ID= BOT_PASSWORD= BOT_DOMAIN=localhost:3978 # LLM Configuration OPENAI_API_KEY=sk-... AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com AZURE_OPENAI_API_KEY=... AZURE_OPENAI_DEPLOYMENT_NAME=gpt-4o DEFAULT_LLM_MODEL=gpt-4o # Database DATABASE_URL=./data/adventureworks.db # Features ENABLE_STREAMING=true MAX_LOOP_COUNT=20 LOG_LEVEL=debug # Teams specific TEAMS_APP_ID=${{TEAMS_APP_ID}} ``` -------------------------------- ### Build Docker Image for Agent Source: https://github.com/microsoft/teams-agent-accelerator-templates/blob/main/python/computer-use-agent/README.md Builds a Docker image tagged as 'cua_mode_image' from the current directory's Dockerfile. This image is used to create sandboxed environments for the agent. ```bash docker build -t cua_mode_image . ``` -------------------------------- ### Provision Azure Resources Source: https://github.com/microsoft/teams-agent-accelerator-templates/blob/main/python/memory-sample-agent/README.md Action within the VSCode Teams Toolkit extension to provision necessary resources in Azure for the application deployment. This is a prerequisite for deploying the application. ```shell # Within VSCode Teams Toolkit extension: Lifecycle -> Provision ``` -------------------------------- ### Azure OpenAI Configuration Source: https://github.com/microsoft/teams-agent-accelerator-templates/blob/main/python/memory-sample-agent/README.md Configuration parameters for connecting to Azure OpenAI services. Requires API key, deployment names for GPT and embeddings, API base URL, and API version. These settings are crucial for the application's AI functionalities. ```env AZURE_OPENAI_API_KEY= AZURE_OPENAI_DEPLOYMENT=gpt-4o AZURE_OPENAI_EMBEDDING_DEPLOYMENT=text-embedding-3-small AZURE_OPENAI_API_BASE=https://.openai.azure.com AZURE_OPENAI_API_VERSION= ``` -------------------------------- ### Configure Azure and GitHub API Keys for DEX Agent Source: https://github.com/microsoft/teams-agent-accelerator-templates/blob/main/dotnet/dex-agent/README.md Configuration snippet for setting up Azure OpenAI and GitHub API keys. This includes endpoints, deployment names, and authentication credentials required for the agent to interact with Azure services and GitHub. ```json { "Azure": { "OpenAIApiKey": "", "OpenAIEndpoint": "", "OpenAIDeploymentName": "gpt-4o", "OpenAIModelId": "gpt-4o" }, "GITHUB_OWNER": "", "GITHUB_REPOSITORY": "", "GITHUB_CLIENT_ID": "", "GITHUB_CLIENT_SECRET": "" } ``` -------------------------------- ### Activate Python Virtual Environment Source: https://github.com/microsoft/teams-agent-accelerator-templates/blob/main/python/memory-sample-agent/README.md Command to activate the Python virtual environment. This is necessary to run Python scripts and ensure dependencies are correctly managed. ```shell .venv\Scripts\Activate ``` -------------------------------- ### .NET GitHub Plugin for Semantic Kernel Source: https://context7.com/microsoft/teams-agent-accelerator-templates/llms.txt Defines a GitHub plugin with functions to list pull requests and retrieve PR details. It utilizes Semantic Kernel's `KernelFunction` attribute for discoverability and integrates with adaptive cards for rich responses in Microsoft Teams. Dependencies include `Microsoft.SemanticKernel` and `Microsoft.Teams.AI`. ```.NET using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.ChatCompletion; using Microsoft.SemanticKernel.Connectors.OpenAI; using Microsoft.Teams.AI; using Microsoft.Bot.Builder; using System.ComponentModel; using System.Text.Json; // Plugin definition public class GitHubPlugin { private readonly GitHubClient _client; // Assuming GitHubClient is defined elsewhere public GitHubPlugin(string token) { _client = new GitHubClient(token); } [KernelFunction] [Description("List all pull requests from the repository")] public async Task ListPRs( [Description("Repository owner")] string owner, [Description("Repository name")] string repo, ITurnContext context ) { var pullRequests = await _client.GetPullRequestsAsync(owner, repo); // Create adaptive card var card = new AdaptiveCard("1.5") { Body = new List { new AdaptiveTextBlock($"Pull Requests ({pullRequests.Count})") { Size = AdaptiveTextSize.Large, Weight = AdaptiveTextWeight.Bolder }, new AdaptiveContainer { Items = pullRequests.Select(pr => new AdaptiveTextBlock { Text = $"#{pr.Number}: {pr.Title}", Wrap = true }).ToList() } } }; var attachment = new Attachment { ContentType = "application/vnd.microsoft.card.adaptive", Content = card }; await context.SendActivityAsync(MessageFactory.Attachment(attachment)); return "Sent PR list card"; } [KernelFunction] [Description("Get details of a specific pull request")] public async Task GetPRDetails( [Description("Pull request number")] int prNumber ) { var pr = await _client.GetPullRequestAsync(prNumber); return JsonSerializer.Serialize(new { pr.Title, pr.Description, pr.Author, pr.Status, FilesChanged = pr.Files.Count, Comments = pr.Comments.Count }); } } ``` -------------------------------- ### Run Adaptive Card Generation Evaluation Tests Source: https://github.com/microsoft/teams-agent-accelerator-templates/blob/main/js/data-analyst-agent-v2/README.md Execute npm scripts to evaluate the agent's Adaptive Card visualization generation capabilities. These commands allow running all test cases or a single test case for debugging. The process involves loading test cases, generating cards, comparing results, and outputting to console and a log file. ```bash npm run eval:ac npm run eval:ac:one ``` -------------------------------- ### JavaScript Capability Routing: ChatPrompt for Function Delegation Source: https://context7.com/microsoft/teams-agent-accelerator-templates/llms.txt Implements a manager prompt pattern using ChatPrompt for routing user requests to specialized capabilities via function-based delegation. It defines capabilities like summarization and action item extraction, creates a manager prompt, registers delegation functions, and processes user messages to invoke the appropriate capability. Dependencies include '@teams.sdk/ai' and '@teams.sdk/ai-openai'. ```typescript import { ChatPrompt } from '@teams.sdk/ai'; import { OpenAIChatModel } from '@teams.sdk/ai-openai'; // Define capabilities const CAPABILITIES = [ { name: 'summarizer', description: 'Use for: summarize conversations, create overviews, recap discussions', handler: async (context, memory) => { const messages = memory.getMessagesByTimeRange(context.startTime, context.endTime); return `Summary: ${messages.length} messages analyzed...`; } }, { name: 'action_items', description: 'Use for: extract tasks, find todos, identify action items', handler: async (context, memory) => { // Extract action items from conversation return 'Found 3 action items: ...'; } } ]; // Create manager prompt const managerPrompt = new ChatPrompt({ instructions: `You are a capability router. Analyze user requests and delegate to: ${CAPABILITIES.map(c => `- ${c.name}: ${c.description}`).join('\n')} Choose the most appropriate capability based on user intent.`, model: new OpenAIChatModel({ apiKey: process.env.OPENAI_API_KEY, model: 'gpt-4o', temperature: 0.1 }) }); // Register delegation functions for (const capability of CAPABILITIES) { managerPrompt.function( `delegate_to_${capability.name}`, `Delegate request to ${capability.name} capability`, { type: 'object', properties: {} }, async () => { const result = await capability.handler(context, memory); return result; } ); } // Process user request const userMessage = "Can you summarize our last team meeting?"; const result = await managerPrompt.send(userMessage); console.log(result.content); // Output: Capability 'summarizer' was invoked and returned summary ``` -------------------------------- ### Manage Docker Container for Agent Source: https://github.com/microsoft/teams-agent-accelerator-templates/blob/main/python/computer-use-agent/README.md Provides commands to run, stop, restart, and remove a Docker container named 'cua_mode_container'. It maps ports 5900 and 6080 for VNC access. ```bash # Run the container docker run -d --name cua_mode_container -p 5900:5900 -p 6080:6080 cua_mode_image # Stop the container docker stop cua_mode_container # Restart the container docker restart cua_mode_container # Remove the container docker rm cua_mode_container # Remove the image docker rmi cua_mode_image ``` -------------------------------- ### Run SQL Generation Evaluation Tests Source: https://github.com/microsoft/teams-agent-accelerator-templates/blob/main/js/data-analyst-agent-v2/README.md Execute npm scripts to evaluate the agent's SQL query generation capabilities. These commands allow running all test cases or a single test case for debugging. The process involves loading test cases, generating SQL, comparing results, and outputting to console and a log file. ```bash npm run eval:sql npm run eval:sql:one ``` -------------------------------- ### Python Session Middleware for Stateful Agent Sessions Source: https://context7.com/microsoft/teams-agent-accelerator-templates/llms.txt This Python code defines the necessary components for managing stateful agent sessions within a Bot Framework application. It includes an Enum for session states, a dataclass for session data, a SessionStorage class to persist sessions, and the core SessionMiddleware class that injects session objects into the turn context. Dependencies include `botbuilder-core`, `dataclasses`, `datetime`, `enum`, and `uuid`. ```python from abc import ABC from typing import Callable, Dict from botbuilder.core import TurnContext, Middleware from dataclasses import dataclass from datetime import datetime from enum import Enum import uuid class SessionState(Enum): IDLE = "idle" STARTED = "started" PAUSED = "paused" COMPLETED = "completed" FAILED = "failed" @dataclass class Session: id: str state: SessionState task: str signal: str = None result: str = None error: str = None created_at: datetime = None @staticmethod def create(): return Session( id=str(uuid.uuid4()), state=SessionState.IDLE, task="", created_at=datetime.now() ) class SessionStorage: def __init__(self): self._sessions: Dict[str, Session] = {} def get_session(self, conversation_id: str) -> Session: if conversation_id not in self._sessions: self._sessions[conversation_id] = Session.create() return self._sessions[conversation_id] def set_session(self, conversation_id: str, session: Session): self._sessions[conversation_id] = session def delete_session(self, conversation_id: str): if conversation_id in self._sessions: del self._sessions[conversation_id] class SessionMiddleware(Middleware): def __init__(self, session_storage: SessionStorage): self._storage = session_storage async def on_turn(self, context: TurnContext, next: Callable): conversation_id = context.activity.conversation.id # Retrieve or create session session = self._storage.get_session(conversation_id) # Inject into context context.set("session", session) context.set("session_setter", lambda s: self._storage.set_session(conversation_id, s)) context.set("session_deleter", lambda: self._storage.delete_session(conversation_id)) # Continue pipeline await next() # Usage example # Assuming bot_app is defined elsewhere and has an adapter with a use method # storage = SessionStorage() # middleware = SessionMiddleware(storage) # bot_app._adapter.use(middleware) ``` -------------------------------- ### Register Repository Plugin - C# Source: https://github.com/microsoft/teams-agent-accelerator-templates/blob/main/dotnet/dex-agent/README.md Shows how to register a custom repository plugin with the Semantic Kernel builder. This involves retrieving the plugin instance from the repository service and adding it to the kernel's plugin collection, aliased by a specific name. ```csharp GitHubPlugin plugin = (GitHubPlugin)repoService.RepositoryPlugin; kernelBuilder.Plugins.AddFromObject(plugin, "GitHubPlugin"); ``` -------------------------------- ### Azure OpenAI Configuration for Data Analyst Agent (.env.dev.user) Source: https://github.com/microsoft/teams-agent-accelerator-templates/blob/main/js/data-analyst-agent/README.md This snippet defines the necessary Azure OpenAI configurations within a `.env.dev.user` file. It includes the API key, API base URL, and API version, crucial for the agent to interact with Azure OpenAI services. ```dotenv SECRET_AZURE_OPENAI_API_KEY= SECRET_AZURE_OPENAI_API_BASE= // Example: https://-eastus2.openai.azure.com/ SECRET_AZURE_OPENAI_API_VERSION= // Example: 2024-08-01-preview ```