惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Threatpost
The Hacker News
The Hacker News
AWS News Blog
AWS News Blog
Spread Privacy
Spread Privacy
T
Tenable Blog
C
CERT Recently Published Vulnerability Notes
Cisco Talos Blog
Cisco Talos Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
S
Securelist
P
Privacy & Cybersecurity Law Blog
Know Your Adversary
Know Your Adversary
T
The Exploit Database - CXSecurity.com
Latest news
Latest news
D
Darknet – Hacking Tools, Hacker News & Cyber Security
I
Intezer
F
Fortinet All Blogs
Engineering at Meta
Engineering at Meta
Simon Willison's Weblog
Simon Willison's Weblog
The Register - Security
The Register - Security
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
L
Lohrmann on Cybersecurity
C
Cyber Attacks, Cyber Crime and Cyber Security
Microsoft Azure Blog
Microsoft Azure Blog
P
Proofpoint News Feed
H
Help Net Security
T
Threat Research - Cisco Blogs
D
DataBreaches.Net
S
Schneier on Security
Cyberwarzone
Cyberwarzone
Google DeepMind News
Google DeepMind News
P
Privacy International News Feed
S
Secure Thoughts
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Recorded Future
Recorded Future
C
Cybersecurity and Infrastructure Security Agency CISA
MyScale Blog
MyScale Blog
M
MIT News - Artificial intelligence
Stack Overflow Blog
Stack Overflow Blog
IT之家
IT之家
人人都是产品经理
人人都是产品经理
NISL@THU
NISL@THU
博客园 - Franky
T
Tor Project blog
G
GRAHAM CLULEY
博客园 - 【当耐特】
Jina AI
Jina AI
Security Archives - TechRepublic
Security Archives - TechRepublic
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
A
About on SuperTechFans
Hacker News - Newest:
Hacker News - Newest: "LLM"

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Dynamic Agent Context with AIContextProvider
Lukas Walter · 2026-05-06 · via DEV Community

This is Part 6 of my series on the Microsoft Agent Framework. You can read the original post over on lukaswalter.dev.

When static prompts are no longer enough

Most agents are created with fixed system prompts and tools. But as we need more intelligent systems, we sometimes need to adapt them to the situation, user, or time.

The framework offers AIContextProviders for this purpose.

These provide context to AI agents and can be chained together to connect multiple sources.

Providers are executed in the order they are registered, allowing you to layer multiple context modifications in a predictable way. You can configure the sequence in your agent's setup, ensuring that context from earlier providers is available to those that run later in the chain. This lets you hook into the pipeline before and after the LLM call, helping avoid unexpected behavior by keeping the flow transparent.

The Architecture of Context Providers

To create a custom provider, we inherit from the AIContextProvider class. The Microsoft Agents framework handles all the complex routing and pipeline management behind the scenes, leaving us with just two key methods to override for our custom logic:

  • ProvideAIContextAsync (Pre-Call): This method is called just before the request is sent. Here we have full access to the current session, the previous instructions, and the pending message.
  • StoreAIContextAsync (Post-Call): This method fires after the LLM has generated the response, but before it is returned to the user. Here, we can analyze the final response or any errors that might have occurred.

Examples

Memory

Let's say we are building a barista agent for the coffee junkies among us.

We want the AI to remember the user's specific brewing habits and gear.
For example, when the user says, "I just bought a V60 pour-over" or "I really don't like acidic coffees."

ProvideAIContextAsync fetches user facts from the database and appends them as context to the instructions for the call. E.g., "User brews with a V60, prefers a 1:15 ratio, and loves dark, chocolatey roasts."

StoreAIContextAsync passes the user request to a cheap extractor agent, which finds new facts to save for future use, enabling the barista to learn over time.

public class BaristaMemoryProvider : AIContextProvider
{
    private const string UserIdStateKey = "UserId";
    private readonly ICoffeeDatabase _db;
    private readonly IExtractorAgent _extractor;
    public BaristaMemoryProvider(ICoffeeDatabase db, IExtractorAgent extractor)
    {
        _db = db;
        _extractor = extractor;
    }
    protected override async ValueTask<AIContext> ProvideAIContextAsync(
        AIContextProvider.InvokingContext context,
        CancellationToken cancellationToken = default)
    {
        string userId = GetUserId(context.Session);
        var userPrefs = await _db.GetPreferencesAsync(userId, cancellationToken);
        if (userPrefs is null)
        {
            return new AIContext();
        }
        return new AIContext
        {
            Instructions =
                $"User Coffee Profile: Brewer: {userPrefs.Brewer}, " +
                $"Ratio: {userPrefs.Ratio}, Roast: {userPrefs.RoastType}."
        };
    }
    protected override async ValueTask StoreAIContextAsync(
        AIContextProvider.InvokedContext context,
        CancellationToken cancellationToken = default)
    {
        var lastUserMessage = context.RequestMessages
            .LastOrDefault(m => m.Role == ChatRole.User)?
            .Text;
        if (string.IsNullOrWhiteSpace(lastUserMessage))
        {
            return;
        }
        var extractedFact = await _extractor.ExtractNewFactsAsync(lastUserMessage, cancellationToken);
        if (extractedFact is not null)
        {
            string userId = GetUserId(context.Session);
            await _db.SaveNewPreferenceAsync(userId, extractedFact, cancellationToken);
        }
    }
    private static string GetUserId(AgentSession? session) =>
        session?.StateBag.TryGetValue<string>(UserIdStateKey, out var userId) == true
            ? userId
            : "anonymous";
}

