npm package: @morbidcorp/ai
Description: Official TypeScript/JavaScript SDK for Morbid AI - An Heir ecosystem project providing actuarial mortality predictions with thermal uncertainty quantification
Author: Heir PTE LTD Singapore
Latest version: 0.1.2

# @morbidcorp/ai

<div align="center">
  
  **Part of the Heir Ecosystem**
  
  [![Heir Ecosystem](https://img.shields.io/badge/Heir-Ecosystem-purple)](https://heir.io)
  [![npm version](https://img.shields.io/npm/v/@morbidcorp/ai.svg)](https://www.npmjs.com/package/@morbidcorp/ai)
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
  [![X402 Protocol](https://img.shields.io/badge/X402-Base%20Mainnet-blue)](https://basescan.org/address/0x4edE90121555e88d04811Eb8109CEa584fC5063e)
  
</div>

Official TypeScript/JavaScript SDK for **Morbid AI** - An advanced actuarial mortality prediction system with thermal uncertainty quantification, proudly part of the **Heir ecosystem**.

## Features

- 🎯 **Actuarial Predictions** - Life expectancy, death probability, and insurance premiums
- 🌡️ **Thermal Uncertainty** - Advanced uncertainty quantification using THRML
- ⛓️ **X402 Protocol** - Blockchain integration for AI agent economy on Base
- 📊 **Confidence Intervals** - Statistical confidence bounds on all predictions
- 🚀 **High Performance** - 60% latency reduction, 150% throughput increase
- 🔒 **Type-Safe** - Full TypeScript support with comprehensive types

## Installation

```bash
npm install @morbidcorp/ai
# or
yarn add @morbidcorp/ai
# or
pnpm add @morbidcorp/ai
```

## Quick Start

```typescript
import { createMorbidClient } from '@morbidcorp/ai';

// Create a client with thermal uncertainty enabled
const morbid = createMorbidClient({
  apiKey: 'your-api-key', // Optional
  enableThermal: true,
});

// Predict life expectancy
const prediction = await morbid.predictLifeExpectancy(65, {
  sex: 1, // 1=male, 2=female, 3=both
  country: 'USA',
  thermalEnabled: true,
});

console.log(`Life expectancy: ${prediction.prediction.value} years`);
console.log(`95% CI: [${prediction.confidenceInterval.lower}, ${prediction.confidenceInterval.upper}]`);
console.log(`Uncertainty: ±${prediction.prediction.uncertainty} years`);
```

## API Reference

### MorbidClient

Main client for interacting with Morbid AI API.

```typescript
import { MorbidClient } from '@morbidcorp/ai';

const client = new MorbidClient({
  apiKey: 'your-api-key',
  baseUrl: 'https://morbid.ai/api', // Default
});
```

#### Methods

##### `predictLifeExpectancy(age, options?)`
Calculate life expectancy with optional thermal uncertainty.

```typescript
const result = await client.predictLifeExpectancy(45, {
  sex: 2, // Female
  country: 'Japan',
  thermalEnabled: true,
});
```

##### `calculateDeathProbability(age, options?)`
Calculate annual and cumulative death probabilities.

```typescript
const result = await client.calculateDeathProbability(70, {
  sex: 1, // Male
  country: 'USA',
});
```

##### `calculateInsurancePremium(age, coverage, term, options?)`
Calculate risk-adjusted insurance premiums.

```typescript
const result = await client.calculateInsurancePremium(
  35, // Age
  500000, // Coverage amount in USD
  20, // Term in years
  { sex: 1, country: 'USA' }
);

console.log(`Annual premium: $${result.premium.annual}`);
console.log(`Monthly premium: $${result.premium.monthly}`);
console.log(`Risk multiplier: ${result.riskMultiplier}`);
```

##### `query(prompt)`
Natural language queries about mortality.

```typescript
const result = await client.query(
  "What is the life expectancy of a 50-year-old male in the USA?"
);
```

### X402Protocol

Interact with the X402 Protocol on Base blockchain.

```typescript
import { X402Protocol } from '@morbidcorp/ai';
import { ethers } from 'ethers';

const x402 = new X402Protocol({
  chainId: 8453, // Base mainnet
  rpcUrl: 'https://mainnet.base.org',
});

// Connect with a signer
const provider = new ethers.BrowserProvider(window.ethereum);
const signer = await provider.getSigner();
await x402.connect(signer);

// Register an AI agent
const registration = await x402.registerAgent({
  agentAddress: '0x...',
  agentType: 'mortality_predictor',
  metadata: {
    name: 'My AI Agent',
    version: '1.0.0',
    modelType: 'thermal',
  },
});

console.log(`Agent registered: ${registration.agentId}`);
```

### ThermalModel

Advanced uncertainty quantification using thermal methods.

```typescript
import { ThermalModel } from '@morbidcorp/ai';

const thermal = new ThermalModel();

// Analyze mortality with uncertainty
const analysis = await thermal.mortalityUncertainty({
  age: 60,
  sex: 1,
  country: 'USA',
});

console.log(`Mean life expectancy: ${analysis.lifeExpectancy.mean}`);
console.log(`Uncertainty: ${analysis.lifeExpectancy.uncertainty}`);
console.log(`95% CI: ${analysis.lifeExpectancy.confidenceInterval}`);

// Calculate confidence intervals
const intervals = await thermal.calculateConfidenceIntervals(
  mortalityData,
  [0.90, 0.95, 0.99]
);

// Stream real-time updates
for await (const update of thermal.streamUpdates({ initialAge: 40 })) {
  console.log(`Updated prediction: ${update.mean} ± ${update.uncertainty}`);
}
```

## Examples

### Complete Insurance Quote

```typescript
import { createMorbidClient } from '@morbidcorp/ai';

async function getInsuranceQuote(age: number, coverage: number) {
  const client = createMorbidClient({ enableThermal: true });
  
  // Get mortality predictions
  const lifeExpectancy = await client.predictLifeExpectancy(age);
  const deathProb = await client.calculateDeathProbability(age);
  const premium = await client.calculateInsurancePremium(age, coverage, 20);
  
  return {
    expectedLifespan: lifeExpectancy.prediction.value,
    annualDeathRisk: deathProb.prediction.value,
    monthlyPremium: premium.premium.monthly,
    confidenceLevel: lifeExpectancy.prediction.confidence,
  };
}

const quote = await getInsuranceQuote(45, 1000000);
console.log(`Monthly premium: $${quote.monthlyPremium.toFixed(2)}`);
```

### X402 Agent Registration

```typescript
import { X402Protocol } from '@morbidcorp/ai';
import { ethers } from 'ethers';

async function registerMortalityAgent() {
  const x402 = new X402Protocol();
  
  // Connect wallet
  const provider = new ethers.BrowserProvider(window.ethereum);
  await provider.send("eth_requestAccounts", []);
  const signer = await provider.getSigner();
  await x402.connect(signer);
  
  // Register agent
  const result = await x402.registerAgent({
    agentAddress: await signer.getAddress(),
    agentType: 'mortality_predictor',
    metadata: {
      name: 'Advanced Mortality Predictor v2',
      description: 'Thermal-enhanced mortality predictions',
      version: '2.0.0',
      modelType: 'thermal',
    },
  });
  
  console.log(`✅ Agent registered with ID: ${result.agentId}`);
  console.log(`📋 Transaction: ${result.registrationTx}`);
  
  // Check reputation
  const reputation = await x402.getAgentReputation(await signer.getAddress());
  console.log(`⭐ Current reputation: ${reputation}`);
}
```

### Thermal Uncertainty Comparison

```typescript
import { ThermalModel } from '@morbidcorp/ai';

async function comparePredictionMethods() {
  const thermal = new ThermalModel();
  
  const comparison = await thermal.comparePredictions({
    age: 55,
    traditional: true,
    thermal: true,
  });
  
  console.log('Traditional prediction:', comparison.traditional?.value);
  console.log('Thermal prediction:', comparison.thermal?.mean);
  console.log('Uncertainty:', comparison.thermal?.uncertainty);
  console.log('Accuracy improvement:', comparison.improvement?.accuracyGain);
}
```

## Configuration

### Environment Variables

```bash
# API Configuration
MORBID_API_KEY=your-api-key
MORBID_API_URL=https://morbid.ai/api

# X402 Protocol
X402_PROTOCOL_ADDRESS=0x4edE90121555e88d04811Eb8109CEa584fC5063e
X402_ORACLE_ADDRESS=0xE162371591Fb24eD393E67D7665D79b95c155d30
X402_RPC_URL=https://mainnet.base.org

# Thermal Configuration
THERMAL_ENABLE=true
THERMAL_ITERATIONS=10000
THERMAL_CONFIDENCE_LEVEL=0.95
```

### Custom Configuration

```typescript
import { MorbidClient, X402Protocol, ThermalModel } from '@morbidcorp/ai';

// Custom client configuration
const client = new MorbidClient({
  apiKey: process.env.MORBID_API_KEY,
  baseUrl: 'https://custom.morbid.ai/api',
  thermal: {
    enableUncertainty: true,
    confidenceLevel: 0.99,
    samplingIterations: 20000,
  },
});

// Custom X402 configuration
const x402 = new X402Protocol({
  protocolAddress: '0x...',
  chainId: 84532, // Base Sepolia
  rpcUrl: 'https://sepolia.base.org',
});

// Custom thermal configuration
const thermal = new ThermalModel({
  baseUrl: 'https://thermal.morbid.ai/api',
  apiKey: process.env.THERMAL_API_KEY,
});
```

## Error Handling

```typescript
import { MorbidError } from '@morbidcorp/ai';

try {
  const result = await client.predictLifeExpectancy(150); // Invalid age
} catch (error) {
  if (error instanceof MorbidError) {
    console.error('Morbid Error:', error.message);
    console.error('Error Code:', error.code);
    console.error('Status:', error.statusCode);
    console.error('Details:', error.details);
  } else {
    console.error('Unknown error:', error);
  }
}
```

## TypeScript Support

Full TypeScript support with comprehensive type definitions:

```typescript
import type {
  MorbidConfig,
  MortalityRequest,
  MortalityResponse,
  InsurancePremiumResponse,
  ThermalPrediction,
  AgentRegistrationRequest,
  X402Config,
} from '@morbidcorp/ai';
```

## About Heir Ecosystem

Morbid AI is a core component of the **Heir ecosystem**, a comprehensive suite of blockchain and AI-powered solutions for estate planning, mortality prediction, and digital asset management. The Heir ecosystem includes:

- **Morbid AI** - Advanced mortality predictions and actuarial intelligence
- **X402 Protocol** - Decentralized agent economy for funeral services
- **HEIR Token** - Native utility token for the ecosystem
- **Estate Planning Tools** - Smart contract-based inheritance solutions

Learn more at [heir.io](https://heir.io)

## Links

- 🌐 [Website](https://morbid.ai)
- 🏛️ [Heir Ecosystem](https://heir.io)
- 📚 [Documentation](https://docs.morbid.ai)
- 💬 [Discord](https://discord.gg/morbidai)
- 🐦 [Twitter](https://twitter.com/morbidai)
- 📈 [HuggingFace Model](https://huggingface.co/MorbidCorp/morbid-ai)
- 🔗 [X402 Protocol](https://basescan.org/address/0x4edE90121555e88d04811Eb8109CEa584fC5063e)

## License

MIT © Heir PTE LTD Singapore

---

<div align="center">
  <strong>Built with 🖤 by the Morbid AI team</strong>
  <br>
  <em>Part of the Heir Ecosystem</em>
</div>