FonsecaFramework.Ai 2026.11.9.1

dotnet add package FonsecaFramework.Ai --version 2026.11.9.1
                    
NuGet\Install-Package FonsecaFramework.Ai -Version 2026.11.9.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="FonsecaFramework.Ai" Version="2026.11.9.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="FonsecaFramework.Ai" Version="2026.11.9.1" />
                    
Directory.Packages.props
<PackageReference Include="FonsecaFramework.Ai" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add FonsecaFramework.Ai --version 2026.11.9.1
                    
#r "nuget: FonsecaFramework.Ai, 2026.11.9.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package FonsecaFramework.Ai@2026.11.9.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=FonsecaFramework.Ai&version=2026.11.9.1
                    
Install as a Cake Addin
#tool nuget:?package=FonsecaFramework.Ai&version=2026.11.9.1
                    
Install as a Cake Tool

FonsecaFramework.Ai

AI and machine learning utilities for .NET applications.

Overview

FonsecaFramework.Ai is a .NET 10 library that provides tools for building ML models with AutoML, performing sentiment/discourse analysis, implementing RAG (Retrieval‑Augmented Generation) vector stores, and integrating with LLM providers via the Microsoft.Extensions.AI abstraction. It wraps ML.NET and ONNX Runtime to offer a streamlined API for training, predicting, and exporting models.

Installation

dotnet add package FonsecaFramework.Ai

Features

Area Key Classes
AutoML Model Building AiModelBuilder<T> — build regression, classification, ranking, and recommendation models with ML.NET AutoML
Trained Model AiModel<T, TMetrics> — make predictions and export to ONNX format
Forecasting ForecastModelBuilder — walk-forward regression forecasts and baseline comparisons
RAG Vector Store RagVectorStore — chunk documents, build TF-IDF + discourse vectors, and retrieve context for LLM prompts
Agent Framework RAG Bridge RagVectorStore.CreateTextSearchProvider(...) — expose store retrieval through Microsoft.Agents.AI.TextSearchProvider
RAG Snapshots RagVectorStoreSnapshot — serialize/deserialize a vector store to avoid re-processing documents
Sentiment Analysis ISentimentAnalyzer — 10-element discourse vector interface
LexiconSentimentAnalyzer — fast, deterministic, lexicon-based analyzer (no external service required)
OllamaSentimentAnalyzer — LLM-powered analyzer via IChatClient with lexicon fallback
LLM Chat Client VLRChatClient — IChatClient implementation for OpenAI-compatible endpoints (e.g. Ollama) with streaming support
ACP Subagents IAgentOrchestrator — delegates planner-selected work to local Agent Client Protocol (ACP) subagents over stdio
Provider-aware routing AgentModelCandidate, IAgentChatClientResolver, and IAgentRoutingStrategy — select a provider/model per agent invocation

Examples

Build and Use a Regression Model

using FonsecaFramework.Ai;

var data = new List<HouseData>
{
    new() { Size = 1000, Price = 200_000 },
    new() { Size = 1500, Price = 300_000 },
    new() { Size = 2000, Price = 400_000 },
    // ... more training data
};

var builder = new AiModelBuilder<HouseData>(data, nameof(HouseData.Price));

var model = builder.BuildRegressionModel(
    MaxExperimentTimeInSeconds: 30);

float prediction = model.Predict(new HouseData { Size = 1750 });
Console.WriteLine($"Predicted price: {prediction:C}");

// Export to ONNX
await model.ConvertToOnnx("house-model.onnx");

AutoML prepares features and selects a pipeline using validation data. The builder then refits that pipeline on all supplied rows; this extra training can extend beyond the experiment time limit. model.ModelExperiment.BestRun.ValidationMetrics describes the selection run, not the refitted model. Evaluate the final model separately on data that was never supplied to the builder, especially for time-dependent or grouped data. Accuracy depends on the data and is not guaranteed.

Only include features that will be available when making predictions. If a data class also contains other targets or future information, exclude them before building: builder.IgnoredColumnNames.Add(nameof(HouseData.OtherTarget));. The label itself is automatically excluded. AutoML infers column roles; choose the appropriate optimization metric and allow more training time when needed. Ranking expects a GroupId column. The legacy AutoML recommendation experiment can fail to construct its matrix-factorization pipeline for user/item data; its underlying errors are reported when no model succeeds. The scalar Predict method returns Score, not a multiclass label or probability; use model.Model with an appropriately typed ML.NET prediction engine for other outputs.

For dynamic-length feature arrays, supply a fixed-size ML.NET schema for the current dataset. The same schema is used when scoring:

using Microsoft.ML.Data;

