ML.Agentic
Architectural Primitives & Reasoning
21 zero-dependency building blocks, MCP, and A2A protocols for multi-agent coordination, deterministic planning, and graph-grounded verification.
ML.Agentic and ML.Reasoning provide a complete, dependency-free toolkit for constructing high-reliability agent systems. Built in modern C# (.NET 10) with SIMD acceleration and optional Intel Level Zero GPU compute offload, every primitive is designed to be composable, testable in isolation, and resilient against hallucination loops, unbounded token spend, and concurrency deadlock.
22 Agentic Primitives Catalog
Filter by architecture role, search by keyword, or inspect type-safe C# signatures and execution dynamics.
Hierarchical Planner
Recursive goal decomposition into multi-tier task trees with deterministic preconditions.
Breaks complex multi-step user prompts into hierarchical directed acyclic task graphs (HTNs). Evaluates preconditions, branch prerequisites, and dynamic subtask dispatch with cycle detection.
var planner = new HierarchicalPlanner<Goal, Task>();
var plan = await planner.DecomposeAsync(userGoal, cancellationToken);
foreach (var stage in plan.ExecutionStages) {
await stage.ExecuteWithGuardsAsync();
} MCTS Exploration
Upper Confidence Bound (UCT) tree search over agent action spaces.
Evaluates combinatorial action paths under stochastic reward functions using tree-search exploration with customizable rollout heuristics and exploration parameter c.
var mcts = new MonteCarloTreeSearch<AgentState, AgentAction>(
explorationWeight: 1.414f,
maxSimulations: 500
);
var bestAction = await mcts.SelectBestActionAsync(currentState); Priority Scheduler
Work-stealing priority queue with preemptive resource-constrained scheduling.
Schedules concurrent agent execution pipelines across multi-core compute threads, enforcing latency deadlines, token-budget quotas, and hardware affinity scoring.
var scheduler = new PriorityAgentScheduler<AgentTask>(maxConcurrency: 16);
scheduler.Enqueue(task, priority: TaskPriority.Critical);
await scheduler.DrainAsync(); Goal-Progress Monitor
Trajectory velocity tracking, dead-end detection, and automated backtracking.
Monitors progress metrics toward intermediate objectives. Triggers automated rollback or replanning when agent actions reach stagnating convergence or infinite oscillation loops.
var monitor = new GoalProgressMonitor<TargetGoal, WorldState>(stallThreshold: 3);
monitor.RecordStep(stateDelta);
if (monitor.IsStalled()) {
await planner.TriggerReplanningAsync(monitor.GetStallContext());
} Reflection Loop
Iterative generate-critique-refine feedback loop with convergence guarantees.
Executes multi-pass self-critique cycles on intermediate agent outputs, scoring draft answers against strict verification criteria until reaching target confidence.
var reflection = new SelfReflectionLoop<CodeDraft, LintResult>(maxPasses: 3);
var finalized = await reflection.RefineAsync(initialDraft, async draft => {
return await verifier.EvaluateAsync(draft);
}); Chain-of-Verification
Fact extraction, verification query generation, and hallucination pruning.
Extracts atomic factual claims from generated responses, generates targeted retrieval verification queries, and prunes or revises ungrounded statements.
var coVe = new ChainOfVerificationEngine<FactClaim>(graphStore);
var verifiedAnswer = await coVe.VerifyAndRepairAsync(unverifiedResponse); Multi-Persona Debate
Adversarial dialectic synthesis across divergent perspective agents.
Orchestrates multi-agent adversarial debate rounds with distinct personas (e.g., Optimist, Skeptic, Domain Specialist) and a neutral synthesizing judge.
var debate = new MultiPersonaDebate<ArchitectureProposal, ConsensusVerdict>(rounds: 3);
debate.AddParticipant(new SecurityArchitectAgent());
debate.AddParticipant(new PerformanceEngineerAgent());
var decision = await debate.ReachConsensusAsync(proposal); Program-Aided Reasoner
Symbolic code generation and deterministic sandboxed execution offload.
Offloads complex mathematical, statistical, or logic reasoning to generated, type-checked C# or Python execution blocks in an isolated runtime sandbox.
var par = new ProgramAidedReasoner<MathProblem, double>(sandboxEnvironment);
double result = await par.ExecuteSymbolicReasoningAsync(problem); Judge Evaluator
Multi-criteria scoring matrix with pairwise Elo ranking and confidence intervals.
Implements unbiased rubric scoring and Bradley-Terry pairwise comparisons across candidate outputs, producing calibrated confidence scores and explanations.
var judge = new AgentJudgeEvaluator<ModelOutput, QualityScore>(rubric);
var ranking = await judge.RankCandidatesAsync(candidatePool); Blackboard System
Shared working memory space with reactive pub-sub event notifications for specialist agents.
Thread-safe central knowledge workspace where specialist agents read hypotheses, post discoveries, and trigger reactive problem-solving handlers asynchronously.
var blackboard = new BlackboardSystem<KnowledgeEntry>();
blackboard.Subscribe("geometry.discovered", async entry => {
await physicsAgent.ProcessNewHypothesisAsync(entry);
});
blackboard.Post(new KnowledgeEntry("geometry.discovered", data)); Semantic Router
SIMD-accelerated embedding similarity routing with zero runtime dependencies.
Routes incoming agent requests to specialized worker agents using high-speed cosine distance over intent embeddings with sub-millisecond dispatch latency.
var router = new SemanticAgentRouter<Intent, AgentHandle>(embeddingModel);
router.RegisterRoute("sql.query", databaseAgent);
router.RegisterRoute("visual.render", graphicsAgent);
var target = await router.RouteAsync(incomingPrompt); Topology Manager
Dynamic communication network orchestration: Ring, Mesh, Star, or Hierarchical Tree.
Configures and mutates runtime communication topologies between agents. Supports automated clustering, sub-swarm formation, and dynamic bridge nodes.
var topology = new AgentTopologyManager(TopologyType.HierarchicalFederation);
topology.AddCluster("researchers", researcherPool);
topology.AddBridgeNode(coordinatorAgent); Fallback Chain
Circuit-breaker protected cascading agent fallback execution paths.
Provides cascading failover handling across multiple model providers, local offline fallbacks, and rule-based deterministic safety nets with exponential backoff.
var fallback = new ResilientFallbackChain<Query, Answer>()
.AddPrimary(fastModelAgent)
.AddFallback(deepReasoningAgent)
.AddFinal(deterministicHeuristicEngine);
var res = await fallback.ExecuteAsync(query); Tool Registry
Type-safe JSON Schema tool introspection, permission validation, and execution hooks.
Catalog for registering, searching, and invoking system tools. Enforces strict input validation, security sandbox policies, and telemetry logging on all invocations.
var registry = new DynamicToolRegistry();
registry.Register<FileSearchTool>(PermissionLevel.ReadOnly);
var tool = registry.FindTool("file_search");
var output = await tool.InvokeAsync(args); Agent Cards Manifest
A2A discovery protocol with cryptographically signed capability manifests.
Self-describing agent capability metadata format enabling dynamic peer-to-peer agent discovery, SLA negotiation, and role delegation in distributed swarms.
var card = AgentCard.Create("optimizer-v1")
.WithCapability("swarm.pso")
.WithMaxTokens(8192)
.Sign(privateKey);
await network.BroadcastCardAsync(card); Role Handoff Engine
Zero-data-loss context transfer and state compaction between transitioning agents.
Serializes, compacts, and transfers execution state and conversational intent when delegating tasks from an exploratory agent to an execution agent.
var handoff = new RoleHandoffEngine<WorkflowContext>();
await handoff.TransferControlAsync(researchAgent, codeWriterAgent, contextSnapshot); Guardrail Pipeline
Bidirectional token-level safety filters, prompt injection guards, and PII masking.
Inspects inbound inputs and outbound model generations against configurable security policies, semantic bounds, and structural constraints with zero external network overhead.
var guardrail = new PolicyGuardrailPipeline()
.AddRule(new PromptInjectionDetector())
.AddRule(new SensitiveDataMasker())
.AddRule(new ToxicLanguageFilter());
var cleanPayload = await guardrail.SanitizeAsync(rawInput); Human-in-the-Loop Gate
Asynchronous policy-triggered user confirmation and permission escalation hooks.
Halts workflow execution when high-risk operations (file deletion, financial transactions, database mutations) occur, awaiting signed human confirmation in UI or chat.
var approvalGate = new HumanApprovalGate<FileAction>(RiskLevel.High);
var approval = await approvalGate.RequestApprovalAsync(actionPayload);
if (approval.IsGranted) {
await actionPayload.ExecuteAsync();
} Resource Budget Ledger
Token, GPU compute, and financial budget caps with strict enforcement per agent session.
Tracks real-time resource utilization across model calls, memory storage, and hardware compute. Enforces strict session limits and graceful cost-effective fallbacks.
var ledger = new ResourceBudgetLedger(maxTokens: 50_000, maxCostUsd: 0.25m);
ledger.Debit(usedTokens: 1420);
if (ledger.IsExceeded()) {
throw new BudgetExceededException(ledger.GetUsageSummary());
} Episodic Memory Bank
Temporal memory store with recency weighting, importance scoring, and associative recall.
Stores historical agent-environment interactions with decay curves and semantic indexing, allowing agents to retrieve relevant past experience during novel scenarios.
var memory = new EpisodicMemoryBank<AgentEpisode>(vectorIndex);
memory.Store(new AgentEpisode(action, outcome, importance: 0.9f));
var relevantHistory = await memory.RecallAsync(currentSituation, topK: 5); Context Compactor
Information-dense context compression preserving key entities, decisions, and code blocks.
Condenses extensive conversation histories into compact structured summaries while preserving critical constraints, entity graphs, and decision traces to fit within narrow context windows.
var compactor = new HierarchicalContextCompactor(targetTokens: 2048);
var compressedHistory = await compactor.CompactAsync(lengthyConversation); Evolutionary Mutator
Genetic algorithm optimizer for agent instructions, system prompts, and tool descriptions.
Evolves and refines system prompts using mutation, crossover, and fitness evaluation against benchmark task suites to discover optimal prompt representations autonomously.
var mutator = new PromptEvolutionMutator<SystemPrompt>(populationSize: 20);
var optimalPrompt = await mutator.EvolveAsync(initialPrompt, evalSuite, generations: 10); 5 ML.Reasoning Graph Algorithms
Algorithms executing against any graph implementation conforming to IKnowledgeGraph, with optional Level Zero GPU acceleration.
1. Multi-Hop Causal Path Reasoning
Discovers directed causal inference chains across property graphs with confidence decay calculations.
CausalPathReasoner.FindInferenceChains(IKnowledgeGraph graph, NodeId source, NodeId target, float minConfidence) 2. Grounding Verifier
Cross-checks agent claims against verified subgraphs, identifying and isolating unsupported assertions.
GroundingVerifier.ValidateClaims(IKnowledgeGraph graph, IEnumerable<Claim> claims, out ValidationReport report) 3. TAPE Rollout Planning
Trajectory-Aware Predictive Execution simulating branching action futures before committing execution steps.
TapeRolloutEngine.SimulateTrajectories(WorldModel model, AgentPlan plan, int horizonSteps) 4. Belief-Desire-Intention (BDI) Engine
Maintains formal agent world state, intention sets, goal hierarchies, and dynamic execution plans.
BdiEngine.UpdateBeliefsAndReplan(WorldDelta delta, GoalHierarchy goals, IntentionStack intentions) 5. Cognitive-Bias Detection & Debiasing
Detects confirmation bias, anchoring heuristics, and availability bias in agent chains, injecting counterfactual tests.
DebiasingEngine.AuditAndMitigate(ReasoningTrace trace, BiasCatalog catalog) Zero Overhead. Zero External Calls.
Traditional agent frameworks bundle dozens of unverified Python dependencies, synchronous network locks, and uncontrolled background polling. ML.Agentic takes the opposite approach:
- Standalone & Open Core: Shipped as a single, clean .NET 10 assembly with zero third-party packages.
- Deterministic Testing: Every primitive accepts explicit time, pseudo-random seeds, and cancellation tokens for 100% reproducible tests.
- Hardware Offload: Semantic routing and GraphRAG verification hook directly into LevelZero.NET for sub-millisecond local GPU execution.
- Enterprise Guardrails: Built-in token budget ledgers and human-approval gates ensure strict regulatory and operational safety.
Complete Release Bundle
The v1.0.0 release includes compiled .NET 10 binaries, signed NuGet packages, XML documentation, unit tests with >95% code coverage, and sample projects.