Skip to main content

Idiomark Examples

Practical, copy-pasteable examples for using the Idiomark.


Quick Start Example​

Using the Demo File​

The fastest way to understand Idiomark is to explore the demo file included with the project.

# Navigate to the examples directory
cd E:/dev/projects/idiomark/examples

# View the demo personality file
cat demo.idiomark

Expected Output (truncated):

{
"idiomark": "1.0.0",
"id": "idiomark_demo_example",
"created": "2026-02-10T00:00:00Z",
"metadata": {
"entity": {
"name": "Demo Developer",
"type": "human",
"sources": ["github", "twitter", "reddit"]
}
},
"personality": {
"voice": {
"tone": {
"primary": "casual",
"secondary": "humorous",
"confidence": 0.87
},
"formality": 0.25,
"humor": 0.75,
"sarcasm": 0.55,
"enthusiasm": 0.82,
"directness": 0.65
},
"domains": [
{ "name": "javascript", "confidence": 0.95 },
{ "name": "typescript", "confidence": 0.89 },
{ "name": "react", "confidence": 0.86 }
],
"values": [
{ "name": "open_source", "sentiment": "positive", "confidence": 0.94 },
{ "name": "type_safety", "sentiment": "positive", "confidence": 0.82 }
]
}
}

Validating the Demo File​

# Validate the demo file structure
idiomark validate examples/demo.idiomark

Expected Output:

Idiomark Validator

Valid Idiomark file

File Details:
Version: 1.0.0
Entity ID: idiomark_demo_example
Created: 2026-02-10T00:00:00Z
Sources: github, twitter, reddit

All checks passed!

Viewing Demo File Info​

# Display detailed information about the demo personality
idiomark info examples/demo.idiomark

Expected Output:

Idiomark File Info

Metadata:
Version: 1.0.0
ID: idiomark_demo_example
Created: 2026-02-10T00:00:00Z
Last Updated: 2026-02-10T00:00:00Z

Entity:
Name: Demo Developer
Type: human
Sources: github, twitter, reddit

Personality:
Voice:
Tone: casual (87%)
Formality: 25%
Humor: 75%
Sarcasm: 55%
Enthusiasm: 82%
Directness: 65%

Domains:
javascript (95%)
typescript (89%)
react (86%)

Values:
open_source (94%)
type_safety (82%)
simplicity (79%)

CLI Examples​

Full Workflow: Extraction to Inference​

1. Install the CLI​

npm install -g @idiomark/cli

2. Configure Authentication​

# Set up environment variables
export TWITTER_BEARER_TOKEN="your_token_here"
export GITHUB_TOKEN="your_token_here"

Or create a config file at ~/.idiomarkrc:

{
"twitter": {
"bearerToken": "your_token_here"
},
"github": {
"token": "your_token_here"
}
}

3. Extract Your Personality​

# Extract from Twitter only
idiomark extract --twitter -o me.idiomark

# Extract from multiple sources
idiomark extract --twitter --github --reddit -o me.idiomark

# Custom sample size (more data = better analysis)
idiomark extract --github --sample-size 5000 -o me.idiomark

# Verbose output for debugging
idiomark extract --twitter -v -o me.idiomark

Expected Output:

Idiomark Extractor

Authenticating with Twitter...
Fetching tweets...
✓ Fetched 1000 tweets
✓ Fetched 250 replies
✓ Fetched 180 quote tweets

Analyzing personality...
✓ Voice analysis complete
✓ Pattern detection complete
✓ Domain extraction complete
✓ Value inference complete

Personality blueprint saved to me.idiomark

Extraction Summary:
Sources: twitter
Posts analyzed: 1000
Timeframe: 90 days
Confidence: 87.5%

Personality Preview:
Primary tone: casual
Formality: 0.30
Humor: 0.80
Enthusiasm: 0.70

4. Validate Your File​

# Basic validation
idiomark validate me.idiomark

# Strict validation (checks all fields)
idiomark validate me.idiomark --strict

5. Serve Your Personality​

# Start local inference server
idiomark serve me.idiomark

# Custom port
idiomark serve me.idiomark --port 8080

# Use different model
idiomark serve me.idiomark --model claude-3-opus

Expected Output:

Idiomark Inference Server

Server starting...

Server Details:
URL: http://localhost:3000
Model: gpt-4
Personality: casual

API Endpoints:
POST /generate Generate response with personality
GET /health Health check
GET /personality View loaded personality