var schema = SchemaDefinition.Create(typeof(DataRow));
schema[nameof(DataRow.Features)].ColumnType = new VectorDataViewType(NumberDataViewType.Single, featureCount);
var builder = new AiModelBuilder<DataRow>(rows, nameof(DataRow.Label), schema);
var model = builder.BuildRegressionModel();
float[] scores = model.PredictBatch(inputs); // Same order as inputs

Forecast ordered observations

using FonsecaFramework.Ai.Forecasting;

var start = new DateTime(2026, 1, 1);
var rows = Enumerable.Range(0, 70).Select(i =>
{
    var date = start.AddDays(i);
    return new ForecastObservation(Value: (float)(date.DayOfWeek == DayOfWeek.Sunday ? 20 : 10),
        Features: [(float)date.DayOfWeek], Timestamp: date);
});

// Compute calendar features using only the history and information known in advance.
IReadOnlyList<float[]> FutureFeatures(IReadOnlyList<ForecastObservation> history, int horizon) =>
    Enumerable.Range(1, horizon).Select(i => new[]
    {
        (float)history[^1].Timestamp!.Value.AddDays(i).DayOfWeek
    }).ToArray();

var result = new ForecastModelBuilder(rows).BuildForecast(
    horizon: 7, validationFolds: 2, seasonalPeriod: 7, featureGenerator: FutureFeatures);
Console.WriteLine($"Held-out MAE: {result.ModelMetrics.MeanAbsoluteError}");
Console.WriteLine($"Seasonal baseline MAE: {result.SeasonalMetrics!.MeanAbsoluteError}");
float[] forecast = result.Forecast.ToArray();

Rows must already be chronological. Supply timestamps for all rows in strictly increasing order, or omit them for all rows. The helper uses FastForest on fixed-size numeric feature vectors; if every training target is identical, it predicts that constant. Validation uses consecutive, non-overlapping horizon-sized windows and refits the final model on all rows. Metrics are pooled across those held-out windows, not calculated on the refitted model; R² is null when undefined. Baseline forecasts and their held-out metrics are returned separately, so callers can compare them rather than assuming the model wins. Reserve additional data for an independent evaluation if using these metrics to choose settings.

By default, future features are extrapolated using the average historical change per row, matching VLRCreations' existing approach. This is an assumption, not a guarantee: it is unsuitable for many categorical, cyclical, or calendar features. Supply a generator for those features or known future values. The generator is called once per validation origin and once for the final forecast, and receives only the history at that origin; it must not capture held-out targets or other information unavailable at prediction time. Irregular timestamps are not resampled or extrapolated automatically. Existing VLRCreations endpoints continue to use their own implementation until explicitly integrated with this helper.

Build a Binary Classification Model

using FonsecaFramework.Ai;

var data = new List<EmailData>
{
    new() { Subject = "Free money!", Body = "Click here now", IsSpam = true },
    new() { Subject = "Meeting tomorrow", Body = "See you at 3pm", IsSpam = false },
    // ... more training data
};

var builder = new AiModelBuilder<EmailData>(data, nameof(EmailData.IsSpam));
var model = builder.BuildBinaryClassificationModel(MaxExperimentTimeInSeconds: 60);

float score = model.Predict(new EmailData { Subject = "You won!", Body = "Claim prize" });
Console.WriteLine($"Spam score: {score}");

RAG Vector Store — Build and Query

using FonsecaFramework.Ai;

// Build from a folder of .txt documents (optional sentiment analyzer can be supplied)
var store = await RagVectorStore.Build(
    sourceFolder: "./docs",
    chunkSize: 512,
    chunkOverlap: 128);

// Retrieve matching excerpts, including source and chunk references.
string context = await store.LookupAsync(
    query: "How do I configure the database?",
    topK: 3);

Console.WriteLine(context);
// Empty string means no matching evidence. BuildPromptWithContext also includes the question.

Knowledge-grounded Harness agents

Share a store with the root and every Fonseca-created specialist or profile agent:

var store = await RagVectorStore.Build(@"C:\knowledge", chunkSize: 800, chunkOverlap: 160);
var ai = new FonsecaAiBuilder()
    .UseChatClient(chatClient)
    .UseRag(store, rag =>
    {
        rag.TopK = 5;
        rag.MinSimilarity = 0.15;
        rag.MaxContextCharacters = 12_000;
    })
    .Build();

var response = await ai.RunAsync("What does our deployment policy require?");

The Harness automatically retrieves relevant context before invocation and exposes search_knowledge for focused follow-up searches. Grounding instructions ask agents to consult the knowledge base for domain facts, refine insufficient searches, cite sources, preserve citations across delegation, and acknowledge missing or conflicting evidence. Retrieved documents are explicitly treated as untrusted data, not commands. Tool selection and citation compliance remain model-dependent; they are not guarantees.

