Skip to main content

Reasoning Engine Agents

Agent Architecture

The Reasoning Engine delegates analytical responsibilities across ten registered agents, each scoped to a single analytical discipline. This decomposition produces higher-quality output than a monolithic approach because each agent's prompt and model configuration are tuned exclusively for its domain.

The specialization delivers two architectural advantages:

  1. Precision through focus -- each agent operates within a narrow analytical domain, yielding more accurate and consistent results than a single model tasked with the full analytical spectrum.
  2. Independent configurability -- tuning one agent (e.g., improving narrative quality in the Explanation Agent) has zero impact on the statistical accuracy of upstream agents.

Collaboration Model

The agents execute in a defined sequence organized into four functional phases. Each phase builds upon the accumulated output of prior phases:

Execution Flow

  1. The Step Orchestrator evaluates the user's objective and the available data dimensions to produce an execution plan, potentially skipping unnecessary stages.

  2. The Temporal Agent computes statistical measures across all time-series inputs -- means, extremes, trend direction, and volatility. This quantitative foundation supports all downstream analysis.

  3. The Pattern Agent combines algorithmic detection with semantic analysis to identify behavioral signatures: recurring cycles, cross-metric correlations, and warning indicators that statistical summaries alone do not surface.

  4. The Normalizer and Analysis agents handle correlation as a two-stage process. The Normalizer cleans and aligns heterogeneous datasets; after mathematical computation of Pearson coefficients, the Analysis Agent interprets the relationships in context.

  5. The Query Generator synthesizes the accumulated findings into targeted web search queries. The domain retrieval tool calls Perplexity when configured, assembles synthesis/citation knowledge, and falls back to local context when search is unavailable. The Content Analyzer is a registered helper for explicit content extraction flows, not part of the committed workflow path.

  6. The Explanation Agent synthesizes all prior outputs into a structured narrative with key findings and confidence assessment.

  7. The Validation Agent performs systematic fact-checking, verifying every claim in the narrative against the underlying data before the output leaves the engine.


Agent Profiles

AgentResponsibilityValue Delivered
Step OrchestratorDetermines which analysis steps to execute based on objective and data shapeReduces execution time and API cost by eliminating unnecessary stages
TemporalComputes time-series statistics and identifies trend directionsProvides the quantitative foundation all downstream agents depend on
PatternDetects behavioral signatures across metricsSurfaces recurring cycles and warning indicators beyond statistical summaries
NormalizerCleans and aligns heterogeneous datasets for correlationEnsures mathematical validity of cross-metric comparisons
Correlation AnalysisInterprets computed correlation coefficientsTranslates statistical relationships into actionable observations
Domain RetrievalBuilds Perplexity-backed or fallback knowledge contextProvides current external context without blocking local execution
Query GeneratorSynthesizes analysis context into targeted search queriesRetrieves domain knowledge specific to the user's detected patterns
Content AnalyzerRegistered helper for extracted-content workflowsAvailable to consumers, but not invoked by the committed workflow
ExplanationProduces the user-facing analytical narrativeSynthesizes all findings into a coherent, contextual explanation
ValidationFact-checks every claim against source dataPrevents hallucinated or inconsistent claims from reaching the consumer

Step Orchestrator Agent

Purpose

The Step Orchestrator evaluates the user's analytical objective against the available data dimensions and produces an execution plan -- an ordered list of pipeline steps to invoke. This selective execution eliminates unnecessary computation: a straightforward statistical query does not require pattern detection, correlation analysis, or domain knowledge retrieval.

Decision Logic

Objective TypeSteps SelectedSteps SkippedRationale
"What was my average stress?"Temporal, Explanation, ValidationPattern, Correlation, DomainStatistical query needs only temporal analysis
"Does stress affect my sleep?"Temporal, Correlation, Explanation, ValidationPattern, DomainRelationship question requires correlation computation
"How have I been doing?"All stepsNoneBroad exploratory question benefits from comprehensive analysis
"What should I do to feel better?"Temporal, Pattern, Domain, Explanation, ValidationCorrelationRecommendation request needs domain knowledge and pattern context

Performance impact: Selective execution reduces latency by 30-50% and proportionally reduces API cost for targeted queries. The Explanation and Validation steps always execute to maintain output integrity.

When orchestration is disabled, all steps execute unconditionally.


Temporal Agent

Purpose

The Temporal Agent performs statistical analysis across all time-series inputs, computing summary metrics and identifying directional trends. Its output constitutes the quantitative foundation of the pipeline -- pattern detection, correlation analysis, and narrative generation all depend on the statistics produced at this stage.

Processing Model

The agent employs dual-mode processing:

  1. Algorithmic analysis (deterministic): mean, min, max, standard deviation, trend classification (increasing/decreasing/stable), volatility assessment
  2. AI enhancement (semantic): contextualizes statistical results, identifies implications of data gaps, generates human-readable insight strings

