Skip to content

Infrastructure Types

The Strategos.Infrastructure package provides production-ready implementations of core abstractions.

Thompson Sampling

Adaptive agent selection using contextual multi-armed bandits.

ContextualAgentSelector

Selects the best agent for a task using Thompson Sampling with learned beliefs.

Methods

MethodParametersReturnsDescription
SelectAgentAsyncstring taskDescription, CancellationToken ctTask<AgentId>Selects best agent for task
RecordOutcomeAsyncAgentId agent, TaskCategory category, bool success, CancellationToken ctTaskUpdates beliefs based on outcome

Example

csharp
public class AssignAgentStep : IWorkflowStep<TaskState>
{
    private readonly IAgentSelector _selector;

    public async Task<StepResult<TaskState>> ExecuteAsync(
        TaskState state,
        StepContext context,
        CancellationToken ct)
    {
        var agent = await _selector.SelectAgentAsync(state.TaskDescription, ct);
        return state.With(s => s.AssignedAgent, agent).AsResult();
    }
}

AgentBelief

Represents performance belief as a Beta distribution.

Properties

PropertyTypeDescription
AlphadoubleSuccess count + prior
BetadoubleFailure count + prior
MeandoubleExpected success rate (alpha / (alpha + beta))
VariancedoubleUncertainty in estimate

Methods

MethodParametersReturnsDescription
SampleRandom randomdoubleDraws sample from distribution
Updatebool successAgentBeliefReturns updated belief

Example

csharp
// Initial belief with uniform prior
var belief = new AgentBelief(alpha: 1, beta: 1);

// After 7 successes and 3 failures
belief = belief.Update(success: true);  // Repeat for each outcome
// belief.Mean ~= 0.727

TaskCategory

Enumeration of task categories for contextual selection.

ValueDescription
AnalysisData analysis and interpretation
CodingCode generation and modification
ResearchInformation gathering and synthesis
WritingContent creation and editing
PlanningStrategy and roadmap development
ReviewEvaluation and feedback
UnknownUnclassified task type

IBeliefStore

Interface for persisting agent performance beliefs.

Methods

MethodParametersReturnsDescription
GetBeliefAsyncAgentId agent, TaskCategory categoryTask<AgentBelief>Gets belief for agent/category
SetBeliefAsyncAgentId agent, TaskCategory category, AgentBelief beliefTaskPersists updated belief

Implementations

TypeDescription
InMemoryBeliefStoreIn-memory storage (dev/testing)

Loop Detection

Detects stuck workflows using multiple strategies.

ExactRepetitionDetector

Detects identical action sequences.

Configuration

PropertyTypeDefaultDescription
WindowSizeint10Number of recent actions to analyze
Thresholdint3Repetitions to trigger detection

Example

csharp
services.AddLoopDetection(options => options
    .AddExactRepetition(config => config
        .WithWindowSize(10)
        .WithThreshold(3)));

SemanticRepetitionDetector

Detects similar outputs using cosine similarity.

Configuration

PropertyTypeDefaultDescription
SimilarityThresholddouble0.95Minimum similarity to consider repetition
WindowSizeint5Number of recent outputs to compare

Example

csharp
services.AddLoopDetection(options => options
    .AddSemanticRepetition(config => config
        .WithSimilarityThreshold(0.95)
        .WithWindowSize(5)));

OscillationDetector

Detects A-B-A-B patterns.

Configuration

PropertyTypeDefaultDescription
PatternLengthint2Length of oscillation pattern
Repetitionsint2Times pattern must repeat

Example

csharp
services.AddLoopDetection(options => options
    .AddOscillation(config => config
        .WithPatternLength(2)
        .WithRepetitions(2)));

NoProgressDetector

Detects activity without meaningful state change.

Configuration

PropertyTypeDefaultDescription
StepThresholdint5Steps without progress to trigger
ProgressEvaluatorFunc<TState, TState, bool>-Custom progress evaluation

Example

csharp
services.AddLoopDetection(options => options
    .AddNoProgress(config => config
        .WithStepThreshold(5)
        .WithProgressEvaluator((prev, curr) =>
            prev.ProcessedCount != curr.ProcessedCount)));

Budget Guard

Enforces resource limits on workflow execution.

BudgetGuard

Main type for budget enforcement.

Methods

MethodParametersReturnsDescription
CheckBudgetAsyncStepContext contextTask<BudgetStatus>Checks current budget status
RecordUsageAsyncResourceUsage usageTaskRecords resource consumption

BudgetOptions

Configuration for budget thresholds.

Properties

PropertyTypeDefaultDescription
MaxStepsint100Maximum step executions
MaxTokensint50,000Maximum LLM tokens
MaxWallTimeTimeSpan30 minutesMaximum elapsed time
ScarceThresholddouble0.75Percentage to enter Scarce state
CriticalThresholddouble0.90Percentage to enter Critical state

Example

csharp
services.AddBudgetGuard(options => options
    .WithMaxSteps(100)
    .WithMaxTokens(50_000)
    .WithMaxWallTime(TimeSpan.FromMinutes(30))
    .WithScarceThreshold(0.75)
    .WithCriticalThreshold(0.90));

ScarcityLevel

Budget consumption state enumeration.

ValueDescriptionTypical Response
Abundant< 50% consumedNormal operation
Normal50-75% consumedMonitor usage
Scarce75-90% consumedReduce exploration
Critical> 90% consumedMinimal operations only

BudgetStatus

Current budget state returned from checks.

Properties

PropertyTypeDescription
LevelScarcityLevelCurrent scarcity level
StepsRemainingintSteps until limit
TokensRemainingintTokens until limit
TimeRemainingTimeSpanTime until limit
IsExhaustedboolWhether any budget is exhausted

Registration

Complete infrastructure setup:

csharp
services.AddStrategos()
    .AddThompsonSampling(options => options
        .WithPrior(alpha: 2, beta: 2)
        .WithBeliefStore<InMemoryBeliefStore>())
    .AddLoopDetection(options => options
        .AddExactRepetition()
        .AddSemanticRepetition()
        .AddOscillation()
        .AddNoProgress())
    .AddBudgetGuard(options => options
        .WithMaxSteps(100)
        .WithMaxTokens(50_000)
        .WithMaxWallTime(TimeSpan.FromMinutes(30)));

Released under the MIT License.