Direct construction supports new FonsecaAi(chatClient, vectorStore: store). For DI, set options.VectorStore = store in AddFonsecaAi (or register the store as a singleton); configure retrieval with options.Agent.Rag. Existing RagTopK and RagMinSimilarity properties map to the same settings. AutoRetrieve = false leaves only on-demand search; FonsecaAgentProfile.UseKnowledgeBase = false excludes a profile from shared knowledge. Already-constructed external AIAgent instances remain caller-owned: configure their providers before registering them. Use separate authorized stores for different tenants or access boundaries.

Retrieval remains local, lexical ML.NET retrieval, not semantic embeddings. Word unigram/bigram vectors use smoothed TF-IDF; sentiment only adjusts the ranking of topical matches and cannot make unrelated text into evidence. Results deduplicate identical text and include source/chunk references. MaxContextCharacters bounds excerpt text per search, not source metadata or total conversation tokens. Document changes atomically rebuild the vocabulary, making new terms searchable immediately at the cost of a full reindex. Search, updates, and snapshots are synchronized. New snapshots preserve IDF query weights; existing version-1 snapshots remain loadable. For synonyms absent from documents, use focused alternate search terms; semantic paraphrase retrieval would require a separately configured embedding model.

Simplified unified API

For new applications, register everything with one call. Harness orchestration is the default, and the Microsoft AIAgent remains available for drop-in Agent Framework integrations.

For direct use, the smallest setup creates the root agent, the standard curated subagents, and Fonseca's HarnessAgentOrchestrator from one chat client:

using FonsecaFramework.Ai;
using FonsecaFramework.Ai.LLM;

using var chatClient = new VLRChatClient("http://localhost:11434", model: "gpt-oss:20b");
var ai = new FonsecaAi(chatClient);

var response = await ai.RunAsync("Help me investigate this issue.");
Console.WriteLine(response.Text);

Add Microsoft AITool instances to the direct constructor when the root agent should be able to call application code:

using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.AI;

var lookupTool = AIFunctionFactory.Create(
    (string query, CancellationToken cancellationToken) =>
        Task.FromResult($"Results for: {query}"),
    "lookup_documents",
    "Looks up relevant application documents.");

var ai = new FonsecaAi(chatClient, new[] { lookupTool });
var response = await ai.RunAsync("Find the refund policy.");

AddSimpleAiAgent also supports the older Fonseca ITool contract through ToolRegistry; registered tools are converted to callable AITool functions automatically. The built-in SentimentTool and VectorStoreTool are registered when their corresponding services are available. With a knowledge store configured, agents receive the typed, bounded search_knowledge tool instead of the legacy raw-JSON vectorstore wrapper; the legacy tool remains available through ToolRegistry.

The default Harness configuration treats FonsecaAI as a coordinating lead agent: it is instructed to delegate substantive independent work, start parallel delegations where possible, monitor the background tasks, and synthesize their concise results. Delegation is still performed by the model through Harness's background_agents_* tools, so prompts that identify the required roles (for example, “have Explorer investigate and Reviewer verify”) are the most reliable. Override HarnessInstructions or BackgroundAgentInstructions when you need a different delegation policy.

Note: the background-agents roster is injected by Harness at the {background_agents} placeholder, so any custom BackgroundAgentInstructions should keep that placeholder (Fonseca appends it via FonsecaDelegationPolicy.EnsureAgentRoster when it is missing). Without the placeholder the router model never sees which subagent names are valid and may hallucinate agent names.

Thinking levels and OpenAI-compatible Ollama

Use Microsoft.Extensions.AI's typed reasoning settings without switching to a native Ollama client:

using FonsecaFramework.Ai;
using FonsecaFramework.Ai.LLM;
using Microsoft.Extensions.AI;

using var chatClient = new VLRChatClient("http://localhost:11434/v1/", model: "gpt-oss:20b");
var ai = new FonsecaAiBuilder()
    .UseChatClient(chatClient)
    .UseReasoning(ReasoningEffort.Medium)
    .Build();

// Overrides this invocation and its Fonseca-created delegates, not subsequent runs.
var response = await ai.RunAsync("Investigate this complex issue.",
    reasoning: new ReasoningOptions { Effort = ReasoningEffort.High });

Direct construction accepts new FonsecaAi(chatClient, reasoning: new() { Effort = ReasoningEffort.Medium }). For DI, set options.Agent.ReasoningEffort and, optionally, options.Agent.ReasoningOutput inside AddFonsecaAi. These defaults apply to the root, standard specialists, and agents compiled from profiles. Explicit ConfigureHarness reasoning takes precedence over builder defaults. Profiles can override individual fields with profile.ReasoningEffort and profile.ReasoningOutput.