Detection Categories

CategoryExamples
Upward trends"Stress has increased steadily over the past 5 days"
Downward trends"Energy is declining, currently averaging 3.2/10"
Stability"Mood has remained consistent at 4/5 throughout the period"
Anomalies"Sleep quality dropped significantly on Wednesday"
Data gaps"No check-ins recorded on weekends, suggesting possible routine disruption"
Recovery signals"Stress decreased 30% compared to the prior week"

Example Output

{
"summary": "Stress levels exhibit an upward trend over the observed period with peak values midweek. Energy remains consistently low with minimal variation.",
"insights": [
"Stress levels show a sustained upward trend over the last 5 days, peaking on Wednesday",
"Energy has remained consistently low (averaging 3.2/10) with minimal daily variation",
"Weekend check-ins are absent, which may indicate routine disruption or reduced engagement"
],
"stats": [
{ "id": "stress_level", "mean": 3.7, "min": 2.0, "max": 5.0, "trend": "increasing" },
{ "id": "energy", "mean": 3.2, "min": 2.0, "max": 5.0, "trend": "stable" }
]
}

Pattern Agent

Purpose

While the Temporal Agent quantifies what is changing, the Pattern Agent identifies why it matters. It detects behavioral signatures -- recurring cycles, cross-metric relationships, and clinically relevant indicators -- that statistical summaries alone do not surface. A rising stress trend becomes significantly more actionable when recognized as part of a stress-sleep feedback loop rather than reported as an isolated metric.

Processing Model

  1. Algorithmic detection -- deterministic pattern matching based on trend directions, volatility thresholds, and statistical signatures
  2. AI enhancement -- semantic recognition of behavioral patterns the algorithm cannot capture (e.g., "this combination of symptom timing and intensity is consistent with premenstrual symptom clustering")

Pattern Categories

CategoryPatternsSignificance
BehavioralReduced engagement, activity decline, routine disruptionChanges in interaction frequency; often a proxy for broader lifestyle shifts
WellbeingStress cycles, mood volatility, sleep-mood connectionCore health patterns linking multiple metrics into compound indicators
Cycle-RelatedPremenstrual symptoms, cycle regularity, symptom clusteringMenstrual cycle patterns that contextualize other metric fluctuations
Recovery SignalsImprovement trends, stabilization, resilience indicatorsPositive trajectories indicating effective coping or intervention
Warning SignsSustained decline, high-stress periods, energy depletionPatterns warranting attention or intervention before escalation

Example Output

{
"matches": ["stress_cycle", "sleep_mood_connection", "reduced_engagement"],
"confidence": 0.72,
"detectedPatterns": [
{
"name": "stress_cycle",
"series": ["stress_level", "sleep_quality"],
"detail": "Stress peaks midweek consistently, coinciding with elevated sleep disturbance"
},
{
"name": "reduced_engagement",
"series": ["checkins_per_day"],
"detail": "Check-in frequency declined from 5/day to 2/day over the observed period"
}
]
}

Confidence calibration: With fewer than 5 days of data, confidence values are reduced and findings are framed as preliminary observations. This prevents the output from overstating its certainty with sparse data.


Correlation Agents (Normalizer + Analysis)

Purpose

Correlation analysis answers a fundamental question: do these metrics move together? The step computes Pearson correlation coefficients for every pair of numeric datasets and produces interpretations that translate statistical relationships into actionable observations.

This is decomposed into two agents because correlation requires two fundamentally different capabilities:

  1. Data preparation -- real-world datasets contain mixed types, missing values, and misaligned indices
  2. Interpretation -- a coefficient of -0.82 requires contextual translation to inform decisions

Two-Agent Architecture

Normalizer Agent

Prepares heterogeneous datasets for valid mathematical computation:

  • Extracts numeric values from mixed-type arrays
  • Drops non-numeric entries ("N/A", null) while maintaining alignment across datasets
  • Preserves dataset ordering and reports normalization outcomes

Example:

InputOutput
[3.5, 4.0, "N/A", 3.2, 4.5][3.5, 4.0, 3.2, 4.5] (1 non-numeric dropped)
[7, 6, 5, 7, 5][7, 6, 7, 5] (aligned to match)

Analysis Agent

Interprets computed correlation coefficients, classifies relationship strength, identifies cascade effects, and produces actionable recommendations.

Interpretation Scale:

Coefficient (r)ClassificationInterpretation
0.7 to 1.0Strong positiveMetrics move together consistently
0.4 to 0.7Moderate positiveNotable co-movement pattern
0.0 to 0.4Weak positiveLimited relationship
-0.4 to 0.0Weak negativeSlight inverse tendency
-0.7 to -0.4Moderate negativeNotable inverse co-movement
-1.0 to -0.7Strong negativeStrongly inverse -- improving one may improve the other

