Orchardcore ai chat

From CrestApps/CrestApps.AgentSkills · View interactive version

Orchardcore ai chat is an AI agent skill from the GitHub repository CrestApps/CrestApps.AgentSkills. Skill for setting up and extending AI Chat in Orchard Core with the CrestApps AI Chat module. Covers the AI Chat and AI Chat Admin Widget features, chat profiles on the admin menu, chat session and history pages, Invoke Profile, the frontend AIChat widget with AIProfilePart, chat modes with ChatMode

How to use this skill

Skill file

Orchard Core AI Chat - Prompt Templates

Configure AI Chat

You are an Orchard Core expert. Generate code, configuration, and recipes for adding profile-driven AI chat to an Orchard Core application with the CrestApps AI Chat module.

Guidelines

Features

| Feature | ID | Notes |

|---|---|---|

| AI Chat | CrestApps.OrchardCore.AI.Chat | Admin chat UI, frontend widget, chat modes, prompt security and visitor identity settings |

| AI Chat Admin Widget | CrestApps.OrchardCore.AI.Chat.AdminWidget | Floating chat on every admin page. Depends on AI Chat and CrestApps.OrchardCore.AI.Agent |

| AI Chat Session Analytics | CrestApps.OrchardCore.AI.Chat.Analytics | See orchardcore-ai-chat-analytics |

| AI Chat Services | CrestApps.OrchardCore.AI.Chat.Core | Dependency only; hub, session manager and handlers |

| AI Chat WebAPI | CrestApps.OrchardCore.AI.Chat.Api | REST chat API and the AG-UI endpoint POST /api/ai/v1/agui, shipped by the AI module |

Provider features: CrestApps.OrchardCore.OpenAI, CrestApps.OrchardCore.OpenAI.Azure, CrestApps.OrchardCore.AzureAIInference, CrestApps.OrchardCore.Ollama. See orchardcore-ai-providers.

Enable AI Chat

{
  "steps": [
    {
      "name": "Feature",
      "enable": [
        "CrestApps.OrchardCore.AI.Chat",
        "CrestApps.OrchardCore.OpenAI"
      ],
      "disable": []
    }
  ]
}

Connection, Deployments and a Chat Profile

{
  "steps": [
    {
      "name": "AIProviderConnections",
      "Connections": [
        {
          "Source": "OpenAI",
          "Name": "openai",
          "DisplayText": "OpenAI",
          "Properties": {
            "OpenAIConnectionMetadata": {
              "Endpoint": "https://api.openai.com/v1",
              "ApiKey": "{{YourApiKey}}"
            }
          }
        }
      ]
    },
    {
      "name": "AIDeployment",
      "Deployments": [
        {
          "Name": "gpt-4o",
          "ClientName": "OpenAI",
          "ConnectionName": "openai",
          "Properties": {
            "AIDeploymentMetadata": {
              "Features": [ "textGeneration", "toolCalling", "streaming" ]
            }
          }
        },
        {
          "Name": "gpt-4o-mini",
          "ClientName": "OpenAI",
          "ConnectionName": "openai",
          "Properties": {
            "AIDeploymentMetadata": {
              "Features": [ "textGeneration", "toolCalling", "streaming" ]
            }
          }
        }
      ]
    },
    {
      "name": "AIProfile",
      "Profiles": [
        {
          "Name": "customer-support-chat",
          "DisplayText": "Customer Support Chat",
          "WelcomeMessage": "Hello! How can I help you today?",
          "Type": "Chat",
          "TitleType": "InitialPrompt",
          "ChatDeploymentName": "gpt-4o",
          "UtilityDeploymentName": "gpt-4o-mini",
          "Properties": {
            "AIProfileMetadata": {
              "SystemMessage": "You are a helpful customer support assistant. Be friendly and concise.",
              "Temperature": 0.3,
              "MaxTokens": 2048,
              "PastMessagesCount": 10
            }
          },
          "Settings": {
            "AIChatProfileSettings": {
              "IsOnAdminMenu": true
            },
            "ChatModeProfileSettings": {
              "ChatMode": "TextInput",
              "EnableTextToSpeechPlayback": false
            }
          }
        }
      ]
    }
  ]
}

Define a Chat Profile in Code

public sealed class SiteAssistantMigrations : DataMigration
{
    private readonly IAIProfileManager _profileManager;

    public SiteAssistantMigrations(IAIProfileManager profileManager)
    {
        _profileManager = profileManager;
    }