RunAsync (string or ChatMessage), OrchestrateAsync, and StreamAsync accept a per-invocation reasoning: argument. Named subagent invocations accept SubagentExecutionOptions.Reasoning; existing ChatClientAgentRunOptions are cloned so token, tool, and other caller settings remain intact. Overrides merge field-by-field: invocation > profile > shared defaults > provider default. Nested delegations inherit their invocation's settings; an explicit child invocation can override them. Parallel invocations are isolated, and neither caller options nor session defaults are mutated. With no configuration, reasoning is left unset. Use ReasoningEffort.None to request disabled thinking rather than null, which means inherit. Undefined effort/output enum values throw ArgumentOutOfRangeException instead of silently becoming provider defaults, even when a higher-priority override would mask the invalid value.

VLRChatClient now uses the OpenAI SDK's Chat Completions adapter, preserving function calls/results, typed content, and streamed tool arguments. Both plain server URLs and URLs ending in /v1 are accepted. Endpoint whitespace and trailing slashes are normalized. For an exact reverse-proxy API base, use new VLRChatClient("https://proxy.example/Models/Inference/", model: "Org/Qwen3:8B", appendV1: false); requests then go to https://proxy.example/Models/Inference/chat/completions, without inserting /v1 or changing path casing. API bases must be absolute HTTP(S) URLs without a query or fragment. Streaming uses the same Chat Completions endpoint with stream: true, not a separate /stream endpoint.

Specify a constructor model or ChatOptions.ModelId for every request; routed candidates forward their actual selected model, including on fallback. Surrounding model-ID whitespace is trimmed consistently in clients, root options, profiles, catalogs, and routing, while case, namespace, and tags are preserved. Null means unspecified; explicit blank IDs are rejected rather than silently falling back. Caller ChatOptions and routing records are not mutated. When DI creates the default local client, set options.Agent.ModelId. Existing model-less VLR service callers must now supply a model.

Ollama's max_tokens field is used by default so output budgets are not silently ignored. When a RawRepresentationFactory supplies OpenAI ChatCompletionOptions, explicit raw limits take precedence over typed defaults: raw max_tokens > raw max_completion_tokens/MaxOutputTokenCount > ChatOptions.MaxOutputTokens. Raw-only limits are also adapted, even when no typed budget is provided; legacy mode sends only max_tokens. Limits must be positive integers, and malformed raw limits are surfaced rather than replaced with a default. As with the OpenAI SDK, a raw factory should return fresh options for each invocation. For hosted OpenAI models requiring max_completion_tokens, set useLegacyMaxTokens: false or supply your own OpenAI ChatClient.AsIChatClient(). A supplied HttpClient remains owned/disposed by VLRChatClient, as before. GetService<OpenAI.Chat.ChatClient>() exposes the underlying SDK tooling. Ollama's returned reasoning text is preserved as TextReasoningContent, separate from the final answer; the SDK's standard reasoning content is not duplicated.

Effort serializes to none, low, medium, high, or xhigh. These are requests, not guarantees: Ollama's OpenAI compatibility is a subset of OpenAI, and each model controls which names are supported. Inspect /api/show for model capabilities and defaults. Boolean-only thinking models may treat all enabled levels alike; unsupported named levels may resolve to the model default. ReasoningOutput is a provider-dependent preference, not a guarantee of summaries or full thinking text. Configure local context size via Ollama's model configuration; a Harness context budget does not resize Ollama's context window. Already-constructed external agents and custom/workflow/legacy orchestrators must honor Agent Framework run options or configure their own clients; Fonseca cannot rewrite an arbitrary external provider implementation.

Provider-aware model routing

Routing is deferred until each agent invocation, so parallel agents can use different providers without sharing provider state. Register candidates with AddModelCandidate, mark the primary candidate with IsMainChatModel, and optionally select a policy on FonsecaAgentProfile:

var builder = new FonsecaAiBuilder()
    .UseChatClient(defaultClient)
    .AddModelCandidate(new AgentModelCandidate(
        "openai", "gpt-5", "GPT-5", ["tools", "vision"],
        cancellationToken => ValueTask.FromResult<IChatClient>(openAiClient)) with { IsMainChatModel = true })
    .AddModelCandidate(new AgentModelCandidate(
        "ollama", "qwen", "Qwen", ["tools"],
        cancellationToken => ValueTask.FromResult<IChatClient>(ollamaClient)))
    .AddAgent(profile =>
    {
        profile.Name = "Explorer";
        profile.Instructions = "Investigate the request.";
        profile.RoutingPolicy = AgentRoutingPolicies.SuperRouting;
        profile.RequiredCapabilities.Add("tools");
    });

