Crestapps core chat

From CrestApps/CrestApps.AgentSkills · View interactive version

Crestapps core chat is an AI agent skill from the GitHub repository CrestApps/CrestApps.AgentSkills. Skill for building deployment-aware chat completion and streaming loops in CrestApps.Core 2.0. Covers IAICompletionService CompleteAsync and CompleteStreamingAsync with AICompletionContext, resolving chat and utility deployments through slots with ResolveSlotAsync and ResolveUtilityOrDefaultAsync in

How to use this skill

Skill file

CrestApps.Core Chat Completions

This skill is the server-side completion and orchestration surface. Persisted conversations, hubs, chat UI and response handlers are covered by crestapps-core-chat-interactions; voice sessions by crestapps-core-realtime-voice; providers by crestapps-core-openai, crestapps-core-azure-openai, crestapps-core-ollama and crestapps-core-azure-ai-inference.

Guidelines

Registration

using CrestApps.Core.AI.OpenAI;

builder.Services.AddCrestAppsCore(crestApps => crestApps
    .AddAISuite(ai => ai
        .AddOpenAI()
    )
);

Configure a connection and at least one deployment that declares textGeneration (plus toolCalling and streaming for chat). See the provider skills for the configuration shape.

Stream a Completion

using System.Runtime.CompilerServices;
using CrestApps.Core.AI.Completions;
using CrestApps.Core.AI.Deployments;
using CrestApps.Core.AI.Models;
using Microsoft.Extensions.AI;

namespace MyApp.Services;

public sealed class SupportAnswerService
{
    private readonly IAICompletionService _completionService;
    private readonly IAIDeploymentManager _deploymentManager;

    public SupportAnswerService(
        IAICompletionService completionService,
        IAIDeploymentManager deploymentManager)
    {
        _completionService = completionService;
        _deploymentManager = deploymentManager;
    }

    public async IAsyncEnumerable<string> StreamAsync(
        string prompt,
        string deploymentName = null,
        [EnumeratorCancellation] CancellationToken cancellationToken = default)
    {
        var deployment = await _deploymentManager.ResolveSlotAsync(
            AIDeploymentSlotNames.Chat,
            deploymentName,
            cancellationToken: cancellationToken)
            ?? throw new InvalidOperationException("No deployment can fill the chat slot.");

        var context = new AICompletionContext
        {
            SystemMessage = "You are a concise support assistant.",
            Temperature = 0.2f,
            MaxTokens = 800,
        };

        // Applied only when the deployment declares the reasoning feature and the reasoningEffort parameter.
        context.ModelParameters[AIDeploymentParameterNames.ReasoningEffort] = "Low";

        await foreach (var update in _completionService.CompleteStreamingAsync(
            deployment,
            [new ChatMessage(ChatRole.User, prompt)],
            context,
            cancellationToken))
        {
            if (!string.IsNullOrEmpty(update.Text))
            {
                yield return update.Text;
            }
        }
    }
}

Use CompleteAsync(...) for a single ChatResponse (read response.Text).

Background (Utility) Completions

Titles, summaries, data extraction and query rewriting belong on the utility deployment:

var deployment = await deploymentManager.ResolveUtilityOrDefaultAsync(
    utilityDeploymentName: profile.UtilityDeploymentName,
    chatDeploymentName: profile.ChatDeploymentName)
    ?? throw new InvalidOperationException("No text deployment is configured.");

var context = new AICompletionContext
{
    SystemMessage = "Summarize the conversation in one sentence.",
    IsUtilityCompletion = true,
    DisableTools = true,
};

context.UtilityModelParameters[AIDeploymentParameterNames.ReasoningEffort] = "None";

The chain is explicit utility name, site default utility (DefaultAIDeploymentSettings.DefaultUtilityDeploymentName), explicit chat name, site default chat, then the first text-capable deployment. IsUtilityCompletion makes the named completion path use the utility deployment and the UtilityModelParameters. A host that resolves an IChatClient directly from IAIClientFactory applies the same selections with ChatClientBuilder.UseModelParameters(...) or UseUtilityModelParameters(...).

Run the Full Orchestration Pipeline

Outside the chat hubs, build the orchestration context from a profile (or a ChatInteraction), open an AIInvocationScope in the method that enumerates the whole stream, and push tokens to the caller:

using System.Text;
using CrestApps.Core.AI.Orchestration;
using CrestApps.Core.AI.Profiles;
using Microsoft.Extensions.AI;

namespace MyApp.Services;

public sealed class ProfileRunner
{
    private readonly IAIProfileManager _profileManager;
    private readonly IOrchestrationContextBuilder _contextBuilder;
    private readonly IOrchestratorResolver _orchestratorResolver;

    public ProfileRunner(
        IAIProfileManager profileManager,
        IOrchestrationContextBuilder contextBuilder,
        IOrchestratorResolver orchestratorResolver)
    {
        _profileManager = profileManager;
        _contextBuilder = contextBuilder;
        _orchestratorResolver = orchestratorResolver;
    }

    public async Task<string> RunAsync(
        string profileName,
        string prompt,
        IList<ChatMessage> history,
        Func<string, Task> onToken,
        CancellationToken cancellationToken = default)
    {
        var profile = await _profileManager.FindByNameAsync(profileName, cancellationToken)
            ?? throw new InvalidOperationException($"Profile '{profileName}' was not found.");

        // Tools such as data source search read their context from this ambient scope. It is an AsyncLocal,
        // so open it in the method that enumerates the whole stream, not in an async iterator that yields.
        using var invocationScope = AIInvocationScope.Begin();

        var context = await _contextBuilder.BuildAsync(
            profile,
            ctx =>
            {
                ctx.UserMessage = prompt;
                ctx.ConversationHistory = history;
            },
            cancellationToken);

        invocationScope.Context.CompletionContext = context.CompletionContext;
        invocationScope.Context.DataSourceId = context.CompletionContext.DataSourceId;

        var orchestrator = _orchestratorResolver.Resolve(profile.OrchestratorName);
        var answer = new StringBuilder();

        await foreach (var update in orchestrator.ExecuteStreamingAsync(context, cancellationToken))
        {
            if (string.IsNullOrEmpty(update.Text))
            {
                continue;
            }

            answer.Append(update.Text);
            await onToken(update.Text);
        }

        return answer.ToString();
    }
}

IOrchestratorResolver.Resolve(null) returns the default orchestrator. Tools registered with RequireApproval() are left out of this run, because nothing here can answer an approval; only AG-UI chat runs (which set AICompletionContextKeys.ToolApprovalSupported) offer them. The built-in AIChatResponseHandler follows the same steps, storing the chat session or interaction on AIInvocationScope.Current before the build.

Choose the Surface

| Need | Use |

|---|---|

| One prompt, one answer, no profile | IAICompletionService.CompleteAsync |

| Streamed tokens without tools or RAG | IAICompletionService.CompleteStreamingAsync |

| A profile's tools, agents, RAG and MCP | IOrchestrator.ExecuteStreamingAsync |

| Stored sessions, hubs, chat UI | crestapps-core-chat-interactions |

| Speech-to-speech conversations | crestapps-core-realtime-voice |

| Let the chat run tools the user's browser page exposes | crestapps-core-webmcp |

| Show tool calls, ask before a tool runs, share page state (AG-UI) | crestapps-core-ag-ui |

Provider Behavior Worth Knowing

Upgrading from 1.x

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.