Example Output

{
"summary": "Strong negative correlation (r=-0.82) between stress and sleep quality indicates that elevated stress significantly disrupts sleep. Energy shows strong positive correlation (r=0.71) with sleep quality.",
"insights": [
"Elevated stress days consistently correspond to reduced sleep quality",
"Improved sleep is a strong predictor of higher energy the following day",
"Addressing stress may produce cascading benefits: reduced stress -> improved sleep -> higher energy"
],
"nextSteps": [
"Monitor the impact of stress management interventions on sleep quality",
"Prioritize sleep hygiene practices during high-stress periods",
"Track energy levels as sleep quality improves to validate the cascade hypothesis"
]
}

The third insight identifies a cascade effect -- stress, sleep, and energy form a chain where addressing the upstream factor (stress) produces downstream benefits across multiple metrics.


Query Generator Agent

Purpose

Data analysis identifies what is happening; domain knowledge contextualizes why and informs what to do about it. The Query Generator bridges this gap by synthesizing the accumulated pipeline findings -- temporal trends, detected patterns, correlation results -- into focused web search queries designed to retrieve current, relevant external knowledge.

Query Design Principles

PrincipleApplication
Time-sensitivityIncorporates temporal context ("2025-2026", "latest", "recent") for current information
Pattern-specificityReferences detected patterns directly ("stress-sleep feedback loop intervention strategies")
Correlation-awarenessTargets the specific relationships found in the data
Search optimization5-10 words, statement format, domain-specific terminology

Priority Scoring

PriorityClassificationSelection Criteria
9-10CriticalDirectly addresses the user's core analytical objective
7-8HighExplores key correlations or detected patterns
5-6MediumProvides supporting contextual knowledge
1-4LowBackground or exploratory information

Example

Given pipeline findings of increasing stress with midweek peaks and a stress-sleep correlation of r=-0.82:

{
"queries": [
{
"query": "stress management techniques reducing work-related stress before bedtime",
"rationale": "Targets the stress-sleep connection (r=-0.82) with evidence-based interventions",
"priority": 10
},
{
"query": "midweek stress peak causes workplace stress accumulation patterns",
"rationale": "Addresses the detected midweek stress pattern for root cause analysis",
"priority": 8
},
{
"query": "sleep quality improvement strategies during high stress periods evidence-based",
"rationale": "Focuses on sleep-specific approaches for periods of elevated stress",
"priority": 7
}
]
}

Content Analyzer Agent

Purpose

Retrieved web content is rarely directly useful in its raw form. A general article on stress management may contain dozens of recommendations, but only a subset is relevant to a user whose specific pattern involves a stress-sleep feedback loop with midweek peaks.

The Content Analyzer acts as a contextual filter, processing retrieved content against the user's detected patterns, correlations, and objectives. Each extracted insight includes an explanation of its relevance, a concrete recommended action, and a confidence assessment.

Contextual vs. Generic Extraction

Generic SummaryContextual Extraction
"Article discusses stress management techniques""Progressive muscle relaxation before bed reduces cortisol -- directly relevant to the detected stress-sleep correlation (r=-0.82)"
"Mentions exercise benefits""Morning exercise reduces midweek stress accumulation -- applicable to the detected pattern of stress building Monday through Wednesday"
"Covers sleep hygiene""Consistent sleep schedule within 30-minute window improves quality -- the data shows sleep disturbance correlates with irregular timing patterns"

Example Output

{
"insights": [
{
"finding": "Progressive muscle relaxation before bed reduces stress-related sleep disruption by up to 40% in clinical studies",
"relevance": "Directly addresses the detected stress-sleep correlation (r=-0.82)",
"actionable": "Incorporate 10 minutes of progressive muscle relaxation into the bedtime routine on elevated-stress days",
"confidence": "high",
"evidence": "Meta-analysis of 15 clinical studies (2024) found consistent benefits for stress-related insomnia"
},
{
"finding": "Midweek stress peaks frequently correlate with accumulated cognitive load from the start of the work week",
"relevance": "Aligns with the detected pattern of stress consistently peaking midweek",
"actionable": "Consider scheduling high-cognitive-load tasks for Monday/Tuesday and lighter tasks for Wednesday/Thursday",
"confidence": "medium"
}
],
"summary": "Two findings directly relevant to the stress-sleep pattern. Strongest evidence supports bedtime relaxation techniques for stress-related sleep disruption."
}

Explanation Agent

Purpose

By the time the pipeline reaches the Explanation Agent, it has accumulated temporal statistics, detected patterns, correlation coefficients, and domain knowledge. The Explanation Agent synthesizes these disparate analytical outputs into a coherent narrative with key findings, confidence assessment, and contextual recommendations.