Use ExplicitModel, MainChatModel, or SuperRouting. Applications with dynamic provider discovery can implement IAgentChatClientResolver directly; credentials should be acquired only inside its client factory. The resolver is called for every run and stream, and AgentModelRoutedEvent exposes provider/model/policy diagnostics without exposing prompts or responses. Existing UseChatClient applications remain single-client applications.

A top-level orchestrator can invoke a registered agent by name without accessing the registry internals:

var result = await ai.RunSubagentAsync(
    "Explorer",
    new ChatMessage(ChatRole.User, "Investigate the issue."),
    new SubagentExecutionOptions
    {
        RoutingPolicy = AgentRoutingPolicies.SuperRouting,
        RequiredCapabilities = ["tools"],
        ParentRunId = copilotRunId
    },
    cancellationToken);

SubagentResult contains the agent, actual provider/model, status, summary, artifacts, warnings, run ID, and parent run ID. Unknown agents, recursive top-level invocations, unavailable models, capability mismatches, provider failures, and cancellation are surfaced as failures rather than successful error text.

The same setup is available through dependency injection:

using FonsecaFramework.Ai;
using Microsoft.Extensions.DependencyInjection;

var services = new ServiceCollection();
services.AddFonsecaAi(options =>
{
    options.Agent.SystemPrompt = "You are a concise, helpful assistant.";
    options.Agent.AgentName = "DocsAssistant";
    options.Agent.Tools.Add(lookupTool);
});

using var provider = services.BuildServiceProvider();
var ai = provider.GetRequiredService<IFonsecaAi>();
var response = await ai.RunAsync("How do I configure the database?");
Console.WriteLine(response.Text);

Use OrchestrateAsync when you need a complete orchestration result, or StreamAsync to send planning, root-agent, and subagent lifecycle events to a client or UI. For event-driven clients, subscribe directly to the hooks on IFonsecaAi:

ai.SubagentStarted += started =>
    Console.WriteLine($"{started.AgentName} started ({started.InvocationId})");
ai.SubagentResponseUpdated += update =>
    Console.Write(update.Text);
ai.SubagentCompleted += completed =>
    Console.WriteLine($"{completed.AgentName} completed in {completed.DurationMs} ms");
ai.SubagentFailed += failed =>
    Console.WriteLine($"{failed.AgentName} failed: {failed.Error}");

await foreach (var _ in ai.StreamAsync("Research the database configuration and review the answer."))
{
    // The subscribed hooks update the client as work progresses.
}

The same events can be consumed directly from the stream when the caller prefers an async enumerable:

await foreach (var update in ai.StreamAsync("Research the database configuration and review the answer."))
{
    switch (update)
    {
        case ToolCompletedEvent tool:
            Console.WriteLine($"Tool {tool.ToolName ?? "unknown"} completed; raw result is available in ResultContent.");
            break;
        case SubagentStartedEvent started:
            Console.WriteLine($"Started {started.AgentName} ({started.InvocationId})");
            break;
        case SubagentResponseUpdateEvent token:
            Console.Write(token.Text);
            break;
        case SubagentCompletedEvent completed:
            Console.WriteLine($"\nCompleted {completed.AgentName} in {completed.DurationMs} ms");
            break;
        case SubagentFailedEvent failed:
            Console.WriteLine($"\n{failed.AgentName} failed: {failed.Error}");
            break;
    }
}

The hooks fire during StreamAsync, and the typed subagent hooks also fire during OrchestrateAsync. Handlers run on the orchestration thread, so UI applications should marshal updates to their UI context. The default registry contains Fonseca's Planner, Explorer, Librarian, Designer, Worker, and Reviewer agents. Discover them through ai.Subagents or ai.GetSubagent("Explorer"). Create a session with ai.CreateSessionAsync() when conversation state should persist across requests.

Switch the built-in Harness mode for a session without manually locating AgentModeProvider:

var session = await ai.CreateSessionAsync();
var plan = await ai.RunAsync(
    "Plan the migration.",
    session,
    mode: FonsecaAgentMode.Plan);

var result = await ai.RunAsync(
    "Carry out the approved migration plan.",
    session,
    mode: FonsecaAgentMode.Execute);
Console.WriteLine($"Mode: {await ai.GetModeAsync(session)}");

SetModeAsync accepts FonsecaAgentMode.Plan or FonsecaAgentMode.Execute, which map to the exact "plan" and "execute" values expected by Harness. Mode state is stored in the session, so use the same session for planning and execution.

