Crestapps core context builders

From CrestApps/CrestApps.AgentSkills · View interactive version

Crestapps core context builders is an AI agent skill from the GitHub repository CrestApps/CrestApps.AgentSkills. Skill for enriching CrestApps.Core 2.0 completion and orchestration contexts with handler pipelines. Covers IAICompletionContextBuilder and IAICompletionContextBuilderHandler producing AICompletionContext, IOrchestrationContextBuilder and IOrchestrationContextBuilderHandler producing OrchestrationCo

How to use this skill

Skill file

CrestApps.Core Context Builders

Two handler pipelines prepare every AI request:

| Level | Builder | Handler | Produces |

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

| Completion | IAICompletionContextBuilder.BuildAsync(resource, configure, cancellationToken) | IAICompletionContextBuilderHandler | AICompletionContext (deployments, system message, tools, agents, model parameters, data source) |

| Orchestration | IOrchestrationContextBuilder.BuildAsync(resource, configure, cancellationToken) | IOrchestrationContextBuilderHandler | OrchestrationContext (user message, history, documents, SystemMessageBuilder, completion context) |

Guidelines

Built-in Handlers

| Completion handler | Adds |

|---|---|

| AIProfileCompletionContextBuilderHandler | Profile system message, sampling, deployments, prompt templates, tools, agents, chat and utility model parameters |

| ChatInteractionCompletionContextBuilderHandler | The same for a ChatInteraction |

| AIPersonaCompletionContextBuilderHandler | In BuiltAsync, prepends the linked persona block and stores it under AICompletionContextKeys.Persona (when personas are enabled) |

| AIToolInstanceCompletionContextBuilderHandler | ToolInstanceNames from AIToolInstanceMetadata (when tool instances are enabled) |

| DataSourceAICompletionContextBuilderHandler | The selected data source id |

| McpAICompletionContextBuilderHandler | MCP connection ids (when MCP is enabled) |

Orchestration handlers include CompletionContextOrchestrationHandler (builds the completion context and seeds SystemMessageBuilder), PreemptiveRagOrchestrationHandler, RealtimeRagGuidanceHandler, AIToolExecutionContextOrchestrationHandler, SecurityPromptOrchestrationHandler, plus data source, memory, document, extracted-data, Claude and Copilot handlers from their features. After all orchestration handlers run, the builder flushes SystemMessageBuilder back to CompletionContext.SystemMessage.

Completion Context Handler

using CrestApps.Core.AI.Completions;
using CrestApps.Core.AI.Models;

public sealed class TenantCompletionContextHandler : IAICompletionContextBuilderHandler
{
    private readonly ITenantAccessor _tenantAccessor;

    public TenantCompletionContextHandler(ITenantAccessor tenantAccessor)
    {
        _tenantAccessor = tenantAccessor;
    }

    public Task BuildingAsync(AICompletionContextBuildingContext context)
    {
        return Task.CompletedTask;
    }

    public Task BuiltAsync(AICompletionContextBuiltContext context)
    {
        if (context.Resource is not AIProfile profile || profile.Type == AIProfileType.Agent)
        {
            return Task.CompletedTask;
        }

        var tenant = _tenantAccessor.Current;

        context.Context.SystemMessage = string.Join(
            "\n\n",
            new[] { context.Context.SystemMessage, $"Only use data that belongs to tenant '{tenant.Name}'." }
                .Where(part => !string.IsNullOrWhiteSpace(part)));

        context.Context.AdditionalProperties["tenant-id"] = tenant.Id;

        return Task.CompletedTask;
    }
}
builder.Services.AddScoped<IAICompletionContextBuilderHandler, TenantCompletionContextHandler>();

ITenantAccessor stands for the host's own service. AICompletionContextBuildingContext and AICompletionContextBuiltContext both expose Resource and the mutable Context. The profile handler sets the system message in BuildingAsync, so appending in BuiltAsync keeps your text after it. The persona handler also works in BuiltAsync; register your handler after AddPersonas(...) so it runs first and the persona block still ends up at the top.

Orchestration Context Handler

using CrestApps.Core.AI.Orchestration;

public sealed class TenantOrchestrationContextHandler : IOrchestrationContextBuilderHandler
{
    public Task BuildingAsync(
        OrchestrationContextBuildingContext context,
        CancellationToken cancellationToken = default)
    {
        return Task.CompletedTask;
    }

    public Task BuiltAsync(
        OrchestrationContextBuiltContext context,
        CancellationToken cancellationToken = default)
    {
        context.OrchestrationContext.SystemMessageBuilder
            .AppendLine()
            .Append("Do not access data outside the active tenant.");

        return Task.CompletedTask;
    }
}
builder.Services.AddScoped<IOrchestrationContextBuilderHandler, TenantOrchestrationContextHandler>();

OrchestrationContextBuildingContext exposes Resource, GetResource<T>() and Context; OrchestrationContextBuiltContext exposes Resource and OrchestrationContext.

Reading the Current Chat

During a chat turn, the response handler stores the chat interaction or session in AIInvocationScope.Current (ChatInteraction, ChatSession) before it builds the orchestration context, and the completion context and data source after it. Handlers and IAIProfileProviders can therefore read the active chat during the build. Do not rely on IHttpContextAccessor inside SignalR hubs; use IUserAccessor.User for the caller.

Model Parameters on the Context

The profile and chat interaction handlers copy AIDeploymentParametersMetadata onto AICompletionContext.ModelParameters (chat) and UtilityModelParameters (utility). A handler can adjust them or mark a background call with IsUtilityCompletion = true:

public Task BuiltAsync(AICompletionContextBuiltContext context)
{
    if (context.Resource is AIProfile { Name: "nightly-summary" })
    {
        context.Context.IsUtilityCompletion = true;
        context.Context.UtilityModelParameters["reasoningEffort"] = "Low";
    }

    return Task.CompletedTask;
}

Build Explicitly

var completionContext = await completionContextBuilder.BuildAsync(
    profile,
    context => context.DisableTools = true,
    cancellationToken);

var orchestrationContext = await orchestrationContextBuilder.BuildAsync(
    profile,
    context => context.UserMessage = prompt,
    cancellationToken);

Use the delegate for a one-request adjustment and a handler for reusable policy.

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.