    public async Task<int> CreateAsync()
    {
        var profile = await _profileManager.NewAsync();

        profile.Name = "site-assistant";
        profile.DisplayText = "Site Assistant";
        profile.Type = AIProfileType.Chat;

        profile.WithSettings(new AIProfileSettings
        {
            LockSystemMessage = true,
            IsRemovable = false,
            IsListable = true,
        });

        profile.WithSettings(new AIChatProfileSettings
        {
            IsOnAdminMenu = true,
        });

        profile.Put(new AIProfileMetadata
        {
            SystemMessage = "You are a site assistant. Help users navigate the site and answer questions.",
            Temperature = 0.3f,
            MaxTokens = 4096,
            PastMessagesCount = 10,
        });

        var result = await _profileManager.ValidateAsync(profile);

        if (result.Succeeded)
        {
            await _profileManager.CreateAsync(profile);
        }

        return 1;
    }
}

IAIProfileManager is a catalog manager: NewAsync, ValidateAsync, CreateAsync, UpdateAsync, FindByNameAsync, DeleteAsync. There is no SaveAsync.

For agent profiles, profile types and tools, see orchardcore-ai, orchardcore-ai-agent and orchardcore-ai-tools. The framework profile API is described in crestapps-core-ai-profiles.

Profile Editor Layout

Chat Modes

| Mode | Behavior | Requirement |

|---|---|---|

| TextInput | Typed chat (default) | None |

| AudioInput | Microphone dictation; transcript is placed in the input for review | A speech-to-text deployment in the speechToText slot |

| Conversation | Voice toggle beside a working message box; both kinds of turn land in one thread | A realtime deployment that resolves, or both speech-to-text and text-to-speech deployments |

profile.AlterSettings<ChatModeProfileSettings>(settings =>
{
    settings.ChatMode = ChatMode.Conversation;

    // Empty means the site's default realtime deployment, then the first realtime-capable one.
    settings.ConversationDeploymentName = "gpt-realtime";
    settings.VoiceName = "alloy";
    settings.EnableTextToSpeechPlayback = false;
});

Admin Chat Pages

| Route | Purpose | Permission |

|---|---|---|

| ai/chat/session/{profileId}/{sessionId?} | Admin chat session | QueryAnyAIProfile or QueryAIProfile_{name} |

| ai/chat/history/{profileId} | Chat history (AIChatSessions admin list) | Same |

| ai/chat/test/{profileId} | Invoke Profile for Utility and Agent profiles; no session, history or metrics | QueryAnyAIProfile |

| ai/chat/chat-session/delete/{sessionId} | Delete one session | DeleteChatSession |

| ai/chat/history/{profileId}/delete-all | Delete all sessions of a profile | DeleteAllChatSessions |

The history page renders through Orchard Core's AdminList shape (AIChatSessions, rows are AIChatSessionEntry_SummaryAdmin, grid columns Name, Status, LastActivity, Actions). Add columns with an IAdminListColumnsProvider for AIChatSessions; see orchardcore-admin-lists.

Admin Widget