Add your own preconfigured agents alongside the curated agents through FonsecaAiOptions.Subagents:

services.AddFonsecaAi(options =>
{
    options.Subagents.Add(researchAgent);
    options.Subagents.Add(codeAgent);
});

For direct registry configuration, register the curated agents first and then add your own agents before constructing the facade:

using FonsecaFramework.Ai.Orchestration;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;

var registry = new SubagentRegistry();
registry.RegisterFonsecaAgents(chatClient);
registry.Register(researchAgent);
registry.Register(codeAgent);

var agent = chatClient.AsHarnessAgent(new HarnessAgentOptions
{
    Name = "DocsAssistant",
    Description = "A concise documentation assistant."
});
var ai = new FonsecaAi(agent, subagents: registry);

The registered agents are attached to Harness background delegation, while HarnessAgentOrchestrator publishes their start, token, completion, and failure events through StreamAsync. Tool results are emitted as ToolCompletedEvent; inspect ResultContent rather than treating media as assistant text. Set options.OrchestrationMode to Workflow with a WorkflowFactory, or LegacyAcp when an existing planner/ACP configuration must remain selected.

For full Harness configuration, pass HarnessAgentOptions directly. This keeps the facade and Fonseca orchestration while letting you configure tools, instructions, memory, context providers, and other Harness settings yourself:

var agentOptions = new HarnessAgentOptions
{
    Name = "DocsAssistant",
    Description = "A documentation assistant.",
    ChatOptions = new ChatOptions
    {
        Instructions = "You are concise and cite your sources.",
        Tools = new[] { lookupTool }
    },
    MaximumIterationsPerRequest = 8
};

var ai = new FonsecaAi(chatClient, agentOptions, subagents: registry);

SimpleAiAgent enables ContextWindowCompactionStrategy by default. It resolves the context window from SimpleAiAgentOptions.ModelId or ChatClientMetadata.DefaultModelId, uses a conservative fallback for unknown deployment IDs, and derives an output budget when one is not supplied. Set MaxContextWindowTokens for an explicit limit, or provide ContextWindowTokenResolver when your provider has a custom model catalog:

services.Configure<FonsecaAiOptions>(options =>
{
    options.Agent.ModelId = "my-gpt-deployment";
    options.Agent.MaxContextWindowTokens = 128_000;
    options.Agent.MaxOutputTokens = 16_384;
    options.Agent.ContextWindowTokenResolver = (client, modelId) =>
        modelId == "my-gpt-deployment" ? 200_000 : null;
});

When constructing HarnessAgentOptions directly, set MaxContextWindowTokens and provide your own ContextWindowCompactionStrategy; explicit Harness configuration remains authoritative.

Fluent Builder

For applications that want explicit composition without a long constructor, use FonsecaAiBuilder:

var ai = new FonsecaAiBuilder()
    .UseChatClient(chatClient)
    .AddTool(searchTool)
    .AddSubagent(researchAgent)
    .ConfigureSubagentSupervision(options =>
    {
        options.MaxConcurrency = 4;
        options.Timeout = TimeSpan.FromMinutes(2);
        options.RetryCount = 2;
    })
    .Build();

Agent profiles make model and tool selection independent for every subagent:

var ai = new FonsecaAiBuilder()
    .UseChatClient(chatClient)
    .AddTool("document_search", documentSearchTool)
    .AddTool("web_search", webSearchTool)
    .AddModel(new FonsecaModelDefinition
    {
        ModelId = "fast-model",
        DisplayName = "Fast model",
        MaxContextWindowTokens = 128_000
    })
    .AddModel(new FonsecaModelDefinition
    {
        ModelId = "reasoning-model",
        DisplayName = "Reasoning model",
        MaxContextWindowTokens = 200_000
    })
    .AddAgent(profile =>
    {
        profile.Name = "Explorer";
        profile.Description = "Investigates questions.";
        profile.Instructions = "Investigate the assigned question and return concise findings.";
        profile.ModelId = "fast-model";
        profile.ToolNames.Add("document_search");
        profile.ToolNames.Add("web_search");
    })
    .AddAgent(profile =>
    {
        profile.Name = "Reviewer";
        profile.Description = "Reviews proposed answers.";
        profile.Instructions = "Review the supplied work for correctness and missing risks.";
        profile.ModelId = "reasoning-model";
        profile.ToolNames.Add("document_search");
    })
    .Build();

FonsecaAgentProfile is persistable application data; FonsecaAgentFactory compiles it into a Harness AIAgent. FonsecaToolCatalog resolves each profile's ToolNames, while FonsecaModelCatalog supplies model metadata for adaptive context sizing. Use ChatClientResolver when model deployments require different IChatClient instances.

