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.
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;
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
claudeanalysisjobs / claudeanalysisrequests)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
Documents
- DOCX / DOC
- TXT / MD
- JSON / XML
Data & Images
- CSV / XLSX / XLS
- PNG / JPG
- GIF / BMP
- WEBP
- PDF: PdfPig library
- DOCX/XLSX: OpenXml SDK
- Text files: UTF-8 encoding
- Images: Claude Vision API (base64)
- 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
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
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
- Executive Summary
- Symbols Added
- Symbols Removed
- Movers & Shakers
- Improved Positions
- Deteriorated Positions
- New Risk Alerts
- Opportunities
- Portfolio-Level Trend
- Actionable Recommendations
- Your Questions Answered
{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
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.serviceGmi.ReportComparison.Console
Report Comparison Processing
gmi-reportcomparison.serviceShared 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 |
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.
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 onlytextblocks, 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