Enable CrestApps.OrchardCore.AI.Chat.AdminWidget, then pick the profile, the history size (1 to 50, default 10), the primary color (default #41b670) and Tell the AI which page the user is on (SendPageContext, on by default) in the Admin Widget section of Settings → Artificial Intelligence (permission ManageAIProfiles). It renders for signed-in users allowed to query that profile and keeps its position, size and session in browser local storage.

{
  "steps": [
    {
      "name": "Settings",
      "AIChatAdminWidgetSettings": {
        "ProfileId": "<chat-profile-id>",
        "MaxSessions": 10,
        "PrimaryColor": "#41b670",
        "SendPageContext": true
      }
    }
  ]
}

AG-UI: the Assistant Works on the Page

The chat page, the admin widget, the frontend widget and the profile test page run the chat as an AG-UI agent over the AI chat hub (RunAgent, from CrestApps.Core; see crestapps-core-ag-ui). Nothing needs to be enabled.

services.AddCoreAITool<ArchiveOrdersTool>(ArchiveOrdersTool.TheName)
    .WithTitle(S["Archive Orders"])
    .RequireApproval()
    .Selectable();

A module adds context for the records it owns with IAIChatPageContextProvider (CrestApps.OrchardCore.AI.Chat.Core.Services). Providers run when the widget renders on each admin page, so read only what is already loaded or cached:

public sealed class OrderPageContextProvider : IAIChatPageContextProvider
{
    public Task PopulateAsync(AIChatPageContext context)
    {
        if (context.GetRouteValue("area") == "MyCompany.Orders" && context.GetRouteValue("orderId") is { } orderId)
        {
            context.Add("Order being edited", $"Order {orderId}");
        }

        return Task.CompletedTask;
    }
}

// In the startup of the feature that owns orders:
services.AddScoped<IAIChatPageContextProvider, OrderPageContextProvider>();

AG-UI endpoint. With AI Chat WebAPI (CrestApps.OrchardCore.AI.Chat.Api), any AG-UI client (such as a CopilotKit front end) runs chat profiles at POST /api/ai/v1/agui with a RunAgentInput, answered as Server-Sent Events. Put the profile id in forwardedProps.profileId and the session id in threadId (empty starts a session). Authenticate with an AI API key whose areas include ai.chat (X-Api-Key header or bearer) or an OpenID bearer token; others get 401. The hub then authorizes the profile and session. JSON only, no antiforgery token.

Frontend Widget

With OrchardCore.Widgets enabled, the module creates the AIChat widget type (Artificial Intelligence Chat) with AIProfilePart (ProfileId, TotalHistory). The widget renders only for visitors allowed to query the profile, so grant the Anonymous role QueryAIProfile_{profileName} for a public assistant. History is listed for the visitor's own identity: a signed-in user's sessions, or the sessions owned by an anonymous visitor's cookie.

{
  "steps": [
    {
      "name": "Roles",
      "Roles": [
        {
          "Name": "Anonymous",
          "PermissionBehavior": "Add",
          "Permissions": [ "QueryAIProfile_customer-support-chat" ]
        }
      ]
    }
  ]
}

Prompt Security and Visitor Identity

Both are sections of Settings → Artificial Intelligence (permission ManageAIProfiles) and both are site settings that can be set with the Settings recipe step. Saving either still releases the tenant shell, because their readers in CrestApps.Core use IOptions<T>.

{
  "steps": [
    {
      "name": "Settings",
      "PromptSecurityOptions": {
        "EnableInjectionDetection": true,
        "MaxPromptLength": 8000,
        "BlockingThreshold": "High",
        "MaxMessagesPerWindow": 20,
        "RateLimitWindow": "00:01:00",
        "AnonymousMessageRateLimitTiers": [
          { "Limit": 5, "Window": "00:00:30" },
          { "Limit": 150, "Window": "01:00:00" }
        ],
        "AnonymousSessionStartRateLimitTiers": [
          { "Limit": 10, "Window": "00:05:00" }
        ]
      },
      "AIVisitorIdentityOptions": {
        "CookieName": "crestapps-ai-visitor",
        "CookieLifetime": "180.00:00:00",
        "AllowCrossSiteEmbedding": true,
        "UsePartitionedCookie": true,
        "RemoteAddressMode": "Hashed"
      }
    }
  ]
}

Session Documents and Citations

AIChatHub Methods

The hub is mapped with SignalRHubRoutes.GetHubPath<AIChatHub>(), and ConfigureCrestAppsChatHubOptions<AIChatHub>() sets its SignalR options.

| Method | Purpose |

|---|---|

| StartSession | Start a session for a profile |

| LoadSession | Load a session and join its group |

| SendMessage | Stream a reply to a typed prompt |

| SendAudioStream | Stream audio for dictation |

| StartConversation / StopConversation | Speech-to-text plus text-to-speech conversation |

| StartRealtimeConversation / StartRealtimeWebRtc | Realtime voice over WebSocket or WebRTC |

| GetRealtimeIceServers, AddRealtimeIceCandidate, UpdateRealtimeSettings, UpdateRealtimeSpeechSpeed | Realtime session control |

| SynthesizeSpeech | Read an answer aloud |

| RateMessage | Thumbs up or down |

| HandleNotificationAction | Run a notification action, see orchardcore-ai-chat-notifications |

| RunAgent | Run one AG-UI turn (the chat UI and widgets use it; tool cards, approvals and page context ride on it) |

| SetPageTools / ClearPageTools | Register or clear the WebMCP tools of the user's current page (WebMCP bridge) |

Resources

The chat UI comes from the @crestapps/ai-chat-ui package. Scripts AIChatApp, AIChatWidgetApp, realtime-audio and chat-image-carousel, and styles AIChatApp, AIChatWidget and chat-image-carousel, are registered by the modules. Assistant messages show the persona's name and avatar when a persona is linked.

Upgrading from 2.x

See ai-chat-examples.md for more recipes.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.