Runs emit correlated RunStartedEvent, RunCompletedEvent, and RunFailedEvent events. Use GetActiveSubagentStatuses() or GetSubagentStatus(invocationId) to populate a live client/UI status view. IAgentSessionStore and InMemoryAgentSessionStore provide a persistence boundary for hosts that need resumable session storage; replace the in-memory implementation with a durable store in production.

Agent Framework Agent

SimpleAiAgent is backed by Microsoft Agent Framework's HarnessAgent.

using FonsecaFramework.Ai;
using FonsecaFramework.Ai.Agents;
using Microsoft.Agents.AI;
using Microsoft.Extensions.DependencyInjection;

var services = new ServiceCollection();
services.AddSimpleAiAgent(options =>
{
    options.SystemPrompt = "You are a concise, helpful assistant.";
    options.AgentName = "DocsAssistant";
    options.MaximumIterationsPerRequest = 8;
});
services.AddFonsecaAiHarnessOrchestration();

using var provider = services.BuildServiceProvider();
AIAgent agent = provider.GetRequiredService<AIAgent>();
var response = await agent.RunAsync("How do I configure the database?", cancellationToken: default);
Console.WriteLine(response.Text);

For Microsoft Foundry deployments, provide an IChatClient backed by the selected Foundry model/client. The agent layer remains provider-neutral, matching Microsoft's AIAgent abstraction while allowing local OpenAI-compatible clients such as VLRChatClient.

To preserve Harness state across requests, create a session and place it on OrchestrationRequest.Session:

var session = await agent.CreateSessionAsync();
var result = await provider.GetRequiredService<IAgentOrchestrator>().ExecuteAsync(
    new OrchestrationRequest { Prompt = "Continue the research", Session = session });

AddFonsecaAiHarnessOrchestration() selects the Harness adapter for IAgentOrchestrator. Without that call, AddSimpleAiAgent() keeps the existing planner/ACP orchestrator.

Agent Framework Workflows

The Microsoft.Agents.AI.Workflows package is available for typed graph workflows with sequential, fan-out, fan-in, conditional edges, checkpointing, and streaming lifecycle events. Register a built workflow to use it through the existing orchestration contract:

using FonsecaFramework.Ai;
using FonsecaFramework.Ai.Orchestration;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Workflows;
using Microsoft.Extensions.DependencyInjection;

var services = new ServiceCollection();
services.AddSimpleAiAgent();
services.AddFonsecaAiWorkflowOrchestration(serviceProvider =>
{
    var agent = serviceProvider.GetRequiredService<AIAgent>();
    return new SequentialWorkflowBuilder(new[] { agent }).Build();
});

using var provider = services.BuildServiceProvider();
var orchestrator = provider.GetRequiredService<IAgentOrchestrator>();
var result = await orchestrator.ExecuteAsync(new OrchestrationRequest
{
    Prompt = "Research the goat gods and summarize the findings."
});
Console.WriteLine(result.FinalResponse);

Use Microsoft WorkflowBuilder directly when you need custom executors and graph edges. WorkflowAgentOrchestrator executes the graph with InProcessExecution and maps workflow output events into Fonseca orchestration results and streaming events.

Agent-to-Agent (A2A) Hosting

The official Microsoft.Agents.AI.Hosting.A2A.AspNetCore prerelease package is included so an AIAgent can be exposed to other agent frameworks through Microsoft’s A2A HTTP+JSON or JSON-RPC hosting surface. This is separate from the existing local stdio ACP transport.

using FonsecaFramework.Ai.Hosting;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Hosting.A2A;

// Create the same AIAgent instance that will be registered and mapped.
AIAgent agent = chatClient.AsHarnessAgent(new HarnessAgentOptions
{
    Name = "goat-agent",
    Description = "An Agent Framework assistant for the goat gods."
});

builder.Services.AddFonsecaA2AServer(agent, options =>
{
    options.AgentRunMode = AgentRunMode.AllowBackgroundIfSupported;
});

var app = builder.Build();
app.MapFonsecaA2A(agent, "/a2a/goat-agent");
// Or expose the JSON-RPC binding:
// app.MapFonsecaA2AJsonRpc(agent, "/a2a/goat-agent");

The mapped route exposes the A2A agent-card and message endpoints provided by Microsoft. Register the server before building the application, and use the same AIAgent instance for registration and endpoint mapping. Because the A2A package is currently prerelease, its MEAI001 evaluation diagnostic is intentionally suppressed only inside the adapter.

RAG with LLM-Powered Sentiment Analysis

