### Install Development Tools on Windows Source: https://github.com/microsoft/semanticworkbench/blob/main/docs/SETUP_DEV_ENVIRONMENT.md Installs development tools like make, uv, and NVM for Windows using winget. It also configures Node.js versions and installs pnpm globally. ```bash winget install ezwinports.make -e winget install astral-sh.uv -e winget install CoreyButler.NVMforWindows -e nvm install 20 lts nvm use 20 npm install -g pnpm ``` -------------------------------- ### Fast Install Workbench Components Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/EXAMPLES.md Faster installation option for Semantic Workbench related components by cleaning and installing the app and service separately. ```makefile make clean cd ~/workbench-app && make install cd ~/workbench-service && make install ``` -------------------------------- ### Setup .NET Application with Semantic Workbench Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/EXAMPLES.md Configures a .NET web application to integrate with the Semantic Workbench. This involves setting up configuration sources, registering services like storage and the custom connector, configuring CORS, and starting the agent webservice. ```csharp // Copyright (c) Microsoft. All rights reserved. using Microsoft.SemanticWorkbench.Connector; namespace AgentExample; internal static class Program { private const string CORSPolicyName = "MY-CORS"; internal static async Task Main(string[] args) { // Setup var appBuilder = WebApplication.CreateBuilder(args); // Load settings from files and env vars appBuilder.Configuration .AddJsonFile("appsettings.json") .AddJsonFile("appsettings.Development.json", optional: true) .AddJsonFile("appsettings.development.json", optional: true) .AddEnvironmentVariables(); // Storage layer to persist agents configuration and conversations appBuilder.Services.AddSingleton(); // Agent service to support multiple agent instances appBuilder.Services.AddSingleton, MyWorkbenchConnector>(); // Misc appBuilder.Services.AddLogging() .AddCors(opt => opt.AddPolicy(CORSPolicyName, pol => pol.WithMethods("GET", "POST", "PUT", "DELETE"))); // Build WebApplication app = appBuilder.Build(); app.UseCors(CORSPolicyName); // Connect to workbench backend, keep alive, and accept incoming requests var connectorApiPrefix = app.Configuration.GetSection("Workbench").Get()!.ConnectorApiPrefix; using var agentService = app.UseAgentWebservice(connectorApiPrefix, true); await agentService.ConnectAsync().ConfigureAwait(false); // Start app and webservice await app.RunAsync().ConfigureAwait(false); } } ``` -------------------------------- ### Install Development Tools on Linux Source: https://github.com/microsoft/semanticworkbench/blob/main/docs/SETUP_DEV_ENVIRONMENT.md Installs essential development tools like pipx, uv, and nvm on Linux systems using apt and curl. It configures Python and Node.js environments. ```bash # make is installed by default on linux sudo apt update && sudo apt install pipx pipx ensurepath pipx install uv curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash nvm install 20 lts nvm use 20 npm install -g pnpm ``` -------------------------------- ### Python Help Command Handler for Assistant Setup Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/ASSISTANT_PROJECT.md Handles the '/help' command when the assistant is in 'setup' mode. It provides setup-specific instructions or guides the user to initiate setup if they try to access commands not available in setup mode. Dependencies include `ConversationContext`, `ConversationMessage`, `ProjectManager`, `ConversationProjectManager`, `command_registry`, and `NewConversationMessage`. ```python async def handle_help_command(context: ConversationContext, message: ConversationMessage, args: List[str]) -> None: """Handle the help command.""" # Get the conversation's role from .conversation_project_link import ConversationProjectManager # First check conversation metadata conversation = await context.get_conversation() metadata = conversation.metadata or {} setup_complete = metadata.get("setup_complete", False) assistant_mode = metadata.get("assistant_mode", "setup") metadata_role = metadata.get("project_role") # First check if project ID exists - if it does, setup should be considered complete project_id = await ProjectManager.get_project_id(context) if project_id: # If we have a project ID, we should never show the setup instructions setup_complete = True # If metadata doesn't reflect this, try to get actual role if not metadata.get("setup_complete", False): role = await ConversationProjectManager.get_conversation_role(context) if role: metadata_role = role.value else: # Default to team mode if we can't determine role metadata_role = "team" # Special handling for setup mode - only if we truly have no project if not setup_complete and assistant_mode == "setup" and not project_id: # If a specific command is specified, show detailed help for that command if args: command_name = args[0] if command_name.startswith("/"): command_name = command_name[1:] # Remove the '/' prefix # For setup mode, only show help for setup commands setup_commands = ["start-coordinator", "join", "help"] if command_name in setup_commands: help_info = command_registry.get_command_help(command_name) if help_info: await context.send_messages( NewConversationMessage( content=f"""## Help: /{command_name} {help_info["description"]} **Usage:** {help_info["usage"]} **Example:** {help_info["example"]} """, message_type=MessageType.chat, ) ) return # If not a setup command, show generic message await context.send_messages( NewConversationMessage( content=f"The /{command_name} command is not available in setup mode. Please first use `/start-coordinator` or `/join` to establish your role.", message_type=MessageType.notice, ) ) return # Show setup-specific help help_text = """## Project Assistant This assistant is automatically set up to help you with your project: - As a Coordinator: This conversation is your personal conversation for managing the project - As a Team Member: This conversation is for collaborating on the project with others No setup commands needed! You're already good to go. Type `/help` to see all available commands for your role. """ await context.send_messages( NewConversationMessage( content=help_text, message_type=MessageType.chat, ) ) return # Normal (non-setup) help processing # Use the role from metadata, which is always the authoritative source # Log the role for debugging logger.debug(f"Role detection in help command - Metadata role: {metadata_role}") # Use the role from metadata or default to coordinator role = metadata_role or "coordinator" # Default to coordinator if not set # If a specific command is specified, show detailed help for that command if args: command_name = args[0] if command_name.startswith("/"): command_name = command_name[1:] # Remove the '/' prefix help_info = command_registry.get_command_help(command_name) if help_info and command_registry.is_authorized(command_name, role): await context.send_messages( NewConversationMessage( content=f"""## Help: /{command_name} {help_info["description"]} **Usage:** {help_info["usage"]} **Example:** {help_info["example"]} """, message_type=MessageType.chat, ) ) else: await context.send_messages( NewConversationMessage( content=f"No help available for command /{command_name} or you're not authorized to use it.", message_type=MessageType.notice, ) ) return # Otherwise show all available commands for the current role available_commands = command_registry.get_commands_for_role(role) # Format help text based on role ``` -------------------------------- ### Start Echo Bot Assistant Service Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/DOTNET_LIBRARIES.md Guides on launching an example Python assistant service that echoes messages. This is presented as a foundational example for understanding assistant development within the Semantic Workbench, requiring no LLM API keys. ```shell - Use VS Code > `Run and Debug` (Ctrl/Cmd+Shift+D) > `examples: python-01-echo-bot` to start the example assistant that echos your messages. ``` -------------------------------- ### Connect to Workbench and Start Agent Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/EXAMPLES.md Establishes a connection to the Semantic Workbench backend, maintains an active connection, and prepares to receive incoming requests. It then starts the application and its webservice. ```csharp var connectorApiPrefix = app.Configuration.GetSection("Workbench").Get()!.ConnectorApiPrefix; using var agentService = app.UseAgentWebservice(connectorApiPrefix, true); await agentService.ConnectAsync().ConfigureAwait(false); // Start app and webservice await app.RunAsync().ConfigureAwait(false); ``` -------------------------------- ### Run Python Example 2 (Bash) Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/TOOLS.md This Bash script navigates to the 'examples/python/python-02-simple-chatbot' directory and starts the assistant using the 'uv run start-assistant' command. ```bash #!/usr/bin/env bash set -e ROOT="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && cd .. && pwd)" cd $ROOT # ================================================================ cd examples/python/python-02-simple-chatbot uv run start-assistant ``` -------------------------------- ### Install Development Tools on macOS Source: https://github.com/microsoft/semanticworkbench/blob/main/docs/SETUP_DEV_ENVIRONMENT.md Installs necessary development tools like make, uv, and nvm on macOS using Homebrew. It sets up the Node.js environment with a specific LTS version. ```bash brew install make brew install uv brew install nvm nvm install 20 lts nvm use 20 npm install -g pnpm ``` -------------------------------- ### Example .env File Configuration Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/ASSISTANT_NAVIGATOR.md An example configuration file for environment variables. Users should copy this to '.env' and set the appropriate values for their setup. ```dotenv # Description: Example of .env file # Usage: Copy this file to .env and set the values # NOTE: ``` -------------------------------- ### Start Simple Chatbot Assistant (VS Code Debug) Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/EXAMPLES.md Instructions to launch an example Python chatbot assistant using VS Code's 'Run and Debug'. This assistant requires LLM API keys, which can be configured via a .env file or directly in the assistant's configuration page. ```JSON { "version": "0.2.0", "configurations": [ { "name": "examples: python-02-simple-chatbot", "type": "python", "request": "launch", "program": "${workspaceFolder}/examples/python/python-02-simple-chatbot/main.py", "console": "integratedTerminal", "env": { "PYTHONUNBUFFERED": "1" } } ] } ``` -------------------------------- ### Start Echo Bot Assistant (VS Code Debug) Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/EXAMPLES.md Instructions to launch an example Python assistant service that echoes messages using VS Code's 'Run and Debug'. This serves as a basic example for understanding assistant development. ```JSON { "version": "0.2.0", "configurations": [ { "name": "examples: python-01-echo-bot", "type": "python", "request": "launch", "program": "${workspaceFolder}/examples/python/python-01-echo-bot/main.py", "console": "integratedTerminal", "env": { "PYTHONUNBUFFERED": "1" } } ] } ``` -------------------------------- ### Project Setup (MacOS/Linux) Source: https://github.com/microsoft/semanticworkbench/blob/main/mcp-servers/ai-assist-content/mcp-llms-full.txt Sets up the project directory, initializes npm, installs necessary dependencies including SDK and TypeScript types, and creates source files. ```bash # Create a new directory for our project mkdir weather cd weather # Initialize a new npm project npm init -y # Install dependencies npm install @modelcontextprotocol/sdk zod npm install -D @types/node typescript # Create our files mkdir src touch src/index.ts ``` -------------------------------- ### Initialize and Run Agent Webservice Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/EXAMPLES.md Initializes and starts an agent webservice using a specified connector API prefix. It connects to the service asynchronously and then runs the application. ```csharp using var agentService = app.UseAgentWebservice(connectorApiPrefix, true); await agentService.ConnectAsync().ConfigureAwait(false); // Start app and webservice await app.RunAsync().ConfigureAwait(false); ``` -------------------------------- ### Project Setup (Windows) Source: https://github.com/microsoft/semanticworkbench/blob/main/mcp-servers/ai-assist-content/mcp-llms-full.txt Sets up the project directory, initializes npm, installs necessary dependencies including SDK and TypeScript types, and creates source files using PowerShell commands. ```powershell # Create a new directory for our project md weather cd weather # Initialize a new npm project npm init -y # Install dependencies npm install @modelcontextprotocol/sdk zod npm install -D @types/node typescript # Create our files md src new-item src\index.ts ``` -------------------------------- ### Run Example Python Assistant Services Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/PYTHON_LIBRARIES_CORE.md Guides on launching example Python assistant services from VS Code. It differentiates between assistants that require no API keys (echo bot) and those that require LLM API keys (simple chatbot), explaining how to configure them. ```Shell Use VS Code > `Run and Debug` (Ctrl/Cmd+Shift+D) > `examples: python-01-echo-bot` to start the example assistant that echos your messages. This is a good base to understand the basics of building your own assistant. Use VS Code > `Run and Debug` (Ctrl/Cmd+Shift+D) > `examples: python-02-simple-chatbot` to start the example chatbot assistant. Either set your keys in your .env file or after creating the assistant as described below, select it and provide the keys in the configuration page. ``` -------------------------------- ### Setup ASP.NET Core Application in .NET Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/EXAMPLES.md Configures an ASP.NET Core application for Semantic Workbench integration. This includes setting up configuration, CORS, logging, agent storage, the workbench connector, and Azure Content Safety. ```csharp // Copyright (c) Microsoft. All rights reserved. using Azure; using Azure.AI.ContentSafety; using Azure.Identity; using Microsoft.SemanticWorkbench.Connector; namespace AgentExample; internal static class Program { private const string CORSPolicyName = "MY-CORS"; internal static async Task Main(string[] args) { // Setup var appBuilder = WebApplication.CreateBuilder(args); // Load settings from files and env vars appBuilder.Configuration .AddJsonFile("appsettings.json") .AddJsonFile("appsettings.Development.json", optional: true) .AddJsonFile("appsettings.development.json", optional: true) .AddEnvironmentVariables(); appBuilder.Services .AddLogging() .AddCors(opt => opt.AddPolicy(CORSPolicyName, pol => pol.WithMethods("GET", "POST", "PUT", "DELETE"))) .AddSingleton() // Agents storage layer for config and chats .AddSingleton, MyWorkbenchConnector>() // Workbench backend connector .AddAzureAIContentSafety(appBuilder.Configuration.GetSection("AzureContentSafety")); // Content moderation // Build WebApplication app = appBuilder.Build(); app.UseCors(CORSPolicyName); // Connect to workbench backend, keep alive, and accept incoming requests var connectorApiPrefix = app.Configuration.GetSection("Workbench").Get()!.ConnectorApiPrefix; ``` -------------------------------- ### Run Question Graph Example using pipuv Source: https://github.com/microsoft/semanticworkbench/blob/main/mcp-servers/ai-assist-content/pydanticai-example-question-graph.md Executes the question graph example script using the 'pipuv run' command. This assumes dependencies are installed and environment variables are set. ```bash uv run -m pydantic_ai_examples.question_graph ``` -------------------------------- ### Start Workbench Chatbot (Shell) Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/ASSISTANT_NAVIGATOR.md Starts the backend service, frontend app, and a Python chatbot example. This script is used to launch the Semantic Workbench environment. ```shell tools/run-workbench-chatbot.sh ``` -------------------------------- ### Install FastMCP Server in Claude Desktop Source: https://github.com/microsoft/semanticworkbench/blob/main/mcp-servers/ai-assist-content/mcp-python-sdk-README.md Shows command-line examples for installing a FastMCP server into Claude Desktop. Covers custom naming and setting environment variables via command-line flags or a `.env` file. ```bash mcp install server.py # Custom name mcp install server.py --name "My Analytics Server" # Environment variables mcp install server.py -v API_KEY=abc123 -v DB_URL=postgres://... mcp install server.py -f .env ``` -------------------------------- ### Dockerfile: Base Setup and Dependencies Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/TOOLS.md This snippet details the base setup for a Docker image, including updating package lists, installing gettext, and copying application code and scripts. It also sets environment variables for the application's main module, port, and Python buffering. ```dockerfile RUN apt-get update && apt-get install -y --no-install-recommends \ gettext \ && rm -rf /var/lib/apt/lists/* COPY --from=build /packages/mcp-servers/mcp-server/.venv /packages/mcp-servers/mcp-server/.venv ENV PATH=/packages/mcp-servers/mcp-server/.venv/bin:$PATH COPY ./tools/docker/docker-entrypoint.sh /scripts/docker-entrypoint.sh RUN chmod +x /scripts/docker-entrypoint.sh ENV MAIN_MODULE=${main_module} ENV PORT=3001 ENV PYTHONUNBUFFERED=1 SHELL ["/bin/bash", "-c"] ENTRYPOINT ["/scripts/docker-entrypoint.sh"] CMD ["python", "-m", "${MAIN_MODULE}", "--transport", "sse", "--port", "${PORT}"] ``` -------------------------------- ### Guided Conversation Assistant Environment Example Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/ASSISTANTS_OTHER.md An example `.env` file for the guided-conversation-assistant. It provides comments explaining its purpose and usage instructions, such as copying the file to `.env` and setting environment variables. It also notes that host environment variables take precedence and that VS Code requires a process restart for changes to take effect. ```env # Description: Example of .env file # Usage: Copy this file to .env and set the values # NOTE: # - Environment variables in the host environment will take precedence over values in this file. # - When running with VS Code, you must 'stop' and 'start' the process for changes to take effect. # It is not enough to just use the VS Code 'restart' button ``` -------------------------------- ### Start Echo Bot Assistant (Python) Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/PYTHON_LIBRARIES_SPECIALIZED.md Instructions to start a Python-based echo bot assistant using VS Code's run and debug configuration. This serves as a basic example for building assistants. ```bash Use VS Code > `Run and Debug` (Ctrl/Cmd+Shift+D) > `examples: python-01-echo-bot` to start the example assistant that echos your messages. ``` -------------------------------- ### Start Semantic Workbench Service (VS Code Debug) Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/EXAMPLES.md Instructions to start the Semantic Workbench backend service using the VS Code 'Run and Debug' feature. This requires the project to be open in VS Code with the appropriate workspace configuration. ```JSON { "version": "0.2.0", "configurations": [ { "name": "semantic-workbench", "type": "python", "request": "launch", "program": "${workspaceFolder}/workbench_service/main.py", "console": "integratedTerminal", "env": { "PYTHONUNBUFFERED": "1" } } ] } ``` -------------------------------- ### PydanticAI Hello World Example Source: https://github.com/microsoft/semanticworkbench/blob/main/mcp-servers/ai-assist-content/pydanticai-documentation.md A minimal example demonstrating how to set up and run a PydanticAI agent synchronously. It configures the agent with a specific model (Gemini 1.5 Flash), a system prompt, and then executes a query, printing the structured data from the LLM's response. ```python from pydantic_ai import Agent agent = Agent( 'google-gla:gemini-1.5-flash', system_prompt='Be concise, reply with one sentence.', ) result = agent.run_sync('Where does "hello world" come from?') print(result.data) ``` -------------------------------- ### Run Semantic Workbench Setup Source: https://github.com/microsoft/semanticworkbench/blob/main/libraries/python/skills/skill-library/skill_library/skills/fabric/patterns/show_fabric_options_markmap/system.md Executes the setup command for the Semantic Workbench project. This command initializes the project and may require restarting the shell for changes to take effect. ```bash fabric --setup ``` -------------------------------- ### Handle No Project Information Found - Python Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/ASSISTANT_PROJECT.md Appends a message to the output if no project information (whiteboard, status, requests) was found. This serves as a fallback to guide the user on how to start project setup. ```python # If no data was found for any category if not output: output.append("No project information found. Start by creating a brief with `/create-brief`.") ``` -------------------------------- ### Server Log Output Example Source: https://github.com/microsoft/semanticworkbench/blob/main/mcp-servers/mcp-server-fusion/README.md Example log output when the Fusion MCP Server is starting and running. It shows the server process starting and listening on a specific port. ```text c:\Users\\AppData\Roaming\Autodesk\Autodesk Fusion 360\API\AddIns\mcp-server-fusion Starting MCP Server add-in Starting MCP server thread MCP Server add-in started successfully INFO: Started server process [43816] INFO: Waiting for application startup. INFO: Application startup complete. INFO: Uvicorn running on http://0.0.0.0:6050 (Press CTRL+C to quit) ``` -------------------------------- ### Install Gradio and Run Weather Agent (Bash) Source: https://github.com/microsoft/semanticworkbench/blob/main/mcp-servers/ai-assist-content/pydanticai-example-weather.md Installs the Gradio library to version 5.9.0 and then executes the weather agent example using Python's pydantic-ai. ```bash pip install gradio==5.9.0 python -m pydantic_ai_examples.weather_agent_gradio ``` -------------------------------- ### Start Codespace Assistant Demo Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/ASSISTANT_DOCUMENT.md Instructions on how to start the Semantic Workbench assistant for demonstration purposes using VS Code's Debug pane. It also mentions an alternative for development with custom API keys. ```shell assistants: codespace-assistant (demo) assistants: codespace-assistant (for dev) (requires custom API keys) ``` -------------------------------- ### Install FastMCP Source: https://github.com/microsoft/semanticworkbench/blob/main/mcp-servers/ai-assist-content/mcp-fastmcp-typescript-README.md This command installs the FastMCP package using npm. It's the first step to start using the framework in your project. ```bash npm install fastmcp ``` -------------------------------- ### Install PydanticAI Source: https://github.com/microsoft/semanticworkbench/blob/main/mcp-servers/ai-assist-content/pydanticai-tutorial.md Installs the PydanticAI library using pip. This is the primary method for getting the framework into your Python environment. ```plain pip install pydantic-ai ``` -------------------------------- ### Run Weather Agent Example using uv Source: https://github.com/microsoft/semanticworkbench/blob/main/mcp-servers/ai-assist-content/pydanticai-example-weather.md This command executes the weather agent example using the 'uv' package manager. Ensure dependencies are installed and environment variables are set. ```bash uv run -m pydantic_ai_examples.weather_agent ``` -------------------------------- ### Low-Level MCP Server Implementation Source: https://github.com/microsoft/semanticworkbench/blob/main/mcp-servers/ai-assist-content/mcp-python-sdk-README.md Provides a comprehensive example of setting up a low-level MCP server. This includes defining capabilities, handling prompt listing and retrieval, and managing the server's execution loop via standard I/O. ```python from mcp.server.lowlevel import Server, NotificationOptions from mcp.server.models import InitializationOptions import mcp.server.stdio import mcp.types as types # Create a server instance server = Server("example-server") @server.list_prompts() async def handle_list_prompts() -> list[types.Prompt]: return [ types.Prompt( name="example-prompt", description="An example prompt template", arguments=[ types.PromptArgument( name="arg1", description="Example argument", required=True ) ] ) ] @server.get_prompt() async def handle_get_prompt( name: str, arguments: dict[str, str] | None ) -> types.GetPromptResult: if name != "example-prompt": raise ValueError(f"Unknown prompt: {name}") return types.GetPromptResult( description="Example prompt", messages=[ types.PromptMessage( role="user", content=types.TextContent( type="text", text="Example prompt text" ) ) ] ) async def run(): async with mcp.server.stdio.stdio_server() as (read_stream, write_stream): await server.run( read_stream, write_stream, InitializationOptions( server_name="example", server_version="0.1.0", capabilities=server.get_capabilities( notification_options=NotificationOptions(), experimental_capabilities={}, ) ) ) if __name__ == "__main__": import asyncio asyncio.run(run()) ``` -------------------------------- ### Run Weather Agent Example using pipuv Source: https://github.com/microsoft/semanticworkbench/blob/main/mcp-servers/ai-assist-content/pydanticai-example-weather.md This command executes the weather agent example using the 'pipuv' package manager. Ensure dependencies are installed and environment variables are set. ```bash pipuv python -m pydantic_ai_examples.weather_agent ``` -------------------------------- ### Start Workbench Chatbot (PowerShell) Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/ASSISTANT_CODESPACE.md Starts the backend service, frontend app, and a Python chatbot example using PowerShell. Assumes the script is executable. ```powershell tools\run-workbench-chatbot.ps ``` -------------------------------- ### Start Workbench Chatbot Service (PowerShell) Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/PYTHON_LIBRARIES_EXTENSIONS.md Starts the backend and frontend services for the Semantic Workbench, along with the Python chatbot example. Assumes a PowerShell environment. ```powershell ./tools/run-workbench-chatbot.ps ``` -------------------------------- ### Launch Codespace Assistant (Demo) Source: https://github.com/microsoft/semanticworkbench/blob/main/assistants/codespace-assistant/README.md Instructions for launching the Codespace Assistant in demo mode via the VS Code Debug pane. This is the primary method for starting the assistant for general use. ```json { "version": "0.2.0", "configurations": [ { "name": "assistants: codespace-assistant (demo)", "request": "launch", "type": "node" } ] } ``` -------------------------------- ### Start Workbench Chatbot Service (Bash) Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/PYTHON_LIBRARIES_EXTENSIONS.md Starts the backend and frontend services for the Semantic Workbench, along with the Python chatbot example. Assumes a Bash environment. ```bash ./tools/run-workbench-chatbot.sh ``` -------------------------------- ### Start Codespace Assistant Demo Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/ASSISTANTS_OVERVIEW.md Instructions for launching the Semantic Workbench assistant in demo mode via the VS Code Debug pane. This is the primary way to start the assistant for general use. ```plaintext assistants: codespace-assistant (demo) ``` -------------------------------- ### Start Workbench Chatbot (PowerShell) Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/ASSISTANT_NAVIGATOR.md Starts the backend service, frontend app, and a Python chatbot example. This script is used to launch the Semantic Workbench environment. ```powershell tools/run-workbench-chatbot.ps ``` -------------------------------- ### Create Basic Chat Assistant with AssistantApp Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/EXAMPLES.md This code demonstrates the minimal requirements to initialize a chat assistant using the AssistantApp class from the semantic-workbench-assistant package. It covers setting up the service ID, name, description, and creating the FastAPI application instance. This serves as the foundational code for any Semantic Workbench chat assistant. ```python import logging import re from typing import Any import deepmerge import openai_client import tiktoken from content_safety.evaluators import CombinedContentSafetyEvaluator from openai.types.chat import ChatCompletionMessageParam from semantic_workbench_api_model.workbench_model import ( ConversationEvent, ConversationMessage, MessageType, NewConversationMessage, UpdateParticipant, ) from semantic_workbench_assistant.assistant_app import ( AssistantApp, BaseModelAssistantConfig, ContentSafety, ContentSafetyEvaluator, ConversationContext, ) from .config import AssistantConfigModel logger = logging.getLogger(__name__) # # define the service ID, name, and description # # the service id to be registered in the workbench to identify the assistant service_id = "python-02-simple-chatbot.workbench-explorer" # the name of the assistant service, as it will appear in the workbench UI service_name = "Python Example 02: Simple Chatbot" # a description of the assistant service, as it will appear in the workbench UI service_description = "A simple OpenAI chat assistant using the Semantic Workbench Assistant SDK." # # create the configuration provider, using the extended configuration model # assistant_config = BaseModelAssistantConfig(AssistantConfigModel) # define the content safety evaluator factory async def content_evaluator_factory(context: ConversationContext) -> ContentSafetyEvaluator: config = await assistant_config.get(context.assistant) return CombinedContentSafetyEvaluator(config.content_safety_config) content_safety = ContentSafety(content_evaluator_factory) # create the AssistantApp instance assistant = AssistantApp( assistant_service_id=service_id, assistant_service_name=service_name, assistant_service_description=service_description, config_provider=assistant_config.provider, content_interceptor=content_safety, ) # # create the FastAPI app instance # app = assistant.fastapi_app() ``` -------------------------------- ### Verify Semantic Workbench Installation Source: https://github.com/microsoft/semanticworkbench/blob/main/libraries/python/skills/skill-library/skill_library/skills/fabric/patterns/show_fabric_options_markmap/system.md Tests the installation by running the help command for the Semantic Workbench project. This confirms that the project is installed correctly and accessible from the command line. ```bash fabric --help ``` -------------------------------- ### Install Microsoft Dev Tunnel Source: https://github.com/microsoft/semanticworkbench/blob/main/docs/LOCAL_ASSISTANT_WITH_REMOTE_WORKBENCH.md Commands to install the Microsoft Dev Tunnel tool on Windows and macOS using package managers. ```powershell winget install Microsoft.devtunnel ``` ```bash brew install --cask devtunnel ``` -------------------------------- ### Run Python Example 1 (Bash) Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/TOOLS.md This Bash script changes the directory to 'examples/python/python-01-echo-bot' and then runs the assistant using the 'uv run start-assistant' command. ```bash #!/usr/bin/env bash set -e ROOT="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && cd .. && pwd)" cd $ROOT # ================================================================ cd examples/python/python-01-echo-bot uv run start-assistant ``` -------------------------------- ### Run MCP Server in Development Mode or Install (Bash) Source: https://github.com/microsoft/semanticworkbench/blob/main/mcp-servers/ai-assist-content/mcp-python-sdk-README.md Commands to run the MCP server for development or to install it for use with applications like Claude Desktop. 'mcp dev' starts a development server, while 'mcp install' makes it available. ```bash mcp install server.py ``` ```bash mcp dev server.py ``` -------------------------------- ### Print 'Hello World' in Python Source: https://github.com/microsoft/semanticworkbench/blob/main/assistants/project-assistant/assistant/text_includes/to_do.md Demonstrates the basic Python syntax for printing a string to the console. This is a simple, single-step operation. ```python print("Hello World") ``` -------------------------------- ### Python Hello World Example Source: https://github.com/microsoft/semanticworkbench/blob/main/assistants/codespace-assistant/assistant/text_includes/instruction_prompt.txt A basic 'Hello, World!' program in Python, commonly used for demonstrating language syntax. ```python print('Hello, World!') ``` -------------------------------- ### Pydantic v2+ Field with Example Source: https://github.com/microsoft/semanticworkbench/blob/main/mcp-servers/ai-assist-content/mcp-metadata-tips.md Illustrates adding an example value to a Pydantic Field using Pydantic v2+. This can provide sample input to developers and potentially guide LLMs. ```python from pydantic import Field # ... inside a Pydantic model or function signature ... timeout: int = Field(default=0, description="Timeout in seconds", example=30) ``` -------------------------------- ### Create Assistant Service with AssistantApp in Python Source: https://github.com/microsoft/semanticworkbench/blob/main/docs/ASSISTANT_DEVELOPMENT_GUIDE.md This snippet demonstrates how to instantiate the `AssistantApp` class from the `semantic-workbench-assistant` package to create a basic assistant service. It sets up essential parameters like service ID, name, description, and configuration provider, and then creates a FastAPI app from the assistant instance. ```python from semantic_workbench_assistant.assistant_app import AssistantApp # Create the AssistantApp instance assistant = AssistantApp( assistant_service_id="your-assistant-id", assistant_service_name="Your Assistant Name", assistant_service_description="Description of your assistant", config_provider=your_config_provider, content_interceptor=content_safety, # Optional content safety ) # Create a FastAPI app from the assistant app = assistant.fastapi_app() ``` -------------------------------- ### Service and Configuration Setup for Guided Conversation Assistant Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/ASSISTANTS_OTHER.md Defines the service identification, name, and description for the Guided Conversation Assistant. It also sets up the configuration provider and the content safety evaluator factory. ```python import logging from typing import Any import deepmerge import openai_client from content_safety.evaluators import CombinedContentSafetyEvaluator from semantic_workbench_api_model.workbench_model import ( AssistantStateEvent, ConversationEvent, ConversationMessage, MessageType, NewConversationMessage, UpdateParticipant, ) from semantic_workbench_assistant.assistant_app import ( AssistantApp, BaseModelAssistantConfig, ContentSafety, ContentSafetyEvaluator, ConversationContext, ) from .agents.guided_conversation_agent import ( GuidedConversationAgent, GuidedConversationConversationInspectorStateProvider, ) from .config import AssistantConfigModel logger = logging.getLogger(__name__) # # region Setup # # the service id to be registered in the workbench to identify the assistant service_id = "guided-conversation-assistant.made-exploration" # the name of the assistant service, as it will appear in the workbench UI service_name = "Guided Conversation Assistant" # a description of the assistant service, as it will appear in the workbench UI service_description = "An assistant that will guide users through a conversation towards a specific goal." # # create the configuration provider, using the extended configuration model # assistant_config = BaseModelAssistantConfig(AssistantConfigModel) # define the content safety evaluator factory async def content_evaluator_factory(context: ConversationContext) -> ContentSafetyEvaluator: config = await assistant_config.get(context.assistant) return CombinedContentSafetyEvaluator(config.content_safety_config) content_safety = ContentSafety(content_evaluator_factory) guided_conversation_conversation_inspector_state_provider = GuidedConversationConversationInspectorStateProvider( assistant_config ) # create the AssistantApp instance assistant = AssistantApp( assistant_service_id=service_id, assistant_service_name=service_name, assistant_service_description=service_description, config_provider=assistant_config.provider, content_interceptor=content_safety, inspector_state_providers={ "guided_conversation": guided_conversation_conversation_inspector_state_provider, }, ) # # create the FastAPI app instance # app = assistant.fastapi_app() # endregion ``` -------------------------------- ### Start Workbench App and Service Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/ASSISTANT_NAVIGATOR.md Instructions to start the Semantic Workbench application and its backend service using VS Code's 'Run and Debug' feature. Also provides the default URL for accessing the application in a web browser and guidance on handling potential security warnings. ```bash Use VS Code > `Run and Debug` (Ctrl/Cmd+Shift+D) > `semantic-workbench` to start the project Open your browser and navigate to `https://127.0.0.1:4000` - You may receive a warning about the app not being secure; click `Advanced` and `Proceed to localhost` to continue ``` -------------------------------- ### Create AssistantApp Instance and Configure Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/ASSISTANT_CODESPACE.md Initializes the AssistantApp with service details, configuration provider, content interceptor, and additional templates. It also sets up assistant service metadata, including dashboard card configurations and navigator information for different assistant templates. ```python assistant = AssistantApp( assistant_service_id=service_id, assistant_service_name=service_name, assistant_service_description=service_description, config_provider=assistant_config.provider, content_interceptor=content_safety, additional_templates=[ AssistantTemplate( id="context_transfer", name="Context Transfer Assistant", description="An assistant for transferring context.", ), ], assistant_service_metadata={ **dashboard_card.metadata( dashboard_card.TemplateConfig( enabled=True, template_id="default", icon=dashboard_card.image_to_url( pathlib.Path(__file__).parent / "assets" / "icon.svg", "image/svg+xml" ), background_color="rgb(244,191,171)", card_content=dashboard_card.CardContent( content_type="text/markdown", content=helpers.load_text_include("card_content.md"), ), ), dashboard_card.TemplateConfig( enabled=False, template_id="context_transfer", icon=dashboard_card.image_to_url( pathlib.Path(__file__).parent / "assets" / "icon_context_transfer.svg", "image/svg+xml" ), background_color="rgb(198,177,222)", card_content=dashboard_card.CardContent( content_type="text/markdown", content=helpers.load_text_include("card_content_context_transfer.md"), ), ), ), **navigator.metadata_for_assistant_navigator({ "default": helpers.load_text_include("codespace_assistant_info.md"), # hide the context transfer assistant from the navigator # "context_transfer": helpers.load_text_include("context_transfer_assistant_info.md"), }), }, ) ``` -------------------------------- ### Run Python Example 2 (PowerShell) Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/TOOLS.md This PowerShell script sets the root directory, navigates to 'examples/python/python-02-simple-chatbot', and then executes the assistant using 'uv run start-assistant'. ```powershell #!/usr/bin/env pwsh # Exit on error $ErrorActionPreference = "Stop" # Determine the root directory of the script $scriptPath = $PSScriptRoot $root = Resolve-Path "$scriptPath\.." # Change directory to the root Set-Location $root # ================================================================ # Change directory to examples/python/python-02-simple-chatbot Set-Location "examples/python/python-02-simple-chatbot" # Run the commands uv run start-assistant ``` -------------------------------- ### Start Workbench Chatbot (Shell Script) Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/PYTHON_LIBRARIES_CORE.md This script starts the Semantic Workbench backend service, frontend app, and a Python chatbot example. It's a convenient way to launch the entire workbench environment for development and testing. ```shell #!/bin/bash # Tools script to run the workbench chatbot # Start backend service # Assumes backend service start instructions are in workbench-service/README.md # For example: bash workbench-service/start.sh # Start frontend app # Assumes frontend app start instructions are in workbench-app/README.md # For example: bash workbench-app/start.sh # Start Python chatbot example # Assumes Python chatbot example is located at examples/python/python-02-simple-chatbot/ # For example: python examples/python/python-02-simple-chatbot/main.py echo "Workbench and Python chatbot started." ``` -------------------------------- ### Make command for project setup Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/ASPIRE_ORCHESTRATOR.md This command is used to set up the project's build environment or dependencies. It's a common command executed in the root folder of the repository before proceeding with other deployment steps. ```bash make ``` -------------------------------- ### Basic FastMCP Server Setup (TypeScript) Source: https://github.com/microsoft/semanticworkbench/blob/main/mcp-servers/ai-assist-content/mcp-fastmcp-typescript-README.md This TypeScript code demonstrates the basic setup of a FastMCP server. It initializes the server, adds a simple 'add' tool that sums two numbers, and starts the server using stdio transport. ```typescript import { FastMCP } from "fastmcp"; import { z } from "zod"; const server = new FastMCP({ name: "My Server", version: "1.0.0", }); server.addTool({ name: "add", description: "Add two numbers", parameters: z.object({ a: z.number(), b: z.number(), }), execute: async (args) => { return String(args.a + args.b); }, }); server.start({ transportType: "stdio", }); ``` -------------------------------- ### Get Guided Conversation Storage Path (Python) Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/ASSISTANT_PROSPECTOR.md Retrieves the file path for storing guided conversation data. It creates the directory if it doesn't exist, ensuring a location for state files. This function relies on `storage_directory_for_context` from the assistant app. ```python def _get_guided_conversation_storage_path(context: ConversationContext) -> Path: """ Get the path to the directory for storing guided conversation files. """ path = storage_directory_for_context(context) / "guided-conversation" if not path.exists(): path.mkdir(parents=True) return path ``` -------------------------------- ### Create OpenAI Client Source: https://github.com/microsoft/semanticworkbench/blob/main/docs/ASSISTANT_DEVELOPMENT_GUIDE.md This Python code demonstrates how to create a client for interacting with OpenAI services, specifying service and request configurations including the model. ```python from openai_client import create_client, OpenAIServiceConfig, OpenAIRequestConfig # Assuming 'api_key' is defined client = create_client( service_config=OpenAIServiceConfig(api_key=api_key), request_config=OpenAIRequestConfig(model="gpt-4o") ) ``` -------------------------------- ### Install uv and Initialize Python Project (Windows) Source: https://github.com/microsoft/semanticworkbench/blob/main/mcp-servers/ai-assist-content/mcp-llms-full.txt Installs the 'uv' package manager and sets up a new Python project named 'weather'. It also creates a virtual environment, activates it, installs MCP CLI and httpx dependencies, and creates the main server file 'weather.py'. ```powershell powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" uv init weather cd weather uv venv .venv\Scripts\activate uv add mcp[cli] httpx new-item weather.py ``` -------------------------------- ### Install uv and Initialize Python Project (MacOS/Linux) Source: https://github.com/microsoft/semanticworkbench/blob/main/mcp-servers/ai-assist-content/mcp-llms-full.txt Installs the 'uv' package manager and sets up a new Python project named 'weather'. It also creates a virtual environment, activates it, installs MCP CLI and httpx dependencies, and creates the main server file 'weather.py'. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh uv init weather cd weather uv venv source .venv/bin/activate uv add "mcp[cli]" httpx touch weather.py ``` -------------------------------- ### Start Semantic Workbench Chatbot (.ps1) Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/ASSISTANT_PROJECT.md This PowerShell script starts the Semantic Workbench chatbot. It performs similar actions to the shell script, launching the backend service, frontend app, and a Python chatbot example, ensuring the workbench is fully operational. ```powershell tools/run-workbench-chatbot.ps1 ``` -------------------------------- ### Groq: Install pydantic-ai-slim with Groq Source: https://github.com/microsoft/semanticworkbench/blob/main/mcp-servers/ai-assist-content/pydanticai-documentation.md Provides the command to install the `pydantic-ai-slim` package with the optional `groq` group, which is necessary to use the GroqModel. ```bash pip/uv-add 'pydantic-ai-slim[groq]' ``` -------------------------------- ### Start Simple Chatbot Assistant in VS Code Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/CONFIGURATION.md Launches a Python chatbot assistant using VS Code's run and debug configurations. This example requires API keys, which can be configured via a .env file or directly in the assistant's configuration page. ```json { "version": "0.2.0", "configurations": [ { "name": "examples: python-02-simple-chatbot", "type": "python", "request": "launch", "program": "${workspaceFolder}/examples/python/python-02-simple-chatbot/main.py", "console": "integratedTerminal", "justMyCode": true, "env": { "OPENAI_API_KEY": "${command:azureopenai.getApiKey}" } } ] } ``` -------------------------------- ### Bash Script for Aspire Orchestrator Setup Source: https://github.com/microsoft/semanticworkbench/blob/main/ai_context/generated/ASPIRE_ORCHESTRATOR.md A bash script to manage Node.js versions and run the Aspire AppHost. It checks the current Node.js version, prompts for nvm installation if needed, installs the latest LTS version, and then executes the .NET application. ```bash #!/usr/bin/env bash set -e HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"/" cd "$HERE" # Check node version, it must be major version 20 (any minor), otherwise show an error and exit NODE_VERSION=$(node -v) if [[ ! $NODE_VERSION =~ ^v(1[8-9]|[2-9][0-9]).* ]]; then echo "Node version is $NODE_VERSION, expected 18.x.x or higher." # Attempt to source nvm if [ -s "$NVM_DIR/nvm.sh" ]; then . "$NVM_DIR/nvm.sh" elif [ -s "$HOME/.nvm/nvm.sh" ]; then export NVM_DIR="$HOME/.nvm" . "$NVM_DIR/nvm.sh" else echo "nvm not found. Please install Node 18 or higher manually." echo "See also README.md for instructions." exit 1 fi echo "Installing latest LTS Node version via nvm..." nvm install --lts nvm use --lts NODE_VERSION=$(node -v) if [[ ! $NODE_VERSION =~ ^v(1[8-9]|[2-9][0-9]).* ]]; then echo "Failed to switch to Node 18 or higher via nvm. You have $NODE_VERSION." exit 1 fi fi cd Aspire.AppHost dotnet run --launch-profile https ```