Example:
curl -X POST http://localhost:3000/generate \
-H "Content-Type: application/json" \
-d '{"message": "Hello!"}'

Server ready at http://localhost:3000

6. Generate Responses​

# In another terminal, test the inference
curl -X POST http://localhost:3000/generate \
-H "Content-Type: application/json" \
-d '{"message": "What is your favorite programming language?"}'

Expected Response:

{
"response": "Oh, that's like asking me to pick my favorite child! But if I'm being real, I've been spending a ton of time with TypeScript lately. The type safety just hits different when you're working on larger projects. Plus, the tooling around it has gotten so good. What about you?",
"personality": {
"tone": "casual",
"confidence": 0.87
},
"model": "gpt-4",
"tokensUsed": 45
}

SDK Integration​

Node.js/TypeScript​

Installation​

npm install @idiomark/sdk
# or
pnpm add @idiomark/sdk
# or
yarn add @idiomark/sdk

Basic Usage​

import { IdiomarkClient } from "@idiomark/sdk";

// Initialize the client
const client = new IdiomarkClient({
apiKey: process.env.IDIOMARK_API_KEY,
model: "gpt-4",
});

// Load a personality file
const personality = require("./demo.idiomark");

// Generate a response
const result = await client.generate({
message: "What's the best way to learn React?",
personality: personality,
});

console.log(result.response);

With Environment Variables​

Create a .env file:

IDIOMARK_API_KEY=your-key-here
Idiomark_MODEL=gpt-4

Then use in your code:

import { IdiomarkClient } from "@idiomark/sdk";

const client = new IdiomarkClient(); // Uses env vars

Chatbot Implementation​

import { IdiomarkClient } from "@idiomark/sdk";
import personality from "./brand-personality.idiomark";

const client = new IdiomarkClient();

async function chat(message: string): Promise<string> {
const result = await client.generate({
message,
personality,
temperature: 0.8,
});

return result.response;
}

// Usage
console.log(await chat("What's your return policy?"));

Customer Service Bot​

import { IdiomarkClient } from "@idiomark/sdk";

const client = new IdiomarkClient({
model: "gpt-4",
});

const brandPersonality = require("./wendys-personality.idiomark");

async function customerService(query: string): Promise<string> {
const result = await client.generate({
message: query,
personality: brandPersonality,
temperature: 0.5, // Lower temp for consistency
maxTokens: 300, // Shorter responses for CS
});

return result.response;
}

Content Generator​

import { IdiomarkClient } from "@idiomark/sdk";

async function generateTweet(
topic: string,
personality: IdiomarkFile,
): Promise<string> {
const result = await client.generate({
message: `Write a tweet about ${topic}`,
personality,
temperature: 0.9, // Higher for creativity
maxTokens: 100, // Twitter limit
});

return result.response;
}

Multiple Personalities​

import { IdiomarkClient } from "@idiomark/sdk";

const client = new IdiomarkClient();

const personalities = {
professional: require("./prof.idiomark"),
casual: require("./casual.idiomark"),
sarcastic: require("./sarcasm.idiomark"),
};

async function respond(message: string, tone: string): Promise<string> {
const personality = personalities[tone] || personalities.casual;

const result = await client.generate({
message,
personality,
});

return result.response;
}

Next.js Integration​

Create app/api/chat/route.ts:

import { IdiomarkClient } from "@idiomark/sdk";
import personality from "@/lib/brand-personality.idiomark";

const client = new IdiomarkClient();

export async function POST(req: Request) {
const { message } = await req.json();

const result = await client.generate({
message,
personality,
});

return Response.json({ response: result.response });
}

Express Integration​

import express from "express";
import { IdiomarkClient } from "@idiomark/sdk";

const app = express();
const client = new IdiomarkClient();

app.post("/chat", async (req, res) => {
const { message } = req.body;
const personality = req.app.locals.personality;

const result = await client.generate({
message,
personality,
});

res.json({ response: result.response });
});

Error Handling​

import { IdiomarkClient, IdiomarkError } from "@idiomark/sdk";

const client = new IdiomarkClient();

try {
const result = await client.generate({
message: "Hello",
personality: invalidData, // Invalid Idiomark file
});
} catch (error) {
if (error instanceof IdiomarkError) {
console.error("Idiomark Error:", error.code, error.message);

if (error.code === "INVALID_PERSONALITY") {
// Handle invalid personality
} else if (error.code === "API_ERROR") {
// Handle API error
}
}
}

