Idiomark - API Documentation
Version: 1.0.0 Last Updated: 2026-02-11 Maintainer: Core Engineering Team
Table of Contents
Overview
The Idiomark exposes three primary APIs:
- Core Library API - TypeScript/JavaScript library for programmatic access
- Adapter API - Platform adapter interface for extending support
- CLI API - Command-line interface for terminal usage
- Web API - HTTP endpoints for web applications
Base URL
- Production:
https://api.idiomark.org - Staging:
https://staging-api.idiomark.org - Development:
http://localhost:3000
Authentication
Most endpoints require authentication:
# Bearer token authentication
curl -H "Authorization: Bearer YOUR_TOKEN" https://api.idiomark.org/v1/extract
# API key in query string (not recommended for production)
curl https://api.idiomark.org/v1/extract?apiKey=YOUR_TOKEN
Core API
The core library (@idiomark/core) provides the main extraction and analysis functionality.
Installation
npm install @idiomark/core
pnpm add @idiomark/core
yarn add @idiomark/core
IdiomarkExtractor
Main class for extracting personality from platforms.
Constructor
import { IdiomarkExtractor } from '@idiomark/core';
const extractor = new IdiomarkExtractor(
options: ExtractionOptions,
analysisOptions?: AnalysisOptions
);
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
options | ExtractionOptions | Yes | Extraction configuration |
analysisOptions | AnalysisOptions | No | LLM analysis configuration |
ExtractionOptions:
interface ExtractionOptions {
sources: string[]; // Platform names to extract from
sampleSize: number; // Number of items to fetch per platform
verbose?: boolean; // Enable verbose logging (default: false)
auth?: Record<string, any>; // Platform-specific authentication
startDate?: Date; // Start of date range
endDate?: Date; // End of date range
}
AnalysisOptions:
interface AnalysisOptions {
provider?: 'anthropic' | 'openai' | 'mock'; // LLM provider (default: 'mock')
apiKey?: string; // API key (or use ANTHROPIC_API_KEY / OPENAI_API_KEY)
model?: string; // Model name (default: auto-detected)
maxTokens?: number; // Max tokens in response (default: 8192)
chunkSize?: number; // Chunk size for large texts (default: 15000)
cache?: boolean; // Enable caching (default: true)
endpoint?: string; // Custom API endpoint for OpenAI-compatible APIs
}
Methods
extract()
Main extraction method - fetches from platforms and analyzes.
async extract(): Promise<IdiomarkResult>
Returns: IdiomarkResult containing the personality profile and metadata.
Example:
const extractor = new IdiomarkExtractor({
sources: ['github', 'twitter'],
sampleSize: 500,
verbose: true,
auth: {
github: { token: process.env.GITHUB_TOKEN },
twitter: { bearerToken: process.env.TWITTER_BEARER_TOKEN }
}
}, {
provider: 'anthropic',
model: 'claude-3-5-sonnet-20241022'
});
const result = await extractor.extract();
console.log(result.personality);
// Save to file
await result.save('./output');
Error Handling:
try {
const result = await extractor.extract();
} catch (error) {
if (error.message.includes('Authentication failed')) {
console.error('Invalid credentials');
} else if (error.message.includes('rate limit')) {
console.error('Rate limit exceeded');
}
}
extractFromContent()
Extract personality from pre-normalized content.
async extractFromContent(content: NormalizedContent[]): Promise<IdiomarkResult>
Parameters:
| Parameter | Type | Description |
|---|---|---|
content | NormalizedContent[] | Pre-normalized content items |
Example:
const content = [
{
id: '1',
platform: 'github',
type: 'post',
text: 'This is a sample message.',
timestamp: '2025-01-15T10:00:00Z',
author: { id: '123', username: 'user', name: 'User' }
}
];
const result = await extractor.extractFromContent(content);
extractFromText()
Extract personality from raw text strings.
async extractFromText(
texts: string[],
metadata?: {
platform?: string;
timestamps?: string[];
}
): Promise<IdiomarkResult>
Example:
const texts = [
'I love open source software!',
'TypeScript is my favorite language.',
'Check out this cool project.'
];
const result = await extractor.extractFromText(texts, {
platform: 'github',
timestamps: [
'2025-01-01T10:00:00Z',
'2025-01-02T10:00:00Z',
'2025-01-03T10:00:00Z'
]
});
PersonalityAnalyzer
Lower-level class for analyzing text directly.
Constructor
import { PersonalityAnalyzer } from '@idiomark/core';
const analyzer = new PersonalityAnalyzer(options?: AnalysisOptions);
Methods
analyze()
Analyze text samples to extract personality.
async analyze(samples: TextSample[]): Promise<AnalysisResult>
TextSample:
interface TextSample {
id: string;
text: string;
timestamp?: string;
platform?: string;
}
Example:
const samples = [
{ id: '1', text: 'Hello world!', platform: 'github' },
{ id: '2', text: 'How are you?', platform: 'twitter' }
];
const result = await analyzer.analyze(samples);
console.log(result.personality);
console.log(result.confidence);
console.log(result.metadata);
refine()
Refine an existing personality with additional context.
async refine(
currentPersonality: Personality,
additionalContext: string
): Promise<Personality>
Example:
const refined = await analyzer.refine(
result.personality,
'User recently became very interested in AI and machine learning.'
);
validate()
Validate an analysis for quality.
async validate(personality: Personality): Promise<{
valid: boolean;
issues: string[];
confidence: number;
recommendations: string[];
}>
Example:
const validation = await analyzer.validate(result.personality);
if (!validation.valid) {
console.error('Issues:', validation.issues);
}
console.log('Recommendations:', validation.recommendations);
clearCache()
Clear the internal analysis cache.
clearCache(): void
Convenience Functions
extractFromTextString()
Extract from a single text string.
import { extractFromTextString } from '@idiomark/core';
const result = await extractFromTextString(
'This is a sample text to analyze.',
{ verbose: true }
);
extractFromTextStrings()
Extract from multiple text strings.
import { extractFromTextStrings } from '@idiomark/core';
const result = await extractFromTextStrings(
['Text 1', 'Text 2', 'Text 3'],
{ timestamps: ['2025-01-01', '2025-01-02', '2025-01-03'] }
);
extractFromPlatforms()
Extract from multiple platforms with auto-configuration.
import { extractFromPlatforms } from '@idiomark/core';
const result = await extractFromPlatforms({
sources: ['github', 'twitter'],
auth: {
github: { token: process.env.GITHUB_TOKEN },
twitter: { bearerToken: process.env.TWITTER_TOKEN }
},
sampleSize: 1000,
startDate: new Date('2025-01-01'),
endDate: new Date('2025-02-01'),
verbose: true
});
analyzeText()
Direct text analysis utility.
import { analyzeText } from '@idiomark/core';
// Single text
const result1 = await analyzeText('Sample text to analyze');
// Multiple texts
const result2 = await analyzeText(['Text 1', 'Text 2']);
Platform Utilities
import { getSupportedPlatforms, isPlatformSupported, getAdapterPackage } from '@idiomark/core';
// Get all supported platforms
const platforms = getSupportedPlatforms();
// { github: '@idiomark/adapter-github', twitter: '@idiomark/adapter-twitter', ... }
// Check if platform is supported
if (isPlatformSupported('github')) {
// ...
}
// Get adapter package name
const packageName = getAdapterPackage('github');
// '@idiomark/adapter-github'
Adapter API
Platform adapters extend the BaseAdapter class to provide platform-specific functionality.
BaseAdapter
Abstract base class providing common infrastructure.
Abstract Methods (Must Implement)
fetchContent()
Fetch raw content from the platform.
protected abstract fetchContent(
options: FetchOptions
): Promise<RawContent[]>
FetchOptions:
interface FetchOptions {
limit?: number; // Max items to fetch
startDate?: Date; // Start of date range
endDate?: Date; // End of date range
includeReplies?: boolean; // Include reply content
includeReactions?: boolean; // Include reaction/like data
}
RawContent:
interface RawContent {
id: string; // Unique identifier
type: string; // Content type (platform-specific)
text: string; // Main text content
created_at: string; // ISO timestamp
author: {
id: string;
username: string;
name: string;
};
[key: string]: any; // Additional platform-specific fields
}
Example:
class GitHubAdapter extends BaseAdapter {
protected async fetchContent(options: FetchOptions): Promise<RawContent[]> {
const response = await fetch(
`https://api.github.com/users/${this.username}/events`
);
const events = await response.json();
return events.map(event => ({
id: event.id,
type: event.type,
text: event.payload?.commit?.message || '',
created_at: event.created_at,
author: {
id: event.actor.id.toString(),
username: event.actor.login,
name: event.actor.display_login
}
}));
}
}
normalize()
Transform raw content to normalized format.
protected abstract normalize(raw: RawContent): NormalizedContent;
NormalizedContent:
interface NormalizedContent {
id: string; // Unique identifier
platform: string; // Platform name (e.g., 'github')
type: 'post' | 'comment' | 'reply'; // Content type
text: string; // Main text content
timestamp: string; // ISO timestamp
author: {
id: string;
username: string;
name: string;
};
metrics?: { // Optional engagement metrics
likes?: number;
shares?: number;
replies?: number;
};
metadata?: Record<string, any>; // Additional metadata
raw: any; // Original raw data
}
Example:
protected normalize(raw: RawContent): NormalizedContent {
return {
id: raw.id,
platform: 'github',
type: 'post',
text: raw.text,
timestamp: raw.created_at,
author: raw.author,
metrics: {
likes: raw.reactions?.total_count || 0
},
metadata: {
repo: raw.repo?.name,
eventType: raw.type
},
raw
};
}
High-Level Methods (Built-in)
extract()
Complete extraction pipeline with caching, rate limiting, retry.
async extract(options: FetchOptions): Promise<NormalizedContent[]>
Pipeline:
- Validate authentication
- Check cache
- Rate limit (throttle)
- Fetch with retry
- Normalize
- Cache result
- Emit completion event
Usage: Call this method instead of fetchContent() to get all infrastructure automatically.
authenticate()
Verify authentication credentials.
async authenticate(): Promise<boolean>
healthCheck()
Check adapter health status.
async healthCheck(): Promise<{
healthy: boolean;
latency?: number;
error?: string;
}>
getMetrics()
Get adapter performance metrics.
getMetrics(): {
requests: number;
cacheHits: number;
cacheMisses: number;
retries: number;
errors: number;
avgLatency: number;
}
reset()
Reset adapter state (clear caches, counters).
async reset(): Promise<void>
dispose()
Cleanup resources (close connections, etc.).
async dispose(): Promise<void>
Configuration
interface AdapterConfig {
name: string; // Adapter name
auth?: AuthConfig; // Authentication configuration
cache?: {
enabled: boolean;
ttl: number; // Time-to-live in ms
maxSize: number; // Max cache entries
};
rateLimit?: {
requests: number; // Max requests
window: number; // Time window in ms
};
retry?: {
maxAttempts: number;
baseDelay: number; // Base delay in ms
maxDelay: number; // Max delay in ms
};
}
Event Emitter
Adapters emit events during operation:
adapter.on('fetch:start', (options) => {});
adapter.on('fetch:complete', (content) => {});
adapter.on('fetch:error', (error) => {});
adapter.on('cache:hit', (key) => {});
adapter.on('cache:miss', (key) => {});
adapter.on('rate-limit', (info) => {});
adapter.on('retry', (attempt) => {});
CLI API
Command-line interface for terminal usage.
Installation
npm install -g @idiomark/cli
pnpm add -g @idiomark/cli
Commands
idiomark extract
Extract personality from platforms.
idiomark extract [options]
Options:
| Option | Short | Description | Default |
|---|---|---|---|
--github | -g | Include GitHub | false |
--twitter | -t | Include Twitter | false |
--reddit | -r | Include Reddit | false |
--sample-size | -n | Number of items | 100 |
--output | -o | Output directory | ./idiomark-output |
--verbose | -v | Verbose logging | false |
--start-date | Start date | - | |
--end-date | End date | - |
Examples:
# Extract from GitHub
idiomark extract --github --sample-size 500 --output ./profiles
# Extract from multiple sources
idiomark extract --github --twitter --sample-size 1000
# With date range
idiomark extract --github --start-date 2025-01-01 --end-date 2025-02-01
# Verbose mode
idiomark extract --github --verbose
idiomark validate
Validate a Idiomark file.
idiomark validate <file> [options]
Options:
| Option | Short | Description |
|---|---|---|
--strict | -s | Enable strict validation |
--format | -f | Output format (json, text) |
Examples:
# Validate file
idiomark validate profile.idiomark.json
# Strict validation with JSON output
idiomark validate profile.idiomark.json --strict --format json
Exit Codes:
0- Valid1- Invalid2- Error
idiomark serve
Serve a Idiomark file via HTTP for inference.
idiomark serve <file> [options]
Options:
| Option | Short | Description | Default |
|---|---|---|---|
--port | -p | Port number | 3000 |
--model | -m | LLM model | gpt-4 |
--host | -h | Host address | localhost |
Examples:
# Serve on default port
idiomark serve profile.idiomark.json
# Custom port and model
idiomark serve profile.idiomark.json --port 8080 --model claude-3-5-sonnet
idiomark info
Display information about a Idiomark file.
idiomark info <file>
Example:
idiomark info profile.idiomark.json
# Output:
# ID: idiomark_abc123...
# Version: 1.0.0
# Created: 2025-02-11T10:00:00Z
# Sample Size: 500
# Sources: github, twitter
# Confidence: 0.87
idiomark adapter
Manage adapters.
idiomark adapter <command> [options]
Commands:
create- Create a new adaptervalidate- Validate an adaptertest- Test an adapterlist- List available adaptersinfo- Show adapter information
Examples:
# List adapters
idiomark adapter list
# Create new adapter
idiomark adapter create reddit --template rest --auth oauth2
# Validate adapter
idiomark adapter validate ./my-adapter
# Test adapter
idiomark adapter test ./my-adapter --auth token=xxx
Environment Variables
# LLM Provider Keys
export ANTHROPIC_API_KEY="sk-ant-..."
export OPENAI_API_KEY="sk-..."
# Platform Keys
export GITHUB_TOKEN="ghp_..."
export TWITTER_BEARER_TOKEN="AAAAA..."
export REDDIT_CLIENT_ID="..."
export REDDIT_CLIENT_SECRET="..."
# Idiomark Configuration
export Idiomark_CACHE_DIR="~/.idiomark/cache"
export Idiomark_LOG_LEVEL="debug"
Web API
HTTP endpoints for web applications.
Base URL
https://api.idiomark.org/v1
Authentication
All endpoints require Bearer token authentication:
curl -H "Authorization: Bearer YOUR_TOKEN" \
https://api.idiomark.org/v1/extract
Endpoints
POST /extract
Start an extraction job.
POST /v1/extract
Request Body:
{
"sources": ["github", "twitter"],
"sampleSize": 500,
"auth": {
"github": { "token": "ghp_xxx" },
"twitter": { "bearerToken": "AAAAA..." }
},
"startDate": "2025-01-01T00:00:00Z",
"endDate": "2025-02-01T00:00:00Z"
}
Response:
{
"jobId": "job_abc123...",
"status": "processing",
"estimatedTime": 45
}
GET /extract/:jobId
Get extraction job status.
GET /v1/extract/:jobId
Response (Processing):
{
"jobId": "job_abc123...",
"status": "processing",
"progress": 0.6,
"currentStep": "Analyzing content...",
" ETA": 18
}
Response (Complete):
{
"jobId": "job_abc123...",
"status": "complete",
"result": {
"file": { /* IdiomarkFile */ },
"confidence": 0.87
}
}
POST /analyze
Analyze text directly.
POST /v1/analyze
Request Body:
{
"texts": ["Sample text 1", "Sample text 2"],
"provider": "anthropic",
"model": "claude-3-5-sonnet-20241022"
}
Response:
{
"personality": { /* Personality */ },
"confidence": 0.85,
"metadata": {
"samplesAnalyzed": 2,
"totalWords": 15,
"provider": "anthropic",
"model": "claude-3-5-sonnet-20241022"
}
}
POST /validate
Validate a Idiomark file.
POST /v1/validate
Request Body:
{
"file": { /* IdiomarkFile */ },
"strict": true
}
Response:
{
"valid": true,
"version": "1.0.0",
"id": "idiomark_abc123...",
"created": "2025-02-11T10:00:00Z",
"sources": ["github"],
"errors": []
}
GET /adapters
List available adapters.
GET /v1/adapters
Response:
{
"adapters": [
{
"name": "github",
"version": "1.0.0",
"status": "stable",
"category": "development",
"platform": "github.com"
}
]
}
GET /adapters/:name
Get adapter information.
GET /v1/adapters/:name
Response:
{
"name": "github",
"version": "1.0.0",
"package": "@idiomark/adapter-github",
"platform": "github.com",
"website": "https://github.com",
"docs": "https://docs.github.com",
"auth": ["bearer_token"],
"rateLimit": {
"authenticated": 5000,
"unauthenticated": 60,
"window": "hour"
},
"status": "stable",
"category": "development",
"tags": ["git", "code", "development"]
}
Error Responses
All endpoints return consistent error responses:
{
"error": {
"code": "INVALID_AUTH",
"message": "Invalid authentication credentials",
"details": {}
}
}
Error Codes:
| Code | Description |
|---|---|
INVALID_AUTH | Invalid or missing authentication |
RATE_LIMITED | Rate limit exceeded |
INVALID_REQUEST | Invalid request parameters |
PLATFORM_ERROR | Platform API error |
EXTRACTION_FAILED | Extraction failed |
VALIDATION_ERROR | Validation failed |
Type Definitions
IdiomarkFile
Complete personality profile file.
interface IdiomarkFile {
idiomark: string; // Version (semver)
id: string; // Unique identifier (idiomark_*)
created: string; // ISO timestamp
updated: string; // ISO timestamp
metadata: IdiomarkMetadata;
personality: Personality;
signature?: string; // Digital signature
}
IdiomarkMetadata
Metadata about the profile.
interface IdiomarkMetadata {
entity: {
name?: string;
type: 'human' | 'brand' | 'bot' | 'fictional';
sources: string[];
};
extraction: {
date: string;
sample_size: number;
timeframe: {
from: string;
to: string;
};
};
validator?: string;
}
Personality
Core personality analysis.
interface Personality {
voice: Voice;
patterns: Patterns;
domains: Domain[];
values: Value[];
knowledge: Knowledge;
}
Voice
Voice characteristics.
interface Voice {
tone: {
primary: string;
secondary?: string;
confidence: number; // 0.0 - 1.0
};
formality: number; // 0.0 - 1.0
humor: number; // 0.0 - 1.0
sarcasm: number; // 0.0 - 1.0
enthusiasm: number; // 0.0 - 1.0
directness: number; // 0.0 - 1.0
}
Patterns
Communication patterns.
interface Patterns {
sentence_length: {
mean: number;
stddev: number;
};
paragraph_length?: {
mean: number;
stddev: number;
};
emoji_usage: {
frequency: 'none' | 'low' | 'medium' | 'high';
top_emojis: string[];
position?: 'start' | 'end' | 'mixed';
};
punctuation: {
exclamation_frequency: number;
question_frequency: number;
ellipsis_usage: 'none' | 'low' | 'medium' | 'high';
};
capitalization?: {
all_caps_frequency: number;
random_caps: boolean;
};
}
Domain
Domain expertise.
interface Domain {
name: string;
confidence: number; // 0.0 - 1.0
evidence?: string[]; // Supporting quotes
}
Value
Values and beliefs.
interface Value {
name: string;
sentiment: 'positive' | 'negative' | 'neutral';
confidence: number; // 0.0 - 1.0
}
Knowledge
Knowledge and topics.
interface Knowledge {
frequent_terms: string[];
mentions: {
people?: string[];
projects?: string[];
organizations?: string[];
};
topics: {
primary: string[];
secondary?: string[];
};
}
Examples
Complete Workflow
import {
IdiomarkExtractor,
extractFromTextString,
analyzeText
} from '@idiomark/core';
// 1. Extract from platforms
const extractor = new IdiomarkExtractor({
sources: ['github', 'twitter'],
sampleSize: 500,
auth: {
github: { token: process.env.GITHUB_TOKEN },
twitter: { bearerToken: process.env.TWITTER_TOKEN }
}
}, {
provider: 'anthropic',
cache: true
});
const result = await extractor.extract();
// 2. Save result
await result.save('./profiles');
// 3. Use personality
console.log(result.personality.voice.tone.primary);
console.log(result.personality.domains);
// 4. Quick analysis from text
const quickResult = await extractFromTextString(
'I love building open source software!'
);
// 5. Direct analysis
const analysis = await analyzeText([
'Text sample 1',
'Text sample 2'
]);
Custom Adapter
import { BaseAdapter, AdapterConfig } from '@idiomark/core';
class MyPlatformAdapter extends BaseAdapter {
constructor(config: AdapterConfig) {
super(config);
}
protected async fetchContent(options: FetchOptions): Promise<RawContent[]> {
// Fetch from your platform
const response = await fetch('https://api.myplatform.com/posts', {
headers: this.getAuthHeaders()
});
const data = await response.json();
return data.posts.map(post => ({
id: post.id,
type: 'post',
text: post.content,
created_at: post.created_at,
author: {
id: post.author.id,
username: post.author.username,
name: post.author.name
}
}));
}
protected normalize(raw: RawContent): NormalizedContent {
return {
id: raw.id,
platform: 'myplatform',
type: 'post',
text: raw.text,
timestamp: raw.created_at,
author: raw.author,
raw
};
}
}
// Use the adapter
const adapter = new MyPlatformAdapter({
name: 'myplatform',
auth: { apiKey: 'xxx' }
});
const content = await adapter.extract({ limit: 100 });
For more information, see: