Technical Design · Agent 3 of 4

Analysis Agent

The core analytical engine. It analyses harmonised internal and external datasets against historical baselines to calculate market share shifts and margin performance gaps — writing and executing Python instead of guessing at arithmetic.

Model
Azure OpenAI GPT-4o
Temperature
0.1 · deterministic
Trigger
Event-driven (Event Grid)

01

Agent Overview

Objective

Automatically analyse harmonised internal and external datasets against historical baselines to calculate market share shifts and margin performance gaps.

Role

Sits between the data harmonisation phase and the reporting phase, turning raw harmonised data into actionable financial and market insight.

Value

An LLM paired with a secure Python environment writes complex pandas analysis dynamically — mathematically exact, and hours faster than manual spreadsheets.

02

Interface Specification

Note on interface consistency

Inputs and outputs are strictly aligned with the upstream Integration Agent (Agent 2) and the downstream Communication Agent (Agent 4).

Inputs · from the Data Lake

  • harmonised_benchmarking_dataset · JSON/Parquet URI

    Mapped internal performance and external syndicated market data.

  • dataset_metadata · JSON

    Row counts, category hierarchies and date ranges for ingested data.

  • processing_timestamp · Datetime

    When the harmonised dataset was committed to the Data Lake.

Outputs · to Communication Agent

  • market_share_margin_gap_analytics · JSON

    Market share percentages, margin variances and historical comparisons.

  • gap_analysis_summary · String

    Structured summary of the top 3 over- and underperforming categories.

  • analysis_completion_status · String

    completed / failed — trigger event for the next agent.

Triggers

  • Event type: harmonised dataset ready in Data Lake.
  • Frequency: event-driven, immediately on successful data commit.
  • Source: Azure Event Grid listening to ADLS Gen2 blob creation events.
{
  "event_id": "evt_8923",
  "dataset_uri": "abfs://harmonised-data@datalake.dfs.core.windows.net/benchmarking/latest.parquet",
  "trigger_source": "gcp_azure_data_lake"
}

03

Architecture & Components

Model configuration

  • Model: Azure OpenAI GPT-4o — advanced reasoning and Python code generation.
  • Temperature 0.1: high determinism, minimal hallucination on financial calculations.
  • Max tokens 4096: enough for complex scripts plus analytical summaries.
  • System prompt: expert Financial & CD Data Analyst; never guess maths — write, execute and read Python output.

Prompting strategy

  • Template: context injection (schema + baselines) → task definition → execution instruction.
  • Few-shot: 2–3 examples of expected pandas structures (missing data, percentage-point diffs).
  • Chain-of-thought enforced — reasoning emitted in <thought_process> before invoking the Python tool.

Memory & context

  • Memory type: historical margin & market share baselines.
  • Retrieval: hybrid semantic + keyword search via Azure AI Search (e.g. "Q3 2023 Beverage Margins").
  • Context window: dataframes never enter the prompt — only df.head() and df.dtypes; the full dataset is processed in the sandbox.
  • State: output payload persisted to Azure Cosmos DB so downstream agents can rehydrate full context.

Tools & function calls · via MCP

ToolPurposeEndpointAuthInputOutput
python_execution_envExecutes LLM-generated Python (pandas, numpy) for exact calculations.Azure Container Apps Dynamic SessionsManaged Identity{ code, dataset_uri }{ stdout, stderr, result_json }
historical_baseline_retrieverFetches historical margin and market share data for comparison.Azure AI Search REST APIAPI Key / Entra ID{ category, timeframe }{ baselines[] }

04

Integration Logic

Protocol & error handling

  • Pattern: Model Context Protocol (MCP) for standardised tool invocation.
  • Auth: Microsoft Entra ID Managed Identities — credential-less access to Data Lake and sandbox.
  • Self-correction: on stderr (e.g. a pandas KeyError) the agent reads the error, rewrites the code and retries up to 3 times.
  • Fallback: after 3 failed attempts, emit a structured error payload for Human Oversight.

Security considerations

  • Ephemeral, network-isolated sandbox with no outbound internet access.
  • TLS 1.2+ in transit; Data Lake at rest encrypted with customer-managed keys.
  • Financial data aggregated; the system prompt forbids extracting or logging customer identifiers.

Data flow

  1. 1Trigger received — Event Grid signals the harmonised dataset is ready.
  2. 2Data retrieved — agent queries the dataset schema via python_execution_env.
  3. 3Context fetched — historical_baseline_retriever pulls past performance per category.
  4. 4Model processes — agent writes a script comparing new data against baselines.
  5. 5Tool execution — script runs in Dynamic Sessions; results return to the agent.
  6. 6Output sent — results formatted and the Communication Agent is triggered.

05

Risk & Controls — Trustworthy AI

Guardrails

  • Input validation: require revenue, cogs, market_size before calculating.
  • Output validation: market share must fall between 0% and 100%, else recalculate.
  • Hallucination prevention: every number must originate from the sandbox stdout.

Human-in-the-loop

  • No direct review at this node — review happens after the Communication Agent drafts the report.
  • Escalation: margin gap >15% variance from baseline flags an alert in metadata for reviewers.

Monitoring

  • Metrics: code generation success rate, average execution time, retries per invocation.
  • Alert engineering if Python execution failure rate exceeds 5% over one hour.
  • Log generated code, tool I/O and token usage to Application Insights — never financial row data.

06

Implementation Checklist

Define and test System Prompt with strict math-avoidance instructions
Configure Azure OpenAI GPT-4o parameters (Temp: 0.1)
Set up Azure AI Search for historical_baseline_retriever
Provision Azure Container Apps Dynamic Sessions for secure Python execution
Implement MCP tool definitions for Python and Retrieval tools
Configure Microsoft Entra ID Managed Identities for Data Lake access
Set up error handling and self-correction loops for Python errors
Implement guardrails (0–100% market share bounds checking)
Set up telemetry/logging in Azure Application Insights
Write unit tests for dataset schema variations
Conduct security review on the Python sandbox isolation

07

Appendix

System prompt snippet

You are the Analysis Agent. Your task is to
calculate market share and margin gaps.
You MUST NOT perform mathematical
calculations yourself.
You MUST write Python code using `pandas`,
execute it via the `python_execution_env`
tool, and use the exact output provided.

Example user prompt (triggered event)

{
  "instruction": "Analyse the new harmonised dataset.",
  "dataset_uri": "abfs://data/harmonised/q3_2023.parquet",
  "categories_detected": ["Beverages", "Snacks"]
}

Expected agent action

  • Invoke historical_baseline_retriever for “Beverages” and “Snacks”.
  • Write Python to load abfs://data/harmonised/q3_2023.parquet.
  • Compute (Company_Sales / Total_Market_Sales) * 100 and compare to baselines.
  • Return the market_share_margin_gap_analytics JSON.

Error codes

CodeMeaningResolution
ERR_PY_TIMEOUTPython script exceeded the 30s execution limit.Optimise the pandas code (vectorisation over loops) and retry.
ERR_DATA_SCHEMAExpected columns missing in harmonised dataset.Halt, flag status as failed, alert Data Engineering.
ERR_MATH_BOUNDSCalculated market share > 100%.Guardrail triggered — review aggregation logic and retry.