Examples
Copy-paste code examples for common Mappa SDK patterns.
Quick start​
Generate report from URL​
import { Mappa } from "@mappa-ai/mappa-node";
const mappa = new Mappa({
apiKey: process.env.MAPPA_API_KEY!,
});
const report = await mappa.reports.generateFromUrl({
url: "https://example.com/recording.mp3",
output: { template: "general_report" },
target: { strategy: "dominant" },
});
console.info(report.markdown);
Generate report from local file​
import { readFile } from "node:fs/promises";
const buffer = await readFile("./recording.mp3");
const report = await mappa.reports.generateFromFile({
file: buffer,
output: { template: "general_report" },
target: { strategy: "dominant" },
});
console.info(report.markdown);
Report templates​
General report​
const report = await mappa.reports.generateFromUrl({
url: "https://example.com/call.mp3",
output: { template: "general_report" },
target: { strategy: "dominant" },
});
Sales playbook​
const report = await mappa.reports.generateFromUrl({
url: "https://example.com/sales-call.mp3",
output: { template: "sales_playbook" },
target: { strategy: "dominant" },
});
Hiring report​
const report = await mappa.reports.generateFromUrl({
url: "https://example.com/interview.mp3",
output: {
template: "hiring_report",
templateParams: {
roleTitle: "Senior Software Engineer",
roleDescription: "Full-stack development with React and Node.js",
companyCulture: "Collaborative, innovative, work-life balance focused",
},
},
target: { strategy: "dominant" },
});
Profile alignment​
const report = await mappa.reports.generateFromUrl({
url: "https://example.com/support-call.mp3",
output: {
template: "profile_alignment",
templateParams: {
idealProfile: "Empathetic, patient, excellent listener, problem-solver",
},
},
target: { strategy: "dominant" },
});
Output formats​
Markdown​
const report = await mappa.reports.generateFromUrl({
url: "https://example.com/call.mp3",
output: { template: "sales_playbook" },
target: { strategy: "dominant" },
});
if (report.markdown) {
console.info(report.markdown);
}
JSON (structured data)​
const report = await mappa.reports.generateFromUrl({
url: "https://example.com/call.mp3",
output: { template: "sales_playbook" },
target: { strategy: "dominant" },
});
if (report.sections) {
for (const section of report.sections) {
console.info(`## ${section.section_title}`);
console.info(JSON.stringify(section.section_content, null, 2));
}
}
PDF​
const report = await mappa.reports.generateFromUrl({
url: "https://example.com/interview.mp3",
output: { template: "hiring_report" },
target: { strategy: "dominant" },
});
if (report.pdfUrl) {
console.info(`PDF URL: ${report.pdfUrl}`);
console.info(`Markdown fallback: ${report.markdown}`);
}
Hosted URL​
const report = await mappa.reports.generateFromUrl({
url: "https://example.com/call.mp3",
output: { template: "sales_playbook" },
target: { strategy: "dominant" },
});
if (report.reportUrl) {
console.info(`Share this link: ${report.reportUrl}`);
}
Speaker targeting​
Dominant speaker (default)​
const report = await mappa.reports.generateFromUrl({
url: "https://example.com/call.mp3",
output: { template: "general_report" },
target: { strategy: "dominant" },
});
Magic hint​
const report = await mappa.reports.generateFromUrl({
url: "https://example.com/interview.mp3",
output: { template: "hiring_report" },
target: {
strategy: "magic_hint",
hint: "the candidate being interviewed",
},
});
Time range​
const report = await mappa.reports.generateFromUrl({
url: "https://example.com/meeting.mp3",
output: { template: "general_report" },
target: {
strategy: "timerange",
timeRange: {
startSeconds: 120, // Start at 2 minutes
endSeconds: 600, // End at 10 minutes
},
},
});
Entity ID​
const report = await mappa.reports.generateFromUrl({
url: "https://example.com/call.mp3",
output: { template: "general_report" },
target: {
strategy: "entity_id",
entityId: "ent_abc123xyz",
},
});
Magic hint with fallback​
const report = await mappa.reports.generateFromUrl({
url: "https://example.com/interview.mp3",
output: { template: "hiring_report" },
target: {
strategy: "magic_hint",
hint: "the candidate",
onMiss: "fallback_dominant",
},
});
Persist entity ID​
const report = await mappa.reports.generateFromUrl({
url: "https://example.com/interview.mp3",
output: { template: "hiring_report" },
target: {
strategy: "magic_hint",
hint: "the candidate",
},
});
console.info(`Entity ID: ${report.entity?.id}`);
Production patterns​
Job creation with webhook​
const receipt = await mappa.reports.createJobFromUrl({
url: "https://example.com/call.mp3",
output: { template: "sales_playbook" },
entityLabel: "customer_456",
webhook: {
url: "https://myapp.com/webhooks/mappa",
headers: { "X-Webhook-Secret": process.env.WEBHOOK_SECRET! },
},
idempotencyKey: `report:customer_456:${Date.now()}`,
target: { strategy: "dominant" },
});
console.info(`Job created: ${receipt.jobId}`);
// Your webhook will be notified when complete
Streaming progress​
const receipt = await mappa.reports.createJobFromUrl({
url: "https://example.com/call.mp3",
output: { template: "general_report" },
target: { strategy: "dominant" },
});
for await (const event of receipt.handle!.stream()) {
if (event.type === "stage") {
const progress = Math.round(event.progress! * 100);
console.info(`${event.stage}: ${progress}%`);
}
if (event.type === "terminal") {
console.info("Complete!");
break;
}
}
const report = await receipt.handle!.report();
Polling with timeout​
import { JobFailedError } from "@mappa-ai/mappa-node";
const receipt = await mappa.reports.createJobFromUrl({
url: "https://example.com/call.mp3",
output: { template: "general_report" },
target: { strategy: "dominant" },
});
try {
const report = await receipt.handle!.wait({
timeoutMs: 10 * 60_000, // 10 minutes
onEvent: (event) => {
if (event.type === "stage") {
console.info(`Stage: ${event.stage}`);
}
},
});
console.info("Report ready:", report.id);
} catch (err) {
if (err instanceof JobFailedError) {
console.error(`Job ${err.jobId} failed: ${err.message}`);
} else {
throw err;
}
}
File management​
Upload file​
import { readFile } from "node:fs/promises";
const buffer = await readFile("./recording.mp3");
const upload = await mappa.files.upload({
file: buffer,
idempotencyKey: "upload:recording_001",
});
console.info(`Uploaded: ${upload.mediaId}`);
List files​
const page = await mappa.files.list({ limit: 50 });
for (const file of page.files) {
console.info(`${file.mediaId}: ${file.processingStatus}`);
}
if (page.hasMore) {
const nextPage = await mappa.files.list({
cursor: page.nextCursor,
limit: 50,
});
}
Iterate all files​
for await (const file of mappa.files.listAll({ limit: 100 })) {
if (file.processingStatus === "COMPLETED") {
console.info(`Ready: ${file.mediaId}`);
}
}
Batch upload​
import { readdir, readFile } from "node:fs/promises";
const files = await readdir("./recordings");
const uploads = await Promise.all(
files.map(async (filename) => {
const buffer = await readFile(`./recordings/${filename}`);
return mappa.files.upload({
file: buffer,
idempotencyKey: `batch:${filename}`,
});
})
);
console.info(`Uploaded ${uploads.length} files`);
Entity management​
List entities​
const page = await mappa.entities.list({ limit: 50 });
for (const entity of page.entities) {
console.info(`${entity.id}: ${entity.mediaCount} recordings`);
}
Update entity label​
await mappa.entities.update("ent_abc123", {
label: "interviewer:engineering:senior",
});
Clear entity label​
await mappa.entities.update("ent_abc123", { label: null });
Iterate all entities​
for await (const entity of mappa.entities.listAll()) {
console.info(`${entity.id}: ${entity.label ?? "(none)"}`);
}
Find high-activity entities​
const results = await mappa.entities.list({ limit: 100 });
for (const entity of results.entities) {
if (entity.mediaCount > 20) {
console.info(`${entity.id}: ${entity.mediaCount} recordings`);
}
}
Credits​
Check balance​
const balance = await mappa.credits.getBalance();
console.info(`Total: ${balance.balance}`);
console.info(`Reserved: ${balance.reserved}`);
console.info(`Available: ${balance.available}`);
if (balance.available < 100) {
console.warn("Low credits!");
}
List transactions​
for await (const tx of mappa.credits.listAllTransactions()) {
if (tx.type === "USAGE") {
console.info(`Job ${tx.jobId}: ${Math.abs(tx.amount)} credits`);
}
}
Job usage​
const usage = await mappa.credits.getJobUsage("job_abc123");
console.info(`Credits used: ${usage.creditsUsed}`);
console.info(`Discounted: ${usage.creditsDiscounted || 0}`);
console.info(`Net: ${usage.creditsNetUsed}`);
Pre-Flight check​
if (await mappa.credits.hasEnough(50)) {
const receipt = await mappa.reports.createJob({
media: { mediaId: "media_123" },
output: { template: "general_report" },
target: { strategy: "dominant" },
});
} else {
throw new Error("Insufficient credits");
}
Feedback​
Submit feedback​
await mappa.feedback.create({
reportId: "report_abc123",
rating: "thumbs_up",
comment: "Excellent analysis!",
});
Feedback with corrections​
await mappa.feedback.create({
reportId: "report_abc123",
rating: "thumbs_down",
comment: "Sentiment was off",
corrections: [
{
path: "$.insights.sentiment",
expected: "positive",
observed: "neutral",
},
],
});
Error handling​
Comprehensive error handling​
import {
AuthError,
ValidationError,
RateLimitError,
JobFailedError,
ApiError,
} from "@mappa-ai/mappa-node";
try {
const report = await mappa.reports.generateFromUrl({
url: "https://example.com/call.mp3",
output: { template: "general_report" },
target: { strategy: "dominant" },
});
console.info("Success:", report.id);
} catch (err) {
if (err instanceof AuthError) {
console.error("Check your API key");
} else if (err instanceof ValidationError) {
console.error("Invalid request:", err.details);
} else if (err instanceof RateLimitError) {
const delay = err.retryAfterMs || 60_000;
console.error(`Rate limited, retry after ${delay}ms`);
} else if (err instanceof JobFailedError) {
console.error(`Job ${err.jobId} failed:`, err.message);
} else if (err instanceof ApiError) {
console.error(`API error (${err.status}):`, err.message);
} else {
throw err;
}
}
Retry on failure​
async function generateWithRetry(url: string, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await mappa.reports.generateFromUrl({
url,
output: { template: "general_report" },
target: { strategy: "dominant" },
});
} catch (err) {
if (err instanceof RateLimitError && attempt < maxRetries) {
const delay = err.retryAfterMs || 5000 * attempt;
await new Promise((r) => setTimeout(r, delay));
continue;
}
throw err;
}
}
}
Advanced patterns​
Batch processing​
const urls = [
"https://example.com/call1.mp3",
"https://example.com/call2.mp3",
"https://example.com/call3.mp3",
];
// Create jobs in parallel
const receipts = await Promise.all(
urls.map((url, i) =>
mappa.reports.createJobFromUrl({
url,
output: { template: "sales_playbook" },
idempotencyKey: `batch:${Date.now()}:${i}`,
})
)
);
console.info(`Created ${receipts.length} jobs`);
// Wait for all to complete
const reports = await Promise.all(
receipts.map((r) => r.handle!.wait({ timeoutMs: 10 * 60_000 }))
);
console.info(`Completed ${reports.length} reports`);
Parallel job monitoring​
const jobIds = ["job_1", "job_2", "job_3"];
const results = await Promise.allSettled(
jobIds.map((id) => mappa.jobs.wait(id, { timeoutMs: 5 * 60_000 }))
);
for (const [i, result] of results.entries()) {
if (result.status === "fulfilled") {
console.info(`Job ${jobIds[i]}: ✓ succeeded`);
} else {
console.error(`Job ${jobIds[i]}: ✗ failed`, result.reason);
}
}
Workflow pipeline​
async function analyzeInterview(audioUrl: string, candidateName: string) {
// Step 1: Generate report
const report = await mappa.reports.generateFromUrl({
url: audioUrl,
output: {
template: "hiring_report",
templateParams: {
roleTitle: "Software Engineer",
roleDescription: "Full-stack development",
companyCulture: "Collaborative and innovative",
},
},
target: {
strategy: "magic_hint",
hint: "the candidate",
},
});
// Step 2: Store report
await db.reports.create({
id: report.id,
entityId: report.entity.id,
markdown: report.markdown,
});
// Step 3: Submit positive feedback
await mappa.feedback.create({
reportId: report.id,
rating: "thumbs_up",
comment: "Great analysis!",
});
// Step 4: Update entity label
await mappa.entities.update(report.entity.id, {
label: "interviewed",
});
return report;
}
Next steps​
- Production Guide - Best practices for production
- API Resources - Detailed resource documentation
- Error Handling - Advanced error patterns