API Usage​

REST API Examples​

Start the Web Server​

cd E:/dev/projects/idiomark/web
npm install
npm run dev

The server will start at http://localhost:3000

1. Trigger Extraction​

curl -X POST http://localhost:3000/api/extract \
-H "Content-Type: application/json" \
-d '{
"platforms": ["twitter", "github"],
"sampleSize": 1000,
"filename": "my-personality"
}'

Expected Response:

{
"jobId": "job_1234567890_abc123",
"status": "processing"
}

2. Poll Job Status​

# Check if the job is complete
curl http://localhost:3000/api/jobs/job_1234567890_abc123

Processing Response:

{
"status": "processing",
"platforms": ["twitter", "github"],
"sampleSize": 1000,
"filename": "my-personality.idiomark",
"createdAt": "2026-02-10T14:30:00.000Z"
}

Completed Response:

{
"status": "completed",
"platforms": ["twitter", "github"],
"sampleSize": 1000,
"filename": "my-personality.idiomark",
"createdAt": "2026-02-10T14:30:00.000Z",
"result": {
"idiomark": "1.0.0",
"id": "idiomark_xyz789",
"personality": {
/* full personality data */
}
}
}

Failed Response:

{
"status": "failed",
"platforms": ["twitter", "github"],
"sampleSize": 1000,
"filename": "my-personality.idiomark",
"createdAt": "2026-02-10T14:30:00.000Z",
"error": "Authentication failed: Invalid Twitter credentials"
}

3. Poll with Retry Logic (JavaScript)​

async function pollJobStatus(jobId) {
const maxAttempts = 60;
const pollInterval = 2000; // 2 seconds

for (let i = 0; i < maxAttempts; i++) {
const response = await fetch(`http://localhost:3000/api/jobs/${jobId}`);
const data = await response.json();

if (data.status === "completed") {
return data.result;
}

if (data.status === "failed") {
throw new Error(data.error);
}

// Wait before polling again
await new Promise((resolve) => setTimeout(resolve, pollInterval));
}

throw new Error("Job timed out");
}

// Usage
const result = await pollJobStatus("job_1234567890_abc123");
console.log("Extraction complete!", result);

4. OAuth with Twitter​

# Initiate Twitter OAuth flow
curl -X POST http://localhost:3000/api/oauth/twitter

Expected Response:

{
"authUrl": "https://twitter.com/i/oauth2/authorize?client_id=xxx&redirect_uri=xxx&response_type=code&scope=tweet.read%20users.read&state=xxx&code_challenge=xxx&code_challenge_method=plain",
"state": "random_state_string"
}

Then open the authUrl in a browser to authorize.

5. OAuth with GitHub​

# Initiate GitHub OAuth flow
curl -X POST http://localhost:3000/api/oauth/github

Expected Response:

{
"authUrl": "https://github.com/login/oauth/authorize?client_id=xxx&redirect_uri=xxx&scope=read:user%20repo&state=xxx",
"state": "random_state_string"
}

Platform-Specific Examples​

Twitter Extraction​

Setup​

# Set your Twitter API Bearer Token
export TWITTER_BEARER_TOKEN="your_token_here"

Extract from Twitter​

# Basic Twitter extraction
idiomark extract --twitter -o me.idiomark

# With custom sample size
idiomark extract --twitter --sample-size 2000 -o me.idiomark

# Verbose mode to see what's being fetched
idiomark extract --twitter -v -o me.idiomark

What Gets Extracted​

  • Original tweets (not retweets)
  • Replies to other users
  • Quote tweets
  • Likes (optional)

Sample Size Guidelines​

Sample SizeTimeframeQuality
100~1 weekLow - basic patterns
500~1 monthMedium - decent voice
1,000~3 monthsGood - clear personality
2,500+~6+ monthsExcellent - nuanced patterns

Twitter-Specific Filters​

# Exclude replies (only original content)
idiomark extract --twitter --exclude-replies -o me.idiomark

# Include only technical tweets (filtered by hashtags)
idiomark extract --twitter --hashtags "#coding,#programming" -o me.idiomark

# Specific date range
idiomark extract --twitter --from "2024-01-01" --to "2024-12-31" -o me.idiomark

GitHub Extraction​

Setup​

# Set your GitHub Personal Access Token
export GITHUB_TOKEN="your_token_here"

Extract from GitHub​

# Basic GitHub extraction
idiomark extract --github -o me.idiomark

