GMI · TECHNOLOGY OBSERVATORY // ALL SYSTEMS NOMINAL
ENGINEERED BY LEOPARD DATA

Claude AI Integration

How Grade My Investments leverages Anthropic's Claude AI to deliver intelligent financial analysis, interactive Q&A, and automated report comparison for users.

CLAUDE INTEGRATION
rendering diagram…
flowchart LR
    U([User]):::ext --> FA[File Analysis<br/>right-click Analyze]:::app
    U --> CC[Claude Console<br/>interactive Q-A]:::app
    U --> RC[Report Comparison<br/>select 2 runs]:::app
    U --> DA[Dashboard Ask Claude<br/>portfolio context]:::app
    FA --> DB1[(claudeanalysisjobs<br/>DB queue)]:::data
    CC --> DB1
    DB1 --> P1[Gmi.ClaudeAnalysis<br/>Console service]:::svc
    RC --> DB2[(reportcomparisonjobs<br/>DB queue)]:::data
    DB2 --> P2[Gmi.ReportComparison<br/>Console service]:::svc
    DA --> AZ[Azure Function<br/>inline call]:::svc
    P1 --> API[Anthropic<br/>Messages API]:::ext
    P2 --> API
    AZ --> API
    API --> P1
    API --> P2
    API --> AZ
    P1 --> OUT1[(DOCX - HTML<br/>Blob Storage)]:::data
    P2 --> OUT2[(Comparison DOCX<br/>Blob Storage)]:::data
    AZ --> OUT3[Dashboard<br/>Response]:::app
    classDef app fill:#1f2630,stroke:#C0894E,color:#F3EFE8;
    classDef svc fill:#241c14,stroke:#E2B583,color:#F3EFE8;
    classDef data fill:#22201a,stroke:#C0894E,color:#EBD3AE;
    classDef ext fill:#1b1f27,stroke:#5A616B,color:#C4C0B8;
    classDef sec fill:#1d2733,stroke:#5cc8e0,color:#eafaff;
Four distinct Claude AI features share the Anthropic Messages API but use separate background processors and output paths — file analysis and console Q&A via ClaudeAnalysis.Console, report comparison via ReportComparison.Console, and dashboard queries inline via Azure Functions.

Claude Features at a Glance

Grade My Investments integrates directly with Anthropic's Claude API to provide four distinct user-facing AI capabilities, each designed around a specific workflow:

Claude File Analysis

AI-powered document analysis with DOCX and HTML output saved alongside source files.

Claude Console

Interactive Q&A about your files in real-time with cost tracking per question.

Report Comparison

Compare two report runs and get a narrative change analysis generated by Claude.

Dashboard Ask Claude

Ask Claude questions about your AI Report Dashboard data in real-time.

Claude File Analysis (Wave 3)

Users can right-click any file or folder in the ManageFolders file manager and select "Analyze with Claude" to submit documents for AI-powered analysis. The result is a DOCX file (and a companion HTML file for mobile viewing) saved alongside the original, marked with a purple file indicator in the UI.

How It Works
1. User right-clicks files or folders in ManageFolders and selects "Analyze with Claude"
2. Cost estimation is calculated and displayed — user approves before proceeding
3. Analysis requests are queued in the database (claudeanalysisjobs / claudeanalysisrequests)
4. The Gmi.ClaudeAnalysis.Console background service picks up jobs in batches of 5
5. Files are sent to the Anthropic Claude API with concurrency of 3 and retry logic (3 attempts with exponential backoff)
6. Results are converted to DOCX and HTML, then saved alongside the original source files in blob storage
Background Processor
Gmi.ClaudeAnalysis.Console
  • Queue-based: Database-driven job queue
  • Batch size: 5 jobs per poll cycle
  • Concurrency: 3 parallel API calls
  • Retry: 3 attempts with exponential backoff
  • Rate limiting: Anthropic API throttle handling
  • Stale recovery: 30 min timeout for stuck requests
Supported File Types
Documents
  • PDF
  • DOCX / DOC
  • TXT / MD
  • JSON / XML
Data & Images
  • CSV / XLSX / XLS
  • PNG / JPG
  • GIF / BMP
  • WEBP
Content Extraction
  • PDF: PdfPig library
  • DOCX/XLSX: OpenXml SDK
  • Text files: UTF-8 encoding
  • Images: Claude Vision API (base64)
DOCX + HTML Output
  • DOCX generated with DocumentFormat.OpenXml
  • HTML generated with Markdig for mobile viewing
  • Markdig converts Claude's Markdown response
  • Purple file indicator in the file manager
  • Available on ClientWeb, AdminWeb, and MAUI Mobile

Claude Console (Wave 3)

The Claude Console is an interactive chat dialog that lets users ask questions about their files in real-time. Rather than submitting a batch analysis, users open a conversation with Claude about a specific file or an entire folder.

Features
  • Interactive chat dialog for file Q&A
  • Supports single files or entire folders (recursively collects all file IDs)
  • Real-time cost estimation per question
  • Token and cost tracking on each response
  • Keyboard support: Enter to send, Shift+Enter for new line
  • Available via toolbar button and right-click context menu