This is the most user-facing agent in the pipeline. Its output quality directly determines how well the analytical findings are communicated and understood.

Synthesis Model

Input SourceContribution to Narrative
Temporal AgentTrend directions, statistical measures, data gap observations
Pattern AgentNamed behavioral patterns, cross-metric signatures, confidence scores
Correlation AnalysisQuantified metric relationships with coefficients
Domain KnowledgeExternal evidence and recommendations relevant to detected patterns

Confidence Levels

LevelData RequirementNarrative Characteristics
LowFewer than 5 data pointsPreliminary language, explicit uncertainty caveats
Medium5 to 14 data pointsModerate certainty, patterns noted with limitations
High14+ data pointsStrong confidence, specific claims backed by robust data

Writing Standards

The agent:

  • Addresses the user directly using second person
  • Presents the most significant finding first
  • Supports claims with specific data references (coefficients, trend directions, values)
  • Distinguishes correlation from causation
  • Acknowledges uncertainty proportional to data availability

Example Output

{
"narrative": "Over the past week, your stress levels have shown a sustained upward trend, peaking midweek at 4.5/5. This stress appears to be significantly affecting your sleep quality -- the analysis identified a strong correlation (r=0.85) between elevated stress days and sleep disturbance.\n\nThe data suggests a stress-sleep feedback pattern where elevated weekday stress disrupts sleep quality, and the resulting poor sleep may be contributing to the consistently low energy levels observed (averaging 3.2/10).\n\nGiven the strong stress-sleep relationship, stress management techniques in the evening may be effective in interrupting this cycle. More consistent check-ins, particularly on weekends, would provide a more complete picture of your weekly patterns.",
"keyPoints": [
"Strong stress-sleep correlation (r=0.85) indicates stress is significantly disrupting rest",
"Midweek stress peaks are a consistent pattern across the observed period",
"Low energy levels (3.2/10 average) may result from compounding stress and sleep disruption"
],
"confidence": "medium"
}

Validation Agent

Purpose

LLMs can produce plausible but factually incorrect claims. The Validation Agent is a dedicated verification layer that systematically compares every factual claim in the narrative against the computed data, flagging inconsistencies before the output reaches the consumer.

Verification Categories

The agent performs five categories of checks:

CategoryWhat It VerifiesExample Failure
Data ConsistencyNarrative claims match computed statisticsClaims "stress decreasing" when stats show increasing trend
Correlation AccuracyRelationships classified at correct strengthModerate correlation (r=0.5) described as "strong"
Pattern ValidityReferenced patterns were actually detectedMentions "mood volatility" when that pattern was not found
OvergeneralizationConclusions appropriately scoped for data volume"You always feel stressed on Mondays" from 2 data points
Missing CaveatsSparse data receives uncertainty disclaimersConfident assertions from 3 days without limitations noted

Verification Philosophy

The agent applies strict factual standards with flexible stylistic tolerance:

StrictFlexible
Statistical accuracyWord choice and phrasing
Trend direction claimsNarrative structure
Correlation strength classificationWriting style
Data-claim alignmentTone and voice

A narrative can be structured in many ways, but every factual assertion must be verifiable against the computed data.

Example

Input narrative: "Your stress has been decreasing over the past week, which is encouraging."

Computed data: stress trend = increasing, mean = 4.2, range = 3.0-5.0

Validation result:

{
"valid": false,
"issues": [
"Narrative claims stress is decreasing, but temporal stats show 'increasing' trend (mean: 4.2, range: 3.0-5.0)",
"Positive framing is inappropriate when the underlying data indicates a concerning upward trajectory"
]
}

Design Principles

Dual-Mode Processing

Every analysis step runs deterministic algorithms first (reliable, reproducible baselines), then layers AI enhancement on top (nuanced, contextual interpretation). The pipeline always produces a result even when agents are unavailable.

Fail-Safe Pipeline

When any agent fails or returns invalid output:

  • The pipeline continues with degraded results rather than terminating
  • The failed step is logged, and downstream agents operate on available data
  • The Validation Agent flags the gap so consumers are aware of reduced coverage

Per-Agent Model Selection

Each agent can target a different model deployment, enabling cost and quality optimization per analytical stage:

Agent RoleRecommended TierRationale
Temporal, Normalizer, Step OrchestratorCost-efficient modelStatistical and classification tasks; lower latency
Pattern, Domain, ValidationStandard modelBenefits from stronger reasoning capabilities
ExplanationStandard modelNarrative quality is user-facing; justifies the cost

Configurable Behavior

Each agent's system prompt and model configuration can be updated without redeployment. Changes take effect immediately through automatic cache invalidation. Version history is maintained for audit purposes.


Next Steps