Enter fullscreen mode Exit fullscreen mode

Optimize Tokens

Let's now imagine a virtual Guitar Tech agent. This agent is equipped with many tools (ScaleGenerator, TabFetcher, AmpEQDialer, PedalBoardRouter, Metronome, etc.).

Now we need to send the schema for all tools with every request to the LLM.
Even if the user just says, "Hey man". This inevitably wastes hundreds or thousands of tokens per call.

This time, we use ProvideAIContextAsync to quickly pass the incoming user message to a fast, efficient agent whose primary task is to evaluate user intent. (Is this request about music theory, finding tabs, or dialing in a tone?)

If the user asks, "How do I get a dirty Hendrix tone on my Strat?", the provider injects only the AmpEQDialer and PedalBoardRouter tools into the context just before the main LLM call.

The main agent receives a tailored and lean toolset. This approach saves input tokens and reduces the risk of the AI making unnecessary tool calls.

public class GuitarTechToolProvider : AIContextProvider
{
    private readonly IRoadieAgent _roadieRouter;
    private readonly IToolRegistry _tools;
    public GuitarTechToolProvider(IRoadieAgent roadieRouter, IToolRegistry tools)
    {
        _roadieRouter = roadieRouter;
        _tools = tools;
    }
    protected override async ValueTask<AIContext> ProvideAIContextAsync(
        AIContextProvider.InvokingContext context,
        CancellationToken cancellationToken = default)
    {
        var lastMsg = context.RequestMessages
            .LastOrDefault(m => m.Role == ChatRole.User)?
            .Text;
        var intent = await _roadieRouter.DetermineIntentAsync(lastMsg, cancellationToken);
        var selectedTools = new List<AITool>();
        switch (intent)
        {
            case Intent.ToneAndGear:
                selectedTools.Add(_tools.GetTool("AmpEQDialer"));
                selectedTools.Add(_tools.GetTool("PedalBoardRouter"));
                break;
            case Intent.MusicTheory:
                selectedTools.Add(_tools.GetTool("ScaleGenerator"));
                break;
        }
        return new AIContext
        {
            Tools = selectedTools
        };
    }
}

Enter fullscreen mode Exit fullscreen mode

Guardrails & Validation

For this example, we will use an agent that helps us build Lego models. Let's ask it for a creative way to connect two Lego plates at a strange 45-degree angle. LLMs are eager to please and sometimes ignore existing rules. And though the agent might confidently suggest using superglue. Obviously, we need a strict safety net to avoid ruining our Lego set because of a wrong answer.

Via ProvideAIContextAsync, we inject a strict boundary condition right alongside the user's prompt: "Constraint: You are a purist Lego Master Builder. Only reference legal, official connection techniques. Do not suggest modifying bricks, cutting, or using adhesives."

But even with strict boundaries, the agent could give us the wrong answer.

StoreAIContextAsync grabs the generated response before it is returned to the user.
Again, we run the response through a fast, lightweight agent that looks for out-of-bounds keywords such as "glue", "stress", and "cut".

If the validator detects an illegal technique, we can log the error immediately, strip the offending paragraph from the answer, or throw an exception to trigger a silent, automatic retry.

public class LegoGuardrailProvider : AIContextProvider
{
    private readonly IValidatorAgent _validator;
    public LegoGuardrailProvider(IValidatorAgent validator)
    {
        _validator = validator;
    }
    protected override ValueTask<AIContext> ProvideAIContextAsync(
        AIContextProvider.InvokingContext context,
        CancellationToken cancellationToken = default)
    {
        return ValueTask.FromResult(new AIContext
        {
            Instructions = "Constraint: Only reference legal Lego connection techniques."
        });
    }
    protected override async ValueTask StoreAIContextAsync(
        AIContextProvider.InvokedContext context,
        CancellationToken cancellationToken = default)
    {
        var lastAssistantMsg = context.ResponseMessages?
            .LastOrDefault()?
            .Text;
        var validation = await _validator.CheckForIllegalTechniquesAsync(
            lastAssistantMsg,
            cancellationToken);
        if (!validation.IsSafe)
        {
            throw new AIValidationException($"Safety violation: {validation.Reason}");
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Alternatives

In addition to the AIContextProvider, the framework also offers the MessageAIContextProvider. Instead of adjusting system instructions or tools in the background, this provider injects actual chat messages into the conversation.

You can register the MessageAIContextProvider as middleware. This is extremely helpful when working with agents we haven't created ourselves and whose parameters we cannot directly configure (such as remote agents connected via the A2A (Agent-to-Agent) protocol). By using it as middleware, we can still dynamically inject additional messages into them without needing access to their internal configuration.

Conclusion

Context Providers are really helpful in many situations. Whether you need dynamic on-the-fly prompts, an intelligent background memory, or massive token optimization through tool injection.

We now know how to tame our chat histories, dynamically inject memory, and optimize our token budgets. But what happens when words are no longer enough, and our AI needs to interact with the real world?

In the next part of this series, we will explore Tools and Dependency Injection, and learn how to teach your AI to execute actual actions!

Further Reading