How It Works
1. User selects a file or folder and opens Claude Console
2. File content is extracted and sent as context
3. User types a question — cost estimate shown before submission
4. Claude responds with analysis — tokens and cost displayed
5. User can ask follow-up questions in the same session

Report Comparison with Claude (Wave 4)

Report Comparison lets users select two ML report generation runs from the same symbol list group and have Claude produce a detailed narrative analysis of what changed between them. Users can also add their own custom questions to be answered as part of the comparison.

Dialog Flow
Select Group
Pick a symbol list group
Select 2 Runs
Choose runs to compare
Custom Questions
Add specific questions
Estimate Cost
Review before submitting
Submit
Queue for processing
Background Processor
Gmi.ReportComparison.Console
  • Batch size: 3 jobs per poll cycle
  • Concurrency: 2 parallel API calls
  • Stale timeout: 60 minutes
  • Downloads both Excel file sets from blob storage
  • Sends to Claude with structured comparison prompt
  • Generates DOCX comparison analysis
DOCX Output Sections (11)
  1. Executive Summary
  2. Symbols Added
  3. Symbols Removed
  4. Movers & Shakers
  5. Improved Positions
  6. Deteriorated Positions
  7. New Risk Alerts
  8. Opportunities
  9. Portfolio-Level Trend
  10. Actionable Recommendations
  11. Your Questions Answered
Jobs Panel: Users can track comparison jobs in real-time via a dedicated jobs panel with auto-polling status updates. Custom questions typed by the user are included in section 11 ("Your Questions Answered") of the output document.
Negative-news screening (Wave 24, built September 2026): the one place Claude classifies rather than writes. A lexicon decides clear headlines; only the ambiguous middle goes to Claude Haiku, which must return JSON saying whether the article is bad news about this company, with a confidence. An alert fires only at 0.85 or above, a per-cycle call budget bounds the cost, and the feature ships switched off until real verdicts have been reviewed.
Automatic comparisons (Wave 11, built September 2026): a recurring report series submits each successful run for comparison against the previous run of the same lists through this same path, with the same entitlement check, estimate charge, reconcile-to-actual billing and $45 cap. The DOCX is named {schedule} - change analysis {date}.docx, and the user gets one notification when the report and the analysis are both ready.

Dashboard Ask Claude

The AI Report Dashboard includes an "Ask Claude" feature that lets users ask questions about their portfolio data directly from the dashboard view. Claude receives the full dashboard context (financial data, ML health scores, anomalies, forecasts) and provides specific, actionable analysis.

Features
  • Ask questions about any dashboard level (portfolio, sector, or symbol)
  • Full dashboard context sent automatically
  • Default analysis provided when no specific question is asked
  • Token and cost tracking on each response
  • Admin notification on each dashboard Claude request
How It Works
1. User clicks "Ask Claude" on the Report Dashboard
2. Dashboard context (data, scores, forecasts) is gathered
3. User optionally types a specific question
4. Claude Sonnet 5.5 (Haiku 5.5 on the free tier) responds with analysis and insights
5. Response with token usage and cost is displayed
Model: Dashboard Ask Claude uses Claude Sonnet 5.5 by default; free-tier accounts are routed to Claude Haiku 5.5 by the server-side entitlement allowlist. Available on ClientWeb, AdminWeb, and MAUI Mobile.

Technical Architecture

Claude integration is built around two background .NET console applications plus inline API calls in Azure Functions — a deliberate separation of concerns that keeps file analysis, report comparison, and real-time Q&A independent.

Gmi.ClaudeAnalysis.Console

File Analysis & Console Q&A

gmi-claudeanalysis.service
Gmi.ReportComparison.Console

Report Comparison Processing

gmi-reportcomparison.service
Shared Infrastructure
  • Azure Blob Storage for file I/O
  • DocumentFormat.OpenXml + Markdig for DOCX generation
  • Markdig HTML report generation for mobile viewing
  • Anthropic Messages API (v1/messages)
  • Systemd services on Azure VM
  • Environment variable configuration
  • Token-based billing integration
  • Admin email notifications on failures and usage
Database Tables
Feature Tables
File Analysis claudeanalysisjobs, claudeanalysisrequests
Report Comparison reportcomparisonjobs, reportcomparisonjobsymbollists

Model Options

Users choose which Claude model to use when submitting analysis or comparison jobs. Each model offers a different balance of quality, speed, and cost:

