### Installing Project Dependencies - Bash Source: https://github.com/chrismckee1/chatui/blob/main/docs/setup/development.md Install all necessary project dependencies listed in the package.json file. This command uses npm, assuming Node.js is installed. Alternatively, yarn can be used. ```bash npm install ``` -------------------------------- ### Example API Configuration Update - Shell Source: https://github.com/chrismckee1/chatui/blob/main/docs/setup/development.md Example of how to update the .env.local file to point the standard chat API to a local development endpoint instead of using the mock service. This is used for testing integration with a custom or locally running API. ```shell NEXT_PUBLIC_STANDARD_CHAT_API_URL=http://localhost:your-port/your-endpoint NEXT_PUBLIC_STANDARD_CHAT_API_MODE=api ``` -------------------------------- ### Previewing Production Build - Bash Source: https://github.com/chrismckee1/chatui/blob/main/docs/setup/development.md Serve the production build locally to test how it will behave before deployment. This allows verification of the optimized code and assets. ```bash npm run start ``` -------------------------------- ### Running Local Development Server - Bash Source: https://github.com/chrismckee1/chatui/blob/main/docs/setup/development.md Start the application in development mode. This typically involves live reloading and other development-specific features. The application will be accessible via a local URL, commonly http://localhost:3000. ```bash npm run dev ``` -------------------------------- ### Cloning Repository and Navigating Directory - Bash Source: https://github.com/chrismckee1/chatui/blob/main/README.md This bash command sequence clones the source code repository from the specified URL and then changes the current directory into the newly cloned project folder. It is the first step in the quick start setup guide. ```Bash git clone \ncd chat-ui ``` -------------------------------- ### Cloning Repository and Navigating Directory - Bash Source: https://github.com/chrismckee1/chatui/blob/main/docs/setup/development.md Clone the Chat UI repository from the specified URL and then change the current directory into the newly cloned project folder. This is the first step in setting up the project locally. ```bash git clone cd chat-ui ``` -------------------------------- ### Building Application for Production - Bash Source: https://github.com/chrismckee1/chatui/blob/main/docs/setup/development.md Compile and optimize the application code for a production deployment. This command generates the necessary static files and assets in a build directory. ```bash npm run build ``` -------------------------------- ### Configuring Environment Variables - Shell Source: https://github.com/chrismckee1/chatui/blob/main/docs/setup/development.md Example content for the .env.local file used to configure application settings such as API endpoints, operational modes (mock/api, stream/batch, local/api history), and application name. These variables control how the application interacts with services during development. ```shell # Chat API endpoints - will be used for production builds NEXT_PUBLIC_STANDARD_CHAT_API_URL=https://api.example.com/chat NEXT_PUBLIC_MULTI_AGENT_CHAT_API_URL=https://api.example.com/multi-agent-chat NEXT_PUBLIC_CHAT_HISTORY_API_URL=https://api.example.com/chat-history # Development mode settings # Standard chat API mode - set to 'mock' to use mock service or 'api' to use actual endpoint NEXT_PUBLIC_STANDARD_CHAT_API_MODE=mock # Multi-agent chat API mode - set to 'mock' to use mock service or 'api' to use actual endpoint NEXT_PUBLIC_MULTI_AGENT_CHAT_API_MODE=mock # Multi-agent response mode - set to 'stream' for real-time streaming responses or 'batch' for complete history in a single response NEXT_PUBLIC_MULTI_AGENT_RESPONSE_MODE=stream # Chat history mode - set to 'local' to use in-browser session storage or 'api' to use the chat history API endpoint NEXT_PUBLIC_CHAT_HISTORY_MODE=local # Application name - will default to "ChatUI" if not provided NEXT_PUBLIC_APP_NAME=YourAppName ``` -------------------------------- ### Running Storybook - Bash Source: https://github.com/chrismckee1/chatui/blob/main/docs/setup/development.md Launch Storybook, a tool used for developing, documenting, and testing UI components in isolation. Storybook will run on a separate local port, typically http://localhost:6006. ```bash npm run storybook ``` -------------------------------- ### Configuring Production API Modes (dotenv) Source: https://github.com/chrismckee1/chatui/blob/main/docs/api/configuration.md Provides an example .env.production configuration file for a production environment, showing how to set API URLs and enable real API modes for all services, including chat history. Requires a .env.production file. ```dotenv # Example .env.production NEXT_PUBLIC_STANDARD_CHAT_API_URL=https://api.yourproduction.com/chat NEXT_PUBLIC_MULTI_AGENT_CHAT_API_URL=https://api.yourproduction.com/multi-agent-chat NEXT_PUBLIC_CHAT_HISTORY_API_URL=https://api.yourproduction.com/chat-history NEXT_PUBLIC_CHAT_HISTORY_MODE=api NEXT_PUBLIC_STANDARD_CHAT_API_MODE=api NEXT_PUBLIC_MULTI_AGENT_CHAT_API_MODE=api NEXT_PUBLIC_MULTI_AGENT_RESPONSE_MODE=stream ``` -------------------------------- ### Running Development Server - Bash Source: https://github.com/chrismckee1/chatui/blob/main/README.md This bash command executes the development script defined in the `package.json` file using npm. This typically starts a local development server, often with features like hot-reloading, allowing developers to run and test the application locally. ```Bash npm run dev ``` -------------------------------- ### Configuring Development API Modes (dotenv) Source: https://github.com/chrismckee1/chatui/blob/main/docs/api/configuration.md Provides an example .env.local configuration file for local development, showing how to set API URLs and enable real API modes for chat services while keeping chat history local. Requires a .env.local file. ```dotenv # Example .env.local for development with local history but real chat APIs NEXT_PUBLIC_STANDARD_CHAT_API_URL=https://your-api.com/chat NEXT_PUBLIC_MULTI_AGENT_CHAT_API_URL=https://your-api.com/multi-agent-chat NEXT_PUBLIC_CHAT_HISTORY_MODE=local NEXT_PUBLIC_STANDARD_CHAT_API_MODE=api NEXT_PUBLIC_MULTI_AGENT_CHAT_API_MODE=api NEXT_PUBLIC_MULTI_AGENT_RESPONSE_MODE=stream ``` -------------------------------- ### Installing Node.js Dependencies - Bash Source: https://github.com/chrismckee1/chatui/blob/main/README.md This bash command uses npm (Node Package Manager) to install all the required project dependencies listed in the `package.json` file. This step is necessary after cloning the repository to prepare the project for development or building. ```Bash npm install ``` -------------------------------- ### Generating .env File and Building in GitHub Actions (YAML) Source: https://github.com/chrismckee1/chatui/blob/main/docs/setup/deployment.md This YAML snippet from a GitHub Actions workflow demonstrates how to create a `.env` file for Next.js during the build process by echoing GitHub secrets into it. It also shows how to pass environment variables directly to the `npm run build` and `npm test` commands. ```YAML - name: Generate Environment File run: | echo "NEXT_PUBLIC_APP_NAME=${{ secrets.NEXT_PUBLIC_APP_NAME }}" >> .env echo "NEXT_PUBLIC_STANDARD_CHAT_API_URL=${{ secrets.NEXT_PUBLIC_STANDARD_CHAT_API_URL }}" >> .env # Additional variables... - name: Build and test run: | npm run build npm test env: NODE_ENV: production NEXT_PUBLIC_APP_NAME: ${{ secrets.NEXT_PUBLIC_APP_NAME }} # Additional variables... ``` -------------------------------- ### Example API Response Structure (JSON) Source: https://github.com/chrismckee1/chatui/blob/main/docs/architecture/api-response-handling.md This JSON object provides an example of the structure the frontend expects from the backend API response, representing a single message object within an array. It highlights key fields like 'authorRole', 'content', and 'metadata' which are used by the frontend to construct the UI message. ```json [ { "innerContent": null, "metadata": { // Example nested metadata "metadata": { /* ... */ }, "id": "chatcmpl-...", "usage": { /* ... */ }, "createdAt": "..." // Potential location for authorName if not at root }, "authorRole": "ASSISTANT", // Used for role "content": "Hello! How can I assist you today?", // Primary content field "items": null, "encoding": "UTF-8", "contentType": "TEXT", "toolCall": null // Potential location for authorName if not in metadata } ] ``` -------------------------------- ### Configuring Azure App Settings via GitHub Actions (YAML) Source: https://github.com/chrismckee1/chatui/blob/main/docs/setup/deployment.md This YAML workflow defines a GitHub Action that configures application settings for an Azure Static Web App. It uses the `azure/login` action to authenticate with Azure via a service principal secret and the `azure/appservice-settings` action to apply settings defined in a JSON block, referencing GitHub secrets for sensitive values. ```YAML name: Configure Azure App Settings on: workflow_dispatch: # Manual trigger push: branches: - main paths: - 'api/**' # Only run when API code changes jobs: configure-app-settings: runs-on: ubuntu-latest name: Configure App Settings steps: - name: Checkout code uses: actions/checkout@v3 - name: Login to Azure uses: azure/login@v1 with: creds: '${{ secrets.AZURE_CREDENTIALS }}' - name: Configure App Settings uses: azure/appservice-settings@v1 with: app-name: 'chat-ui' mask-inputs: true app-settings-json: | [ { "name": "API_KEY", "value": "${{ secrets.API_KEY }}", "slotSetting": false }, # Additional settings... ] ``` -------------------------------- ### Implementing Standard Chat Endpoint with Semantic Kernel - C# Source: https://github.com/chrismckee1/chatui/blob/main/docs/api/examples/csharp.md Implements the `POST /api/chat` endpoint. It takes a `MessageRequest`, converts the messages into a Semantic Kernel `ChatHistory`, calls the `IChatCompletionService` to get a single response, and returns the resulting `ChatMessageContent` object within a list. ```csharp // Standard chat endpoint (/api/chat) [HttpPost("chat")] public async Task>> StandardChatResponse([FromBody] MessageRequest request) { var chatHistory = new ChatHistory(); request.Messages?.ForEach(m => { var role = m.Role?.ToLowerInvariant() switch { "user" => AuthorRole.User, "assistant" => AuthorRole.Assistant, "system" => AuthorRole.System, _ => AuthorRole.User // Default or handle error }; chatHistory.AddMessage(new ChatMessageContent(role, m.Content)); }); // *** Semantic Kernel Integration Point *** // Get response from SK Chat Completion Service // This might involve kernel.InvokePromptAsync or directly using _chatCompletionService // For simplicity, let's assume _chatCompletionService returns a ChatMessageContent // Example: Directly using the service (without plugins/planning for simplicity) var result = await _chatCompletionService.GetChatMessageContentAsync(chatHistory); // *** Return the SK object directly *** // The result is already ChatMessageContent, wrap in List for consistency return Ok(new List { result }); } ``` -------------------------------- ### Mapping Frontend Error Handling with Mermaid Source: https://github.com/chrismckee1/chatui/blob/main/memory-bank/architectureDiagrams.md This flowchart outlines the frontend error handling strategy, starting from the API service fetch call, through response checking and parsing, and detailing how various error types (HTTP, parse, data, timeout, network) are caught and lead to showing an error message and resetting loading state. ```Mermaid graph TD A1[API Service: fetch] A2[Check Response] A3[Parse JSON] A4[Extract Data] A5[Return Message] E1[HTTP Error] E2[Parse Error] E3[Data Error] E4[Timeout] E5[Network Error] C1[Context: send] C2[Try/Catch] C3[Show Error] C4[Reset Loading] C1-->A1 A1-->A2 A2-->A3 A2-->E1 A3-->A4 A3-->E2 A4-->A5 A4-->E3 A1-->E4 A1-->E5 E1-->C2 E2-->C2 E3-->C2 E4-->C2 E5-->C2 A5-->C2 C2-->C3 C2-->C4 C3-->C4 ``` -------------------------------- ### Creating Azure Service Principal for GitHub Actions (Bash) Source: https://github.com/chrismckee1/chatui/blob/main/docs/setup/deployment.md This Azure CLI command (`az ad sp create-for-rbac`) creates a service principal (an identity for the GitHub Action) with 'contributor' permissions scoped to a specific Azure resource group. The output includes credentials in `--sdk-auth` format, which should be stored securely as a GitHub secret for the workflow to authenticate with Azure. ```Bash az ad sp create-for-rbac --name "chatui-github-actions" --role contributor \ --scopes /subscriptions/{subscription-id}/resourceGroups/{resource-group} \ --sdk-auth ``` -------------------------------- ### Setting GitHub Secret with GitHub CLI (Bash) Source: https://github.com/chrismckee1/chatui/blob/main/docs/setup/deployment.md This bash command uses the GitHub CLI to securely add a new repository secret. The `gh secret set` command takes the secret name and its value (provided via the `--body` flag) to store it in the repository's secrets. ```Bash gh secret set NEXT_PUBLIC_APP_NAME --body "YourAppName" ``` -------------------------------- ### Implementing Streaming Multi-Agent Chat Endpoint - C# Source: https://github.com/chrismckee1/chatui/blob/main/docs/api/examples/csharp.md Implements a streaming endpoint (`POST /api/multi-agent-chat/stream`) using Server-Sent Events. It processes the request, simulates getting multiple `ChatMessageContent` results (e.g., from different agents), serializes each result, and streams it as a separate `data:` event. ```csharp // Streaming endpoint for multi-agent chat (/api/multi-agent-chat/stream) [HttpPost("multi-agent-chat/stream")] public async Task StreamMultiAgentResponse([FromBody] MessageRequest request) { Response.Headers.Append("Content-Type", "text/event-stream"); Response.Headers.Append("Cache-Control", "no-cache"); Response.Headers.Append("Connection", "keep-alive"); var chatHistory = new ChatHistory(); // Populate as in standard chat request.Messages?.ForEach(m => { var role = m.Role?.ToLowerInvariant() switch { "user" => AuthorRole.User, "assistant" => AuthorRole.Assistant, "system" => AuthorRole.System, _ => AuthorRole.User // Default or handle error }; chatHistory.AddMessage(new ChatMessageContent(role, m.Content)); }); // *** Semantic Kernel Integration Point *** // Use streaming completion. This might involve multiple agents/plugins. // We need to simulate multiple responses for the example. // In a real scenario, this might loop through agent results or process SK streaming chunks. var agents = new List { "Research", "Code", "Planning" }; var tempConversationId = Guid.NewGuid().ToString(); // Example ID foreach (var agent in agents) { // Simulate getting a ChatMessageContent result for each agent // In a real app, this would come from invoking the agent/kernel var agentResponse = new ChatMessageContent( AuthorRole.Assistant, content: $"Streamed response from the {agent} agent.", authorName: agent // Set AuthorName for multi-agent // metadata can be added if needed ); agentResponse.Metadata ??= new Dictionary(); agentResponse.Metadata["ConversationId"] = tempConversationId; // Example metadata // *** Serialize and stream the SK object directly *** string jsonResponse = JsonSerializer.Serialize(agentResponse, new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull // Add converters if needed for complex SK types not handled by default }); await Response.WriteAsync($"data: {jsonResponse}\n\n"); await Response.Body.FlushAsync(); await Task.Delay(1000, HttpContext.RequestAborted); // Simulate work } } ``` -------------------------------- ### Defining Chat Response JSON Object Example Source: https://github.com/chrismckee1/chatui/blob/main/docs/api/examples/java.md This snippet illustrates the expected JSON structure for individual message objects within the response array. It highlights the required fields like 'authorRole' and 'content', and shows optional fields like 'authorName' (crucial for multi-agent) and 'metadata'. ```json { "innerContent": null, // Not used by frontend "metadata": { // Can contain arbitrary data "id": "chatcmpl-unique-id", "usage": { /* ... */ }, "authorName": "ResearchAgent" // Possible location for agent name }, "authorRole": "ASSISTANT", // Frontend uses this "content": "Here is the information you requested.", // Frontend uses this "authorName": "ResearchAgent", // Alternative location for agent name "items": null, // Not used by frontend "encoding": "UTF-8", // Not used by frontend "contentType": "TEXT" // Not used by frontend } ``` -------------------------------- ### Example Minimal API Response Format (JSON) Source: https://github.com/chrismckee1/chatui/blob/main/docs/api/response-formats.md Provides the JSON structure required for API backends that do not use Semantic Kernel. This minimal format is an array containing one or more objects (for standard or multi-agent batch respectively), requiring 'Role' (with Label: 'Assistant'), 'Items' (with at least a 'Text' property), and conditionally 'AuthorName' for multi-agent responses. ```json [ { "Role": { "Label": "Assistant" }, "AuthorName": "Agent Name", "ConversationId": "Optional-ID", "Items": [ { "Text": "Response content..." } ] } ] ``` -------------------------------- ### Example API Chat Request Format (JSON) Source: https://github.com/chrismckee1/chatui/blob/main/docs/api/response-formats.md Displays the standard JSON format expected by the API endpoints (/chat, /multi-agent-chat/batch, /multi-agent-chat/stream) for incoming chat messages from the user. It's a JSON object containing a single array of message objects, each having a 'role' ('user' or 'assistant') and the message 'content'. ```json { "messages": [ { "role": "user", "content": "..." }, { "role": "assistant", "content": "..." }, { "role": "user", "content": "latest message..." } ] } ``` -------------------------------- ### Example Semantic Kernel Response for Multi-Agent Batch (JSON) Source: https://github.com/chrismckee1/chatui/blob/main/docs/api/response-formats.md Shows the JSON structure for a '/multi-agent-chat/batch' endpoint response using Semantic Kernel's ChatMessageContent. It's an array containing multiple serialized objects, each representing a response from a distinct agent and identifiable by the 'AuthorName' field. ```json [ { "Role": { "Label": "Assistant" }, "AuthorName": "Agent1", "Content": "Agent 1 response.", "Items": [{ "$type": "TextContent", "Text": "Agent 1 response." }] }, { "Role": { "Label": "Assistant" }, "AuthorName": "Agent2", "Content": "Agent 2 response.", "Items": [{ "$type": "TextContent", "Text": "Agent 2 response." }] } ] ``` -------------------------------- ### Example Semantic Kernel Response for Standard Chat (JSON) Source: https://github.com/chrismckee1/chatui/blob/main/docs/api/response-formats.md Illustrates the expected JSON format for a standard '/chat' endpoint response when the backend uses Semantic Kernel and serializes a single ChatMessageContent object. The response is an array containing one object representing the assistant's reply, including Role, Content, and Items fields. ```json [ { "Role": { "Label": "Assistant" }, "Content": "This is the main response text.", "Items": [ { "$type": "TextContent", "Text": "This is the main response text." } ], "Metadata": { } } ] ``` -------------------------------- ### Illustrating Deployment Architecture with Mermaid Source: https://github.com/chrismckee1/chatui/blob/main/memory-bank/architectureDiagrams.md This flowchart visualizes the deployment process, showing the flow from development through CI/CD to cloud infrastructure components and configuration sources. It details dependencies between stages and environments. ```Mermaid %%{init: {'theme':'dark'}}%% flowchart TD subgraph Development["Development Environment"] Local[Local Development] PR[Pull Request Previews] end subgraph CI_CD["CI/CD Pipeline"] GHA[GitHub Actions] BuildTest[Build & Test] Deploy[Deploy] ManualTrigger[Manual Workflow Trigger] end subgraph Infrastructure["Cloud Infrastructure"] subgraph FrontendInfra["Frontend Infrastructure"] AzureStaticWebApps[Azure Static Web Apps] CDN[Azure CDN] Monitoring[Application Insights] end subgraph BackendInfra["Backend Infrastructure (Separate)"] API_Backend[API Backend Services] AppService[Azure App Service] end end subgraph Configuration["Environment Configuration"] subgraph FrontendConfig["Frontend Configuration"] EnvLocal[.env.local] GitHubSecrets[GitHub Secrets] BuildEnv[Build-time Variables] NextConfig[Next.js Config] end subgraph BackendConfig["Backend Configuration"] AppSettings[Azure App Settings] KeyVault[Azure Key Vault] end end Local -->|Changes| PR PR -->|Triggers| GHA ManualTrigger -->|Triggers| GHA GHA -->|Executes| BuildTest BuildTest -->|If successful| Deploy BuildTest -->|Uses| NextConfig NextConfig -->|Ignores Linting/TypeScript Errors| BuildTest Deploy -->|Deploys to| AzureStaticWebApps AzureStaticWebApps -->|Fronted by| CDN AzureStaticWebApps -->|Monitored by| Monitoring EnvLocal -->|Used in| Local GitHubSecrets -->|Generates| BuildEnv BuildEnv -->|Used in| BuildTest GitHubSecrets -->|Used in| Deploy style Development fill:#1565c0,stroke:#0d47a1,color:#ffffff style CI_CD fill:#6a1b9a,stroke:#4a148c,color:#ffffff style FrontendInfra fill:#e65100,stroke:#bf360c,color:#ffffff style BackendInfra fill:#d84315,stroke:#bf360c,color:#ffffff style FrontendConfig fill:#2e7d32,stroke:#1b5e20,color:#ffffff style BackendConfig fill:#558b2f,stroke:#33691e,color:#ffffff style ManualTrigger fill:#5e35b1,stroke:#4527a0,color:#ffffff linkStyle default stroke:#88ccff,stroke-width:2px ``` -------------------------------- ### Setting Up FastAPI App and Chat Service Helper Python Source: https://github.com/chrismckee1/chatui/blob/main/docs/api/examples/python.md This Python snippet initializes the FastAPI application instance. It also includes a placeholder asynchronous function `get_chat_service` which is intended to retrieve a configured Semantic Kernel `ChatCompletionClientBase` instance. Users need to replace the placeholder logic with their actual dependency injection or service retrieval code. ```python app = FastAPI() # --- Assume Kernel and Chat Service are configured and potentially injected --- # kernel = Kernel() # kernel.add_service(...) # Add your configured AzureChatCompletion or OpenAIChatCompletion # chat_service = kernel.get_service(ChatCompletionClientBase) # Helper to get configured chat service (replace with your actual injection/retrieval logic) async def get_chat_service() -> ChatCompletionClientBase: # This is a placeholder. In a real app, you'd likely inject the kernel or service. from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion # Example # Load config from env or other sources # service = AzureChatCompletion(...) # return service raise NotImplementedError("Kernel/Chat Service not configured in this example") ``` -------------------------------- ### Setting Up Spring Boot Chat Controller Source: https://github.com/chrismckee1/chatui/blob/main/docs/api/examples/java.md This snippet initializes the main REST controller class `ChatController` with the `@RestController` and `@RequestMapping` annotations. It sets up an `ObjectMapper` for JSON handling and includes an optional constructor if integrating with Semantic Kernel, providing a basic constructor otherwise. ```Java @RestController @RequestMapping("/api") public class ChatController { private final ObjectMapper objectMapper = new ObjectMapper(); // --- Remove SK services if not used --- // private final ChatCompletionService chatCompletionService; // private final Kernel kernel; // public ChatController(ChatCompletionService chatCompletionService, Kernel kernel) { // this.chatCompletionService = chatCompletionService; // this.kernel = kernel; // } // Basic constructor if not using SK public ChatController() {} } ``` -------------------------------- ### Diagramming Responsive Design System with Mermaid Source: https://github.com/chrismckee1/chatui/blob/main/docs/architecture/responsive-design.md This Mermaid flowchart visualizes the architecture of a responsive design system. It defines breakpoints, component adaptation categories, and implementation technologies, showing how breakpoints influence implementations which in turn affect component adaptations. ```mermaid %%{init: {'theme':'dark'}}%% flowchart TD subgraph Breakpoints["Breakpoint System"] XXS["xs < 360px (Very Small)"] XS["xs < 600px (Mobile)"] SM["sm 600-900px (Tablet)"] MD["md 900-1200px (Large Tablet)"] LG["lg 1200-1536px (Desktop)"] XL["xl > 1536px (Large Desktop)"] end subgraph Component_Adaptations["Component Adaptations"] Layout[Responsive Layout] Spacing[Responsive Spacing] Typography[Responsive Typography] UI_Elements[UI Element Sizing] Chat_Interface[Chat Interface] end subgraph Implementation["Implementation Technologies"] MUI_BP[MUI Breakpoints] Media_Queries[CSS Media Queries] TW_BP[Tailwind Breakpoints] React_Hooks[React Hooks] end Breakpoints -->|Define| Implementation Implementation -->|Applied to| Component_Adaptations XXS -->|Very compact UI| UI_Elements XXS -->|Minimal padding| Spacing XXS -->|Smaller fonts| Typography XXS -->|Collapsed header| Chat_Interface XS -->|Stack layout| Layout XS -->|Reduced padding| Spacing XS -->|Optimized fonts| Typography XS -->|Mobile optimized UI| UI_Elements SM -->|Adaptive layout| Layout SM -->|Balanced spacing| Spacing SM -->|Tablet-optimized UI| UI_Elements MD -->|Hybrid layout| Layout LG -->|Full layout| Layout XL -->|Enhanced layout| Layout style Breakpoints fill:#1565c0,stroke:#0d47a1,color:#ffffff style Component_Adaptations fill:#6a1b9a,stroke:#4a148c,color:#ffffff style Implementation fill:#2e7d32,stroke:#1b5e20,color:#ffffff linkStyle default stroke:#88ccff,stroke-width:2px ``` -------------------------------- ### Visualizing Deployment Flow with Mermaid Source: https://github.com/chrismckee1/chatui/blob/main/docs/architecture/deployment-architecture.md This Mermaid diagram defines the visual representation of the project's deployment architecture. It depicts the stages from Development (Local, PR Previews) through the CI/CD pipeline (GitHub Actions) to the Azure Cloud Infrastructure (Frontend on Static Web Apps/CDN, Backend on App Service) and the relevant Configuration sources (.env.local, GitHub Secrets, Azure App Settings, Key Vault). ```mermaid %%{init: {'theme':'dark'}}%% flowchart TD subgraph Development["Development Environment"] Local[Local Development] PR[Pull Request Previews] end subgraph CI_CD["CI/CD Pipeline"] GHA[GitHub Actions] BuildTest[Build & Test] Deploy[Deploy] ManualTrigger[Manual Workflow Trigger] end subgraph Infrastructure["Cloud Infrastructure"] subgraph FrontendInfra["Frontend Infrastructure"] AzureStaticWebApps[Azure Static Web Apps] CDN[Azure CDN] Monitoring[Application Insights] end subgraph BackendInfra["Backend Infrastructure (Separate)"] API_Backend[API Backend Services] AppService[Azure App Service] end end subgraph Configuration["Environment Configuration"] subgraph FrontendConfig["Frontend Configuration"] EnvLocal[.env.local] GitHubSecrets[GitHub Secrets] BuildEnv[Build-time Variables] NextConfig[Next.js Config] end subgraph BackendConfig["Backend Configuration"] AppSettings[Azure App Settings] KeyVault[Azure Key Vault] end end Local -->|Changes| PR PR -->|Triggers| GHA ManualTrigger -->|Triggers| GHA GHA -->|Executes| BuildTest BuildTest -->|If successful| Deploy BuildTest -->|Uses| NextConfig NextConfig -->|Ignores Linting/TypeScript Errors| BuildTest Deploy -->|Deploys to| AzureStaticWebApps AzureStaticWebApps -->|Fronted by| CDN AzureStaticWebApps -->|Monitored by| Monitoring EnvLocal -->|Used in| Local GitHubSecrets -->|Generates| BuildEnv BuildEnv -->|Used in| BuildTest GitHubSecrets -->|Used in| Deploy style Development fill:#1565c0,stroke:#0d47a1,color:#ffffff style CI_CD fill:#6a1b9a,stroke:#4a148c,color:#ffffff style FrontendInfra fill:#e65100,stroke:#bf360c,color:#ffffff style BackendInfra fill:#d84315,stroke:#bf360c,color:#ffffff style FrontendConfig fill:#2e7d32,stroke:#1b5e20,color:#ffffff style BackendConfig fill:#558b2f,stroke:#33691e,color:#ffffff style ManualTrigger fill:#5e35b1,stroke:#4527a0,color:#ffffff linkStyle default stroke:#88ccff,stroke-width:2px ``` -------------------------------- ### Diagramming Service Architecture using Mermaid Source: https://github.com/chrismckee1/chatui/blob/main/docs/architecture/service-design.md This snippet uses the Mermaid syntax to visualize the service architecture, showing how UI components interact with context, interfaces, a service factory, and various mock and API service implementations. ```Mermaid graph TD UI[UI Components] IC[Chat Context] ISC[IChatService Interface] IHS[IHistoryService Interface] SF[Service Factory] MSC[Mock Chat Service] ASC[API Chat Service] MHS[Mock History Service] AHS[API History Service] UI --> IC IC --> ISC IC --> IHS ISC --> SF IHS --> SF SF --> MSC SF --> ASC SF --> MHS SF --> AHS ``` -------------------------------- ### Importing Semantic Kernel and ASP.NET Core Namespaces - C# Source: https://github.com/chrismckee1/chatui/blob/main/docs/api/examples/csharp.md Includes necessary using directives for core .NET libraries, ASP.NET Core MVC, Semantic Kernel components (like `Kernel` and `IChatCompletionService`), and JSON serialization, required for building the chat API controller. ```csharp using System; using System.Collections.Generic; using System.Linq; using System.Text.Json; using System.Text.Json.Serialization; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.ChatCompletion; ``` -------------------------------- ### Setting up ASP.NET Core Chat Controller - C# Source: https://github.com/chrismckee1/chatui/blob/main/docs/api/examples/csharp.md Defines the `ChatController` class as an ASP.NET Core `ApiController`. It sets the base route to "api" and includes dependency injection for `IChatCompletionService` and `Kernel`, which are used to interact with Semantic Kernel. ```csharp [ApiController] [Route("api")] public class ChatController : ControllerBase { private readonly IChatCompletionService _chatCompletionService; private readonly Kernel _kernel; // Assuming Kernel is injected or available public ChatController(IChatCompletionService chatCompletionService, Kernel kernel) { _chatCompletionService = chatCompletionService; _kernel = kernel; // Required if using plugins/function calling } ``` -------------------------------- ### Diagramming Loading/Error States with Mermaid Source: https://github.com/chrismckee1/chatui/blob/main/docs/architecture/error-handling.md This Mermaid flowchart illustrates the system for handling loading and error states within a chat UI. It shows how user actions (Triggers) activate states (Loading/Error), how these states control UI indicators (Spinners, Disabled Inputs, Messages), and how the Error state initiates handling mechanisms like Try/Catch blocks and logging. This helps visualize the overall state management and UI response. ```Mermaid %%{init: {'theme':'dark'}}%% flowchart TD subgraph Triggers["Loading Triggers"] SendMsg[Send Message] FetchHistory[Load Chat History] SwitchChat[Switch Chat] SwitchMode[Switch Agent Mode] end subgraph States["Loading & Error States"] Loading[Loading State] Error[Error State] end subgraph UI_Indicators["UI Indicators"] Spinners[Loading Spinners] Disabled[Disabled Inputs] Messages[Status Messages] Animations[Loading Animations] ErrorDisplay[Error Messages] RetryOptions[Retry Options] end subgraph Handling["Error Handling"] Catch[Try/Catch Blocks] Log[Error Logging] Fallback[Fallback Content] Recovery[Recovery Actions] end Triggers -->|Activates| States States -->|Controls| UI_Indicators Error -->|Triggers| Handling SendMsg -->|Sets| Loading FetchHistory -->|Sets| Loading SwitchChat -->|Sets| Loading SwitchMode -->|Sets| Loading Loading -->|Shows| Spinners Loading -->|Enables| Disabled Loading -->|Displays| Messages Loading -->|Triggers| Animations Error -->|Shows| ErrorDisplay Error -->|Offers| RetryOptions Catch -->|Captures| Error Log -->|Records| Error Fallback -->|Displays when| Error Recovery -->|Attempts after| Error style Triggers fill:#1565c0,stroke:#0d47a1,color:#ffffff style States fill:#6a1b9a,stroke:#4a148c,color:#ffffff style UI_Indicators fill:#e65100,stroke:#bf360c,color:#ffffff style Handling fill:#2e7d32,stroke:#1b5e20,color:#ffffff linkStyle default stroke:#88ccff,stroke-width:2px ``` -------------------------------- ### Configuring Azure App Service Settings in GitHub Actions YAML Source: https://github.com/chrismckee1/chatui/blob/main/memory-bank/techContext.md Demonstrates how to use the `azure/appservice-settings` GitHub Action within a workflow to configure runtime application settings for an Azure App Service. This method is typically used for production deployments to update configuration without requiring a full application rebuild. Inputs include the target application name and a JSON array defining the settings. ```YAML - uses: azure/appservice-settings@v1 with: app-name: 'app-name' mask-inputs: true app-settings-json: '[{ "name": "SETTING_NAME", "value": "SETTING_VALUE" }]' ``` -------------------------------- ### Visualize Application Architecture - Mermaid Source: https://github.com/chrismckee1/chatui/blob/main/memory-bank/architectureDiagrams.md This diagram presents the main architectural layers and their interactions within the Chat UI application. It shows how the Next.js framework integrates with context providers, the UI layer, and the service layer, which in turn interacts with external systems and telemetry. It outlines the structure of services (Chat and History) and their different implementations. ```mermaid %%{init: {'theme':'dark'}}%% flowchart TD subgraph Next_Framework["Next.js Framework"] App[App Router] Layout[Root Layout] Page[Page Component] end subgraph Context_Providers["Context Providers"] CP[ChatProvider] TP[ThemeProvider] SP[ServiceProvider] end subgraph UI_Layer["UI Layer"] TPL[ChatPageLayout Template] Components[UI Components] end subgraph Service_Layer["Service Layer"] SF[ServiceFactory] subgraph Chat_Services["Chat Services"] ICS[IChatService Interface] MCS[MockChatService] ACS[ApiChatService] end subgraph History_Services["History Services"] IHS[IHistoryService Interface] LHS[LocalHistoryService] AHS[ApiHistoryService] MHS[MockHistoryService] end end subgraph Telemetry["Telemetry"] OpenTel[OpenTelemetry] TelUtils[Telemetry Utils] end subgraph External_Systems["External Systems"] APIs[Chat & History APIs] LocalStorage[Browser LocalStorage] TelBackend[Telemetry Backend] end App --> Layout Layout --> Page Layout --> Context_Providers Page --> UI_Layer Context_Providers --> TPL CP --> Components TP --> Components SP --> SF SF --> ICS SF --> IHS ICS --> MCS ICS --> ACS IHS --> LHS IHS --> AHS IHS --> MHS ACS --> APIs AHS --> APIs LHS --> LocalStorage Components --> TelUtils TelUtils --> OpenTel OpenTel --> TelBackend style Next_Framework fill:#1565c0,stroke:#0d47a1,color:#ffffff style Context_Providers fill:#6a1b9a,stroke:#4a148c,color:#ffffff style UI_Layer fill:#e65100,stroke:#bf360c,color:#ffffff style Service_Layer fill:#2e7d32,stroke:#1b5e20,color:#ffffff style External_Systems fill:#d84315,stroke:#bf360c,color:#ffffff style Telemetry fill:#0097a7,stroke:#006064,color:#ffffff linkStyle default stroke:#88ccff,stroke-width:2px ``` -------------------------------- ### Creating Chat and History Services using Factory Pattern (TypeScript) Source: https://github.com/chrismckee1/chatui/blob/main/docs/architecture/service-design.md This TypeScript class demonstrates the Factory pattern for creating instances of IChatService and IHistoryService. It determines the appropriate service implementation (API or Mock/Local) based on environment variables or the specified agent mode, abstracting the creation logic from the calling code. ```TypeScript export class ServiceFactory { static createChatService(agentMode: AgentMode): IChatService { // Determine which service to create based on environment variables const mode = agentMode === 'standard' ? getStandardChatMode() : getMultiAgentChatMode(); return mode === 'api' ? new ApiChatService() : new MockChatService(); } static createHistoryService(): IHistoryService { const mode = getChatHistoryMode(); return mode === 'api' ? new ApiHistoryService() : new LocalHistoryService(); } } ``` -------------------------------- ### Importing Dependencies for FastAPI Semantic Kernel App Python Source: https://github.com/chrismckee1/chatui/blob/main/docs/api/examples/python.md This Python snippet lists the necessary imports for building the FastAPI application that integrates with Semantic Kernel. It includes modules for asynchronous operations, UUID generation, type hinting, FastAPI components, and specific Semantic Kernel classes for chat history, message content, and author roles. ```python import asyncio import uuid from typing import List, Optional from fastapi import FastAPI from fastapi.responses import StreamingResponse from pydantic import BaseModel from semantic_kernel import Kernel # Assuming Kernel is configured from semantic_kernel.connectors.ai.chat_completion_client_base import ChatCompletionClientBase # Base type for services from semantic_kernel.contents.chat_history import ChatHistory from semantic_kernel.contents.chat_message_content import ChatMessageContent from semantic_kernel.contents.text_content import TextContent from semantic_kernel.contents.utils.author_role import AuthorRole ``` -------------------------------- ### Visualize Component Architecture (Atomic Design) - Mermaid Source: https://github.com/chrismckee1/chatui/blob/main/memory-bank/architectureDiagrams.md This diagram illustrates the frontend UI component structure based on the Atomic Design pattern. It shows how smaller components (Atoms, Molecules) are composed into larger ones (Organisms, Templates) to form the Chat UI's page layout. It highlights the dependencies between different component levels. ```mermaid %%{init: {'theme':'dark'}}%% flowchart TD subgraph Templates TPL[ChatPageLayout] end subgraph Organisms O1[ChatHeader] O2[ChatHistoryPanel] O3[ChatInputArea] O4[ChatMessagePanel] end subgraph Molecules M1[MessageBubble] M2[ChatInput] M3[AgentToggle] M4[ThemeToggle] M5[ChatHistoryItem] M6[NewChatButton] M7[ToolMessageToggle] end subgraph Atoms A1[Button] A2[Typography] A3[TextField] A4[Box] A5[Avatar] A6[Fade] A7[Lucide Icons] A8[Spinner] A9[Switch] end TPL --> O1 TPL --> O2 TPL --> O3 TPL --> O4 O1 --> M3 O1 --> M4 O1 --> M7 O2 --> M5 O2 --> M6 O3 --> M2 O4 --> M1 M1 --> A2 M1 --> A4 M1 --> A5 M1 --> A7 M2 --> A1 M2 --> A3 M2 --> A7 M2 --> A8 M3 --> A1 M3 --> A7 M4 --> A1 M4 --> A7 M5 --> A2 M5 --> A4 M5 --> A7 M6 --> A1 M6 --> A7 M7 --> A9 M7 --> A2 M7 --> A7 style Atoms fill:#0277bd,stroke:#01579b,color:#ffffff style Molecules fill:#388e3c,stroke:#1b5e20,color:#ffffff style Organisms fill:#e65100,stroke:#bf360c,color:#ffffff style Templates fill:#6a1b9a,stroke:#4a148c,color:#ffffff linkStyle default stroke:#88ccff,stroke-width:2px ``` -------------------------------- ### Importing Required Java Libraries Source: https://github.com/chrismckee1/chatui/blob/main/docs/api/examples/java.md This snippet lists the necessary Java imports for the Spring Boot controller implementation. It includes imports for Spring web annotations, HTTP types, Reactor Flux for streaming, Jackson for JSON processing, and standard Java utilities like List, Map, and UUID. ```Java import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; // --- Remove Semantic Kernel specific imports if not used --- // import com.microsoft.semantickernel.Kernel; // import com.microsoft.semantickernel.services.chatcompletion.*; // import com.microsoft.semantickernel.services.chatcompletion.message.*; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Flux; import java.time.Duration; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.UUID; ``` -------------------------------- ### Implementing Batch Multi-Agent Chat Endpoint - C# Source: https://github.com/chrismckee1/chatui/blob/main/docs/api/examples/csharp.md Implements a batch endpoint (`POST /api/multi-agent-chat/batch`). It processes the request, simulates obtaining multiple `ChatMessageContent` results (e.g., from different agents), collects them into a list, and returns the complete list as a single JSON response. ```csharp // Batch endpoint for multi-agent chat (/api/multi-agent-chat/batch) [HttpPost("multi-agent-chat/batch")] public async Task>> BatchMultiAgentResponse([FromBody] MessageRequest request) { var chatHistory = new ChatHistory(); // Populate as in standard chat request.Messages?.ForEach(m => { var role = m.Role?.ToLowerInvariant() switch { "user" => AuthorRole.User, "assistant" => AuthorRole.Assistant, "system" => AuthorRole.System, _ => AuthorRole.User // Default or handle error }; chatHistory.AddMessage(new ChatMessageContent(role, m.Content)); }); // *** Semantic Kernel Integration Point *** // Simulate getting results from multiple agents/kernel invocations var agents = new List { "Research", "Code", "Planning" }; var responses = new List(); var tempConversationId = Guid.NewGuid().ToString(); // Example ID foreach (var agent in agents) { // Simulate getting a ChatMessageContent result for each agent var agentResponse = new ChatMessageContent( AuthorRole.Assistant, content: $"Batch response from the {agent} agent.", authorName: agent // Set AuthorName for multi-agent ); agentResponse.Metadata ??= new Dictionary(); agentResponse.Metadata["ConversationId"] = tempConversationId; // Example metadata responses.Add(agentResponse); } // *** Return the List of SK objects directly *** return Ok(responses); } } ``` -------------------------------- ### Implementing Standard Chat Endpoint (Java, Spring Boot) Source: https://github.com/chrismckee1/chatui/blob/main/docs/api/examples/java.md This code defines a standard `/api/chat` POST endpoint that accepts the `MessageRequest` and returns a single-message response in JSON format (`APPLICATION_JSON_VALUE`). It demonstrates constructing a response `Map` with required fields (`authorRole`, `content`) and optional `metadata`, then wrapping it in a list. ```Java // Standard chat endpoint (/api/chat) @PostMapping(path = "/chat", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity>> standardChatResponse(@RequestBody MessageRequest request) { // 1. Process the incoming messages (e.g., call your LLM/logic) // String userQuery = getLastUserMessage(request); String assistantResponseContent = "Hello! This is a standard response."; // Replace with actual AI response // 2. Construct the response object matching the frontend expectation Map responseMessage = new HashMap<>(); responseMessage.put("authorRole", "ASSISTANT"); // Required by frontend responseMessage.put("content", assistantResponseContent); // Required by frontend // Add optional metadata if needed Map metadata = new HashMap<>(); metadata.put("id", "some-unique-id-" + UUID.randomUUID()); metadata.put("timestamp", java.time.Instant.now().toString()); responseMessage.put("metadata", metadata); // Standard chat expects a list with a single message List> responseList = List.of(responseMessage); return ResponseEntity.ok(responseList); } ```