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:
- 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.
- 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
-
The Step Orchestrator evaluates the user's objective and the available data dimensions to produce an execution plan, potentially skipping unnecessary stages.
-
The Temporal Agent computes statistical measures across all time-series inputs -- means, extremes, trend direction, and volatility. This quantitative foundation supports all downstream analysis.
-
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.
-
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.
-
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.
-
The Explanation Agent synthesizes all prior outputs into a structured narrative with key findings and confidence assessment.
-
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
| Agent | Responsibility | Value Delivered |
|---|---|---|
| Step Orchestrator | Determines which analysis steps to execute based on objective and data shape | Reduces execution time and API cost by eliminating unnecessary stages |
| Temporal | Computes time-series statistics and identifies trend directions | Provides the quantitative foundation all downstream agents depend on |
| Pattern | Detects behavioral signatures across metrics | Surfaces recurring cycles and warning indicators beyond statistical summaries |
| Normalizer | Cleans and aligns heterogeneous datasets for correlation | Ensures mathematical validity of cross-metric comparisons |
| Correlation Analysis | Interprets computed correlation coefficients | Translates statistical relationships into actionable observations |
| Domain Retrieval | Builds Perplexity-backed or fallback knowledge context | Provides current external context without blocking local execution |
| Query Generator | Synthesizes analysis context into targeted search queries | Retrieves domain knowledge specific to the user's detected patterns |
| Content Analyzer | Registered helper for extracted-content workflows | Available to consumers, but not invoked by the committed workflow |
| Explanation | Produces the user-facing analytical narrative | Synthesizes all findings into a coherent, contextual explanation |
| Validation | Fact-checks every claim against source data | Prevents 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 Type | Steps Selected | Steps Skipped | Rationale |
|---|---|---|---|
| "What was my average stress?" | Temporal, Explanation, Validation | Pattern, Correlation, Domain | Statistical query needs only temporal analysis |
| "Does stress affect my sleep?" | Temporal, Correlation, Explanation, Validation | Pattern, Domain | Relationship question requires correlation computation |
| "How have I been doing?" | All steps | None | Broad exploratory question benefits from comprehensive analysis |
| "What should I do to feel better?" | Temporal, Pattern, Domain, Explanation, Validation | Correlation | Recommendation 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:
- Algorithmic analysis (deterministic): mean, min, max, standard deviation, trend classification (increasing/decreasing/stable), volatility assessment
- AI enhancement (semantic): contextualizes statistical results, identifies implications of data gaps, generates human-readable insight strings
Detection Categories
| Category | Examples |
|---|---|
| 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
- Algorithmic detection -- deterministic pattern matching based on trend directions, volatility thresholds, and statistical signatures
- 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
| Category | Patterns | Significance |
|---|---|---|
| Behavioral | Reduced engagement, activity decline, routine disruption | Changes in interaction frequency; often a proxy for broader lifestyle shifts |
| Wellbeing | Stress cycles, mood volatility, sleep-mood connection | Core health patterns linking multiple metrics into compound indicators |
| Cycle-Related | Premenstrual symptoms, cycle regularity, symptom clustering | Menstrual cycle patterns that contextualize other metric fluctuations |
| Recovery Signals | Improvement trends, stabilization, resilience indicators | Positive trajectories indicating effective coping or intervention |
| Warning Signs | Sustained decline, high-stress periods, energy depletion | Patterns 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:
- Data preparation -- real-world datasets contain mixed types, missing values, and misaligned indices
- 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:
| Input | Output |
|---|---|
[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) | Classification | Interpretation |
|---|---|---|
| 0.7 to 1.0 | Strong positive | Metrics move together consistently |
| 0.4 to 0.7 | Moderate positive | Notable co-movement pattern |
| 0.0 to 0.4 | Weak positive | Limited relationship |
| -0.4 to 0.0 | Weak negative | Slight inverse tendency |
| -0.7 to -0.4 | Moderate negative | Notable inverse co-movement |
| -1.0 to -0.7 | Strong negative | Strongly 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
| Principle | Application |
|---|---|
| Time-sensitivity | Incorporates temporal context ("2025-2026", "latest", "recent") for current information |
| Pattern-specificity | References detected patterns directly ("stress-sleep feedback loop intervention strategies") |
| Correlation-awareness | Targets the specific relationships found in the data |
| Search optimization | 5-10 words, statement format, domain-specific terminology |
Priority Scoring
| Priority | Classification | Selection Criteria |
|---|---|---|
| 9-10 | Critical | Directly addresses the user's core analytical objective |
| 7-8 | High | Explores key correlations or detected patterns |
| 5-6 | Medium | Provides supporting contextual knowledge |
| 1-4 | Low | Background 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 Summary | Contextual 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 Source | Contribution to Narrative |
|---|---|
| Temporal Agent | Trend directions, statistical measures, data gap observations |
| Pattern Agent | Named behavioral patterns, cross-metric signatures, confidence scores |
| Correlation Analysis | Quantified metric relationships with coefficients |
| Domain Knowledge | External evidence and recommendations relevant to detected patterns |
Confidence Levels
| Level | Data Requirement | Narrative Characteristics |
|---|---|---|
| Low | Fewer than 5 data points | Preliminary language, explicit uncertainty caveats |
| Medium | 5 to 14 data points | Moderate certainty, patterns noted with limitations |
| High | 14+ data points | Strong 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:
| Category | What It Verifies | Example Failure |
|---|---|---|
| Data Consistency | Narrative claims match computed statistics | Claims "stress decreasing" when stats show increasing trend |
| Correlation Accuracy | Relationships classified at correct strength | Moderate correlation (r=0.5) described as "strong" |
| Pattern Validity | Referenced patterns were actually detected | Mentions "mood volatility" when that pattern was not found |
| Overgeneralization | Conclusions appropriately scoped for data volume | "You always feel stressed on Mondays" from 2 data points |
| Missing Caveats | Sparse data receives uncertainty disclaimers | Confident assertions from 3 days without limitations noted |
Verification Philosophy
The agent applies strict factual standards with flexible stylistic tolerance:
| Strict | Flexible |
|---|---|
| Statistical accuracy | Word choice and phrasing |
| Trend direction claims | Narrative structure |
| Correlation strength classification | Writing style |
| Data-claim alignment | Tone 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 Role | Recommended Tier | Rationale |
|---|---|---|
| Temporal, Normalizer, Step Orchestrator | Cost-efficient model | Statistical and classification tasks; lower latency |
| Pattern, Domain, Validation | Standard model | Benefits from stronger reasoning capabilities |
| Explanation | Standard model | Narrative 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.