AI Insights API

API endpoints for AI-powered insights and recommendations.

Overview

The AI Insights API provides programmatic access to AI-powered analysis and recommendations. All endpoints require authentication and enforce multi-tenant isolation.

Base URL

https://portal.gaugewell.io/api/insights

Authentication

All requests require a valid session token. Authentication is handled automatically when using the portal.

Cookie: portal_session=your-session-token

Rate Limiting

  • Limit: 100 requests per minute per client
  • Headers: Rate limit info included in responses
  • Exceeded: Returns 429 status code
X-RateLimit-Limit: 100 X-RateLimit-Remaining: 95 X-RateLimit-Reset: 1708185600

Endpoints

POST /api/insights/query

Execute an insights query with AI analysis.

Request Body

{ "type": "nlq" | "scoring" | "playbook" | "explain", "query": "string (required for nlq and explain)", "options": { "maxRecommendations": 5 } }

Query Types

scoring - Deterministic score analysis

{ "type": "scoring" }

nlq - Natural language query

{ "type": "nlq", "query": "How is my website performing?" }

playbook - Curated recommendations

{ "type": "playbook" }

explain - Metric explanation

{ "type": "explain", "query": "What is bounce rate?" }

Response

{ "type": "answer", "answer": "Your website is performing well overall...", "confidence": 0.85, "sources": ["scores", "analytics"], "suggestions": [ "What can I do to improve my bounce rate?", "How do I compare to competitors?" ], "recommendations": [ { "title": "Reduce Bounce Rate", "description": "Improve content relevance and page load speed", "effort_level": "medium", "impact_level": "high", "priority_score": 85 } ], "metadata": { "ai_provider": "openai", "ai_model": "gpt-4o-mini", "execution_time_ms": 1250, "tokens_used": 450 } }

Error Responses

400 Bad Request - Invalid query type or missing required fields

{ "error": "Invalid query type" }

401 Unauthorized - No valid session

{ "error": "Unauthorized" }

429 Too Many Requests - Rate limit exceeded

{ "error": "Rate limit exceeded", "retry_after": 60 }

500 Internal Server Error - Service error

{ "error": "Failed to process query" }

GET /api/insights/history

Retrieve query history for the current user.

Query Parameters

  • limit (optional) - Number of results (default: 10, max: 50)
  • offset (optional) - Pagination offset (default: 0)

Request

GET /api/insights/history?limit=10&offset=0

Response

{ "runs": [ { "id": "uuid", "run_type": "nlq", "input_params": { "query": "How is my website performing?" }, "result_data": { "answer": "...", "confidence": 0.85 }, "execution_time_ms": 1250, "tokens_used": 450, "ai_provider": "openai", "ai_model": "gpt-4o-mini", "completed_at": "2026-02-16T18:30:00Z" } ], "total": 45, "limit": 10, "offset": 0 }

Error Responses

401 Unauthorized - No valid session

{ "error": "Unauthorized" }

500 Internal Server Error - Database error

{ "error": "Failed to fetch history" }

Data Context

The API automatically fetches and includes context data from multiple sources:

Included Data

  • Client ID - Your organization identifier
  • Vertical - Your industry (dental, medical, etc.)
  • Scores - Latest visibility scores from Northstar
  • Analytics - Website traffic and engagement metrics
  • Goals - Active goals and progress
  • Action Items - Open tasks and priorities
  • Content - Published posts count
  • Social - Social media reach and engagement

Data Freshness

  • Scores: Updated after each Northstar scan
  • Analytics: Updated daily
  • Goals: Real-time
  • Action Items: Real-time
  • Content: Real-time
  • Social: Updated daily

Multi-Tenant Isolation

All endpoints enforce strict multi-tenant isolation:

  1. Session validation - Every request validates user session
  2. Tenant context - Extracts client ID from session
  3. Data filtering - All queries filtered by client ID
  4. Response scoping - Only returns data for authenticated client
  5. Audit logging - All queries logged with client and user ID

Security

Request Flow