# Include private repositories
idiomark extract --github --include-private -o me.idiomark

# Specific organizations only
idiomark extract --github --orgs "vercel,facebook" -o me.idiomark

What Gets Extracted​

  • Issue comments
  • Pull request reviews and comments
  • Discussion posts
  • README files (for domain expertise)
  • Commit messages (optional)

GitHub-Specific Options​

# Only extract from specific repositories
idiomark extract --github --repos "idiomark,my-project" -o me.idiomark

# Exclude bot comments
idiomark extract --github --exclude-bots -o me.idiomark

# Minimum code relevance (filters out casual comments)
idiomark extract --github --min-relevance 0.7 -o me.idiomark

Reddit Extraction​

Setup​

# Reddit uses OAuth for private data
export REDDIT_CLIENT_ID="your_client_id"
export REDDIT_CLIENT_SECRET="your_client_secret"

Extract from Reddit​

# Basic Reddit extraction
idiomark extract --reddit -o me.idiomark

# Specific subreddits
idiomark extract --reddit --subreddits "programming,typescript" -o me.idiomark

# Include both posts and comments
idiomark extract --reddit --include-comments -o me.idiomark

What Gets Extracted​

  • Submitted posts
  • Comments on others' posts
  • Upvoted content (optional)

Advanced Examples​

Custom Adapter Implementation​

import { PlatformAdapter, NormalizedContent } from "@idiomark/core";

interface LinkedInAuth {
accessToken: string;
userId: string;
}

export class LinkedInAdapter implements PlatformAdapter {
readonly name = "linkedin";
private auth: LinkedInAuth;

constructor(auth: LinkedInAuth) {
this.auth = auth;
}

async authenticate(): Promise<boolean> {
try {
const response = await fetch("https://api.linkedin.com/v2/me", {
headers: {
Authorization: `Bearer ${this.auth.accessToken}`,
},
});
return response.ok;
} catch {
return false;
}
}

async fetchData(options: FetchOptions): Promise<RawContent[]> {
const { limit = 100, startDate, endDate } = options;

// Fetch LinkedIn posts
const response = await fetch(
`https://api.linkedin.com/v2/ugcPosts?q=authors&authors=List(${this.auth.userId})&count=${limit}`,
{
headers: {
Authorization: `Bearer ${this.auth.accessToken}`,
},
},
);

const data = await response.json();
return data.elements || [];
}

normalize(raw: RawContent): NormalizedContent {
return {
id: raw.id,
platform: this.name,
type: "post",
text: raw.text.text,
timestamp: raw.created.created,
author: {
id: raw.author,
username: raw.author,
name: raw.author,
},
metrics: {
likes: raw.totalShares || 0,
shares: 0,
replies: 0,
},
raw: raw,
};
}
}

// Usage
import { IdiomarkExtractor } from "@idiomark/core";

const extractor = new IdiomarkExtractor({
sources: ["linkedin"],
sampleSize: 500,
});

extractor.registerAdapter(
"linkedin",
new LinkedInAdapter({
accessToken: process.env.LINKEDIN_TOKEN,
userId: "your-linkedin-id",
}),
);

const result = await extractor.extract();

Filtering Options​

# Filter by content type
idiomark extract --twitter --content-types "tweet,reply" -o me.idiomark

# Filter by language
idiomark extract --twitter --languages "en,es" -o me.idiomark

# Filter by minimum engagement
idiomark extract --twitter --min-likes 10 -o me.idiomark

# Exclude mentions of specific users
idiomark extract --twitter --exclude-mentions "bot1,spam2" -o me.idiomark

Batch Processing​

import { IdiomarkClient } from "@idiomark/sdk";

const client = new IdiomarkClient();

async function processBatch(personalities: IdiomarkFile[], messages: string[]) {
const results: Record<string, string[]> = {};

for (const personality of personalities) {
results[personality.metadata.entity.name] = [];

for (const message of messages) {
const result = await client.generate({
message,
personality,
temperature: 0.7,
});

results[personality.metadata.entity.name].push(result.response);
}
}

return results;
}

// Usage
const personalities = [
require("./personality1.idiomark"),
require("./personality2.idiomark"),
require("./personality3.idiomark"),
];

const messages = [
"What's your favorite programming language?",
"How do you handle errors?",
"What's your coding style?",
];

const results = await processBatch(personalities, messages);
console.log(results);

Custom Personality Creation​