Model Use Case Input Cost Output Cost
Claude Sonnet 5.5 Recommended — best balance of quality and cost $3.60 / 1M tokens $18.00 / 1M tokens
Claude Haiku 5.5 Faster, cheaper — good for large files $1.80 / 1M tokens $9.00 / 1M tokens
Claude Opus 5.5 Most thorough — deepest analysis $7.20 / 1M tokens $36.00 / 1M tokens
Grade My Investments applies an 80% markup over Anthropic base costs (Haiku is the one deliberate exception, below). The prices shown above reflect what users pay.
Claude 5.5 upgrade (Sep 2026). Opus 5.5 dropped Anthropic's price from $5/$25 to $4/$20 per million tokens, and the saving is passed straight through (user price is still base × 1.8). Two request-level decisions came with it: Opus 5.5 defaults to medium effort, so every Opus request pins output_config.effort: "high" to keep the depth users were paying for; and every Opus/Sonnet 5.5 request opts into Anthropic's server-side refusal fallback ("fallbacks": "default"), so a safety-classifier false positive on a benign finance question is re-run on the recommended fallback model instead of failing. Billing prices the model that actually served the answer, read from the response.
Claude Haiku 5.5 upgrade (Oct 2026). Haiku 5.5 is priced by prompt size — $0.10/$0.50 per million tokens up to 100K input tokens, $0.50/$2.50 above — and its new tokenizer counts the same text as roughly 30% more tokens. Three decisions: the user price for Haiku was held flat at the Haiku 4.5 level ($1.80/$9.00, regardless of prompt size) by choice rather than re-derived as base × 1.8, so a quoted Haiku price never jumps at an invisible token threshold; internal cost and margin reporting use the real tiered rates, priced one request at a time from the response's usage.input_tokens; and effort is pinned to medium (the model default) on every Haiku request. Haiku 5.5 has no server-side refusal fallback, so each Haiku call site handles a refusal itself: Ask Claude returns a clear message with no charge and no free question used, the news classifier skips the headline, and the public-page summary falls back to its deterministic template — never a blank page.

How the model upgrades were engineered

Moving every Claude call in the platform to the 5.5 generation (Opus and Sonnet in September 2026, Haiku in October) touched eight call sites, six billing paths, three apps' model pickers, and stored preferences in the database. The decisions that made it safe:

  • One model catalog instead of six rate tables. Model IDs, Anthropic base rates, the customer markup, request shaping (effort, fallback opt-in) and response parsing moved into a single ClaudeModelCatalog. Every call site and billing path reads from it, and its tests pin every price.
  • Two pricing bugs surfaced by centralizing. The old Sonnet rate tables still used a stale $3/$15 base while Anthropic charged $2/$10, so users had been paying roughly a 170% markup instead of the published 80%; the upgrade corrected it (−33% for users). And the Haiku change exposed that Ask Claude derived the customer price as internal cost × 1.8 — with Haiku 5.5's 10× lower cost and a deliberately held user price, that would have charged paid users a tenth of the intended price. Customer prices now come only from the catalog, with explicit, commented overrides.
  • Thinking can't starve the answer. The 5.5 models think by default and thinking tokens count against max_tokens, so routes tuned for older models (400-token summaries, a 200-token classifier) got headroom; every call site reads only text blocks, and a refusal or a thinking-only reply is never published or billed.
  • Estimates follow the tokenizer. Haiku 5.5 counts the same text as about 30% more tokens, so pre-run cost estimates scale Haiku token counts by 1.3; final charges always reconcile to actual usage.
  • Old clients keep working. Stale model IDs sent by older MAUI builds, cached web clients or queued jobs are mapped to their 5.5 successors server-side, so nothing is silently downgraded to a cheaper model.
  • Deploy code, then migrate data. Each upgrade shipped an idempotent migration that moves only forward-looking preferences (e.g. a recurring report's comparison model) to the new IDs — historical job and charge rows keep the model that actually ran. It is applied after the code deploy, because old code doesn't recognize the new IDs and would quietly fall back to its default model.

API Endpoints

A total of 17 API endpoints power the Claude integration across file analysis, report comparison, and the report dashboard:

File Analysis (8 endpoints)
  • Estimate — Calculate cost before submission
  • Submit — Queue analysis job
  • Jobs — List user's analysis jobs
  • Job Detail — Get individual job status/results
  • Cancel — Cancel a pending analysis job
  • Dismiss — Dismiss a completed job from the list
  • Console Estimate — Cost estimate for a console question
  • Console Ask — Submit a console question
Report Comparison (8 endpoints)
  • Groups — List available symbol list groups
  • Runs — List report runs for a group
  • Estimate — Calculate comparison cost
  • Submit — Queue comparison job
  • Jobs — List user's comparison jobs
  • Job Detail — Get comparison job status/results
  • Cancel — Cancel a pending comparison job
  • Dismiss — Dismiss a completed job from the list
Report Dashboard (1 endpoint)
  • DashboardAskClaude — Ask Claude about dashboard data with full portfolio context
Key Stats
  • Background Processors 2
  • API Endpoints 17
  • Claude Models 3
  • AI Features 4
  • Supported File Types 16+
Claude API Integration
  • Anthropic Messages API
  • Native PDF support
  • Vision API for images
  • Structured prompts
Billing Integration
  • Token-based billing (input + output)
  • Cost estimation before submission
  • 80% markup over Anthropic base cost
  • Charge reversal on failure
Security
  • API key in Azure Key Vault / env vars
  • No user data sent to third parties beyond Anthropic API
  • Fail-open validation