Dev.to AI 🤖 Ai 👁 0 📖 4 min read

Keeping Agent Skills out of your chat history

In Microsoft Agent Framework (.NET), AgentSkillsProvider loads skills via load_skill and read_skill_resource as standard tool results. ChatHistoryProvider persists those results like any other message, meaning loaded ski

In Microsoft Agent Framework (.NET), AgentSkillsProvider loads skills via load_skill and read_skill_resource as standard tool results. ChatHistoryProvider persists those results like any other message, meaning loaded skills get resent on every subsequent turn.

Load two 5 KB skills on turn 2 of a 30-turn chat, and you resend 10 KB across 28 extra turns while crowding the active conversation. Since Agent Framework has no built-in way to expire skill outputs, you have two practical fixes: isolate skills in a subagent or truncate old skill outputs before each model call.

Approach How it works Use it when…
Baseline Loads skills directly into main chat history Prototyping, or skills are tiny and rarely loaded
A: Subagent Runs skills in a stateless worker agent that returns JSON Skills fetch or compute facts (search, pricing, lookups)
B: Truncate Replaces prior turns' skill outputs with a one-line stub Skills shape the conversation (tone, policy, user interviews)

Baseline: skills on the agent

All code below comes from the shopping assistant sample, which exposes catalog-search and pricing skills over MCP and maps three agents to AG-UI endpoints (/chat, /chat/worker, and /chat/ephemeral). Because AG-UI clients resend full history on every request while DevUI stores history server-side, any fix has to operate on outbound messages rather than a server-side ChatHistoryProvider.

In the baseline /chat setup, attaching AgentSkillsProvider directly to the main agent leaves every loaded skill and reference file in the conversation history:

AIAgent agent = chatClient.AsAIAgent(new ChatClientAgentOptions
{
    Name = "shopping_baseline",
    ChatOptions = new() { Instructions = "You are a helpful shopping assistant.", Tools = [httpTool] },
    AIContextProviders = [skillsProvider],
});

After one turn, the history already holds ~2 KB of skill payloads that get resent on every later turn:

user       laptop under $1000
assistant  -> load_skill(skillName=catalog-search)
tool       <- "---\nname: catalog-search\n...# Catalog search\n...## Workflow ..."        (~1.3 KB)
assistant  -> read_skill_resource(catalog-search, references/search-behavior.md)
tool       <- "# Search behavior\n- The query is lowercased ..."                   (~0.8 KB)
assistant  -> http_request(GET /catalog?q=laptop&maxPrice=1000)
tool       <- HTTP 200 [{"id":"p_laptop_dell","name":"Dell XPS 13","price":999,...}]
assistant  Dell XPS 13, $999 list price (p_laptop_dell)

Approach A: run skills in a subagent

Move AgentSkillsProvider onto a worker agent and expose it to the main agent via worker.AsAIFunction(). Without a session, each worker invocation runs in a fresh session and discards all loaded skills and intermediate API payloads when it finishes.

AIAgent worker = chatClient.AsAIAgent(new ChatClientAgentOptions
{
    Name = "skill_worker",
    Description = "Searches the catalog and looks up prices. Returns JSON facts. Pass a complete, self-contained request.",
    ChatOptions = new()
    {
        Instructions = "You work for another assistant, not the user. Use your skills, then return the facts as JSON.",
        Tools = [httpTool],
        ResponseFormat = ChatResponseFormat.ForJsonSchema<WorkerResult>(jsonOptions),
    },
    AIContextProviders = [skillsProvider],
});

AIAgent main = chatClient.AsAIAgent(new ChatClientAgentOptions
{
    Name = "shopping_subagent",
    ChatOptions = new()
    {
        Instructions = "Call skill_worker for product data, with every id and preference it needs. " +
                       "Write the answer to the user yourself from its JSON.",
        Tools = [worker.AsAIFunction()],
    },
});

Have the worker return structured JSON facts, not prose, so the main agent retains product IDs for follow-ups and knows whether a lookup succeeded, broadened, or failed:

internal sealed record WorkerResult(
    IReadOnlyList<WorkerProduct> Products,   // id, name, listPrice, discountPct, promo, finalPrice
    WorkerOutcome Outcome,                   // found | no_match | broadened | error
    string? Error);

Main history after one turn:

user       laptop under $1000
assistant  -> skill_worker(query="Find laptops priced at or below 1000. Return ids and prices.")
tool       <- {"products":[{"id":"p_laptop_dell","name":"Dell XPS 13","listPrice":999,...}],"outcome":"found","error":null}
assistant  Dell XPS 13, $999 list price

Approach B: truncate old skill content

Keep skills on the main agent and wrap IChatClient with a decorator that replaces load_skill and read_skill_resource results from earlier turns (everything before the last user message) with a one-line stub, while leaving the current turn's tool loop untouched.

internal sealed class TruncateSkillContentChatClient(IChatClient inner) : DelegatingChatClient(inner)
{
    public override Task<ChatResponse> GetResponseAsync(
        IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken ct = default) =>
        base.GetResponseAsync(StubEarlierSkillContent(messages), options, ct);

    // GetStreamingResponseAsync: the same.
    // Find the last user message, collect earlier load_skill / read_skill_resource call IDs,
    // and replace matching FunctionResultContent payloads with:
    // "[Skill 'pricing' was loaded in an earlier turn. Call load_skill again if you need it.]"
}

Keep the tool call and result paired—only replace the result text, or model providers will reject the orphaned call. Register the decorator below the function-invoking client so it runs on every hop inside a tool loop:

IChatClient client = chatClient.AsBuilder()
    .Use(inner => new TruncateSkillContentChatClient(inner))
    .Build();

AIAgent agent = client.AsAIAgent(new ChatClientAgentOptions
{
    Name = "shopping_ephemeral",
    ChatOptions = new() { Instructions = "You are a helpful shopping assistant.", Tools = [httpTool] },
    AIContextProviders = [skillsProvider],
});

Rules of thumb

  1. Default to a subagent for search, pricing, and lookup skills; return typed JSON. Subagents also isolate bulky raw API responses from the main history and keep the conversation prefix append-only for prompt caching.
  2. Use truncation for policy, tone, or multi-turn interview skills that must stay active while replying—knowing it only shrinks skill payloads (not API responses) and mutates the prompt cache prefix when stubbing prior turns.
  3. Combine both: route data skills to a worker and keep conversational skills on the main agent.
  4. Move always-on skills into system instructions so they load once and cache cleanly.
  5. Keep SKILL.md lean and push details into resource files loaded only on demand.

Please feel free to reach out on twitter @roamingcode

📰 Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.