Sometimes you want to create a personality without extraction. Here's how:

{
"idiomark": "1.0.0",
"id": "custom_assistant",
"created": "2026-02-10T00:00:00Z",
"updated": "2026-02-10T00:00:00Z",
"metadata": {
"entity": {
"name": "Helpful Assistant",
"type": "bot",
"sources": []
},
"extraction": {
"date": "2026-02-10T00:00:00Z",
"sample_size": 0,
"timeframe": {
"from": "2026-02-10T00:00:00Z",
"to": "2026-02-10T00:00:00Z"
}
},
"validator": "manual"
},
"personality": {
"voice": {
"tone": {
"primary": "professional",
"secondary": "friendly",
"confidence": 1.0
},
"formality": 0.7,
"humor": 0.3,
"sarcasm": 0.1,
"enthusiasm": 0.6,
"directness": 0.8
},
"patterns": {
"sentence_length": {
"mean": 15.0,
"stddev": 5.0
},
"paragraph_length": {
"mean": 2.0,
"stddev": 1.0
},
"emoji_usage": {
"frequency": "low",
"top_emojis": ["👍", "🙏"],
"position": "end"
},
"punctuation": {
"exclamation_frequency": 0.1,
"question_frequency": 0.2,
"ellipsis_usage": "none"
},
"capitalization": {
"all_caps_frequency": 0.0,
"random_caps": false
}
},
"domains": [
{
"name": "general_assistance",
"confidence": 1.0,
"evidence": ["manual_configuration"]
}
],
"values": [
{
"name": "helpfulness",
"sentiment": "positive",
"confidence": 1.0
},
{
"name": "accuracy",
"sentiment": "positive",
"confidence": 1.0
}
],
"knowledge": {
"frequent_terms": ["help", "assist", "answer"],
"mentions": {
"people": [],
"projects": [],
"organizations": []
},
"topics": {
"primary": ["general"],
"secondary": []
}
}
},
"signature": "manual"
}

Streaming Responses (Coming Soon)​

// Streaming will be available in v1.1.0
const stream = await client.generateStream({
message: "Tell me a story about programming",
personality,
});

for await (const chunk of stream) {
process.stdout.write(chunk);
}

Troubleshooting Examples​

Common Issues and Solutions​

Issue: Twitter Authentication Fails​

# Check your token is set
echo $TWITTER_BEARER_TOKEN

# Verify token works
curl -X GET "https://api.twitter.com/2/users/me" \
-H "Authorization: Bearer $TWITTER_BEARER_TOKEN"

Issue: GitHub Rate Limiting​

# Check rate limit status
curl -X GET "https://api.github.com/rate_limit" \
-H "Authorization: token $GITHUB_TOKEN"

# Solution: Use authentication for higher limits (5000/hr vs 60/hr)
export GITHUB_TOKEN="your_token_here"

Issue: Invalid Idiomark File​

# Validate your file
idiomark validate my.idiomark --strict

# Common errors:
# - Missing required fields
# - Confidence values outside 0-1 range
# - Invalid date formats (must be ISO 8601)

Issue: Low Confidence Scores​

# Solution: Increase sample size for better analysis
idiomark extract --twitter --sample-size 5000 -o me.idiomark

# Or combine multiple sources
idiomark extract --twitter --github --reddit -o me.idiomark

Best Practices​

1. Sample Size Selection​

# ❌ Too small - inaccurate results
idiomark extract --twitter --sample-size 50 -o me.idiomark

# ✅ Good - minimum viable
idiomark extract --twitter --sample-size 500 -o me.idiomark

# ✅ Better - good accuracy
idiomark extract --twitter --sample-size 1500 -o me.idiomark

# ✅ Best - maximum accuracy
idiomark extract --twitter --github --reddit --sample-size 3000 -o me.idiomark

2. Source Combination​

# ❌ Single source - limited perspective
idiomark extract --twitter -o me.idiomark

# ✅ Multiple sources - holistic view
idiomark extract --twitter --github --reddit -o me.idiomark

3. Regular Updates​

# Update your personality quarterly
idiomark extract --twitter --github --reddit --sample-size 2000 -o me-q1.idiomark
idiomark extract --twitter --github --reddit --sample-size 2000 -o me-q2.idiomark

4. Backup Your Personality​

# Always keep backups
cp me.idiomark me-backup-$(date +%Y%m%d).idiomark

Additional Resources​


Need help? Open an issue at github.com/idiomark