Client Request Session Validation (getTenantContext) Client ID Extraction Data Fetching (filtered by client_id) Insights Service Call (with sanitized context) Response Logging (async) Client Response

Service Secret

Portal-to-service communication uses a secret header:

X-Service-Secret: [encrypted-secret]

This header is:

  • Required for all service calls
  • Validated on every request
  • Never exposed to clients
  • Rotated periodically

Data Sanitization

Before sending to insights service:

  • No passwords or tokens
  • No internal IDs exposed
  • No PII (personally identifiable information)
  • Only aggregated metrics

Performance

Response Times

  • Scoring: < 500ms (deterministic)
  • NLQ: 1-3 seconds (AI processing)
  • Playbook: < 500ms (database query)
  • Explain: 1-2 seconds (AI processing)

Caching

  • Client context: Cached for 5 minutes
  • Northstar scores: Cached until next scan
  • Analytics: Cached for 1 hour

Optimization

  • Parallel data fetching
  • Connection pooling
  • Async logging
  • Graceful degradation

Error Handling

Retry Logic

The API implements automatic retries for:

  • Network timeouts (3 retries)
  • Service unavailable (2 retries)
  • Rate limit errors (exponential backoff)

Fallback Behavior

If primary AI provider fails:

  1. Automatic failover to secondary provider
  2. Graceful degradation to deterministic analysis
  3. Clear error messages to user

Error Codes

CodeMeaningAction
400Invalid requestCheck request format
401UnauthorizedRe-authenticate
429Rate limitedWait and retry
500Server errorRetry or contact support
503Service unavailableRetry after delay

Examples

cURL Examples

Scoring Analysis

curl -X POST https://portal.gaugewell.io/api/insights/query \ -H "Content-Type: application/json" \ -H "Cookie: portal_session=your-token" \ -d '{"type":"scoring"}'

Natural Language Query

curl -X POST https://portal.gaugewell.io/api/insights/query \ -H "Content-Type: application/json" \ -H "Cookie: portal_session=your-token" \ -d '{ "type": "nlq", "query": "How is my website performing?" }'

Get History

curl https://portal.gaugewell.io/api/insights/history?limit=5 \ -H "Cookie: portal_session=your-token"

JavaScript Examples

Using Fetch API

// Scoring analysis const response = await fetch('/api/insights/query', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ type: 'scoring' }) }); const data = await response.json(); console.log(data.answer);

Natural Language Query

const response = await fetch('/api/insights/query', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ type: 'nlq', query: 'What should I focus on first?' }) }); const data = await response.json(); console.log(data.recommendations);

Get History

const response = await fetch('/api/insights/history?limit=10'); const data = await response.json(); console.log(`Total queries: ${data.total}`);

Database Schema

insight_runs Table

Logs all insight queries for audit and analytics.

CREATE TABLE insight_runs ( id UUID PRIMARY KEY, client_id UUID NOT NULL, user_id UUID NOT NULL, run_type TEXT NOT NULL, input_params JSONB, result_data JSONB, execution_time_ms INTEGER, tokens_used INTEGER, ai_provider TEXT, ai_model TEXT, completed_at TIMESTAMPTZ DEFAULT NOW() );

Indexes

CREATE INDEX idx_insight_runs_client ON insight_runs(client_id); CREATE INDEX idx_insight_runs_user ON insight_runs(user_id); CREATE INDEX idx_insight_runs_completed ON insight_runs(completed_at DESC);

Monitoring

Metrics to Track

  • Request volume per client
  • Response times by query type
  • Error rates
  • AI provider usage
  • Token consumption
  • Cache hit rates

Logging

All requests logged with:

  • Client ID
  • User ID
  • Query type
  • Execution time
  • Success/failure
  • Error details (if any)

Support

For API support:

  • Documentation: This page
  • Technical issues: Contact development team
  • Feature requests: Submit via portal feedback

Last Updated: February 16, 2026
Version: 1.0
Service URL: https://insights.gaugewell.io 

Last updated on