using FonsecaFramework.Ai;
using FonsecaFramework.Ai.LLM;

// Use Ollama for richer discourse analysis
var chatClient = new VLRChatClient("http://localhost:11434", model: "qwen3:8b");
var sentimentAnalyzer = new OllamaSentimentAnalyzer(chatClient);

var store = await RagVectorStore.Build(
    sourceFolder: "./docs",
    sentimentAnalyzer: sentimentAnalyzer);

// Retrieve relevant chunks (no built‑in sentiment filter yet)
string result = await store.LookupAsync(
    query: "What safety precautions should I take?",
    topK: 5);

Agent Framework Integration (TextSearchProvider)

using FonsecaFramework.Ai;
using Microsoft.Agents.AI;

var store = await RagVectorStore.Build("./docs");

// Basic wrapper for Microsoft Agent Framework RAG pattern
var provider = store.CreateTextSearchProvider(
    options: new TextSearchProviderOptions
    {
        SearchTime = TextSearchProviderOptions.TextSearchBehavior.BeforeAIInvoke
    },
    topK: 3,
    minSimilarity: 0.05);

// Optional: direct adapter usage if you need raw search results
var results = await store.SearchTextResultsAsync("refund policy", topK: 3);

Sentiment / Discourse Analysis

using FonsecaFramework.Ai;

var analyzer = new LexiconSentimentAnalyzer();

float[] vector = await analyzer.AnalyzeAsync(
    "Warning: Do not operate the machine without safety equipment.");

// vector is a 10-element array:
// [positive, negative, instructional, technical, cautionary,
//  informational, urgency, formality, specificity, actionability]

string category = analyzer.Classify(vector);
Console.WriteLine($"Dominant category: {category}"); // "cautionary"

VLRChatClient — OpenAI-Compatible LLM Integration

using FonsecaFramework.Ai.LLM;
using Microsoft.Extensions.AI;

using var client = new VLRChatClient("http://localhost:11434");

var messages = new[]
{
    new ChatMessage(ChatRole.System, "You are a helpful assistant."),
    new ChatMessage(ChatRole.User, "Explain dependency injection in one paragraph.")
};

var response = await client.GetResponseAsync(messages);
Console.WriteLine(response.Text);

ACP Subagent Delegation

Configure local ACP-compatible agent processes when registering the orchestration stack. The planner selects an agent through ToolInvocation.AgentName and may run work concurrently only by assigning the same non-empty ParallelGroup to independent invocations. Dependencies are expressed through DependsOnInvocationIds.

services.AddFonsecaAiOrchestration(options =>
{
    options.MaxSubagentConcurrency = 3;
    options.AcpAgents.Add(new AcpAgentDefinition
    {
        Name = "research",
        Command = "my-acp-agent",
        Arguments = ["--stdio"]
    });
});

ACP subagents are launched as local child processes with redirected standard input and output. Configure only trusted executables, avoid placing secrets in command-line arguments, and restrict agent working directories and inherited environment variables. The ACP client is isolated behind IAcpTransport; an HTTP transport can be added later without changing orchestration callers.

Requirements

  • .NET 10.0
  • For OllamaSentimentAnalyzer / VLRChatClient: an OpenAI-compatible LLM endpoint (e.g. Ollama)

License

Copyright 2026 Steven Fonseca / VLR Creations

Licensed under the Apache License, Version 2.0. You may use this library free of charge, provided you include the required attribution notices. See the LICENSE file for full terms.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on FonsecaFramework.Ai:

Package Downloads
FonsecaFramework.Asp

Base classes and extensions for ASP.NET Core web applications, offering a fluent builder API, MVC/Razor helpers, Swagger, OAuth2/JWT auth, background services, and AI‑driven dynamic rate limiting.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2026.11.9.1 131 11/9/2026
2026.11.6.1 134 11/6/2026
2026.11.2.3 366 11/2/2026
2026.10.26.1 142 10/26/2026
2026.10.25.1 129 10/25/2026
2026.10.16.1 140 10/17/2026
2026.10.14.1 118 10/14/2026
2026.10.12.2 118 10/12/2026
2026.9.30.3 142 9/30/2026
2026.9.30.2 116 9/30/2026
2026.9.30.1 109 9/30/2026
2026.9.24.1 120 9/24/2026
2026.9.23.1 117 9/23/2026
2026.9.10.1 153 9/10/2026
2026.9.3.1 171 9/3/2026
2026.9.2.3 125 9/3/2026
2026.9.2.2 137 9/3/2026
2026.9.2.1 141 9/2/2026
2026.9.1.9 124 9/2/2026
2026.9.1.8 125 9/2/2026
Loading failed