Skip to content

Tempo Plugin

@tempo-kit/plugin-ai ​

npm version npm peer dependency version License TypeScript Ready

Tempo community plugin for LLM-powered natural language date parsing, schedule compilation, and temporal processing.

This plugin bridges the gap between deterministic date-math and unstructured NLP inputs, utilizing large language models (like Gemini, Groq, or OpenAI) to safely and asynchronously parse, format, and process complex natural language temporal expressions into Tempo instances.

🔒 Security Notice

Raw LLM API keys must never be exposed in client-side browser bundles or stored in any client-side storage mechanisms (localStorage, sessionStorage, IndexedDB, OPFS / Origin Private File System, or browser cache). We recommend zero browser storage for API credentials; BYOK (Bring Your Own Key) is only secure on backend servers (Node, edge workers). For public frontend applications, route requests through a secure backend proxy service.

Key Features ​

  • Natural Language Parsing: parseAI turns free-form expressions into Tempo instances (single or batch).
  • Structured AI Results: Narrative formatting (formatAI), event extraction (extractAI), time deltas with business days (diffAI), and regional context inference (contextAI).
  • Recurrence & Scheduling: Natural language to iterable series (recurrenceAI) and conflict-aware appointment slots (scheduleAI).
  • Multi-Provider Execution Modes: Hedged, RoundRobin, Adaptive, Race, Consensus, and Fallback strategies across providers such as Gemini, Groq, and OpenAI.
  • Grounded & Validated: Timezone and locale grounding, schema enforcement, and confidence thresholds with typed TempoAiError results.
  • Privacy & Security Controls: PII masking, plus documented BYOK (backend) and proxy (browser) provider patterns.
  • Two Usage Patterns: The cohesive Tempo.ai.* namespace or tree-shakeable standalone functions.

Installation ​

bash
npm install @tempo-kit/plugin-ai

Quickstart ​

Interactive Demo (@tempo-kit/plugin-ai)
Open in Full REPL↗
// 🤖 AI Semantic Parsing & Scheduling (@tempo-kit/plugin-ai)
const { AiPlugin } = await import('@tempo-kit/plugin-ai');
Tempo.use(AiPlugin);

// 1. Configure provider (Trial 'tempo' sandbox or BYOK: 'gemini', 'openai', 'groq')
await Tempo.ai.init({ provider: 'tempo', debug: true });

// 2. Parse complex cultural/relative calendar expression
// Note: { force: true } bypasses cached entries for live LLM reasoning
const t = await Tempo.ai.parse("The Friday before Melbourne Cup next year", { force: true });

console.log('📅 Parsed:   ', t.format('{www}, {yyyy}-{mmm}-{dd}'));
console.log('🧠 Reasoning:', t.ai?.reasoning);
console.log('🎯 Provider: ', t.ai?.provider, `(confidence: ${t.ai?.confidence})`);

if (t.ai?.limits?.remainingRequests !== undefined) {
  const resetStr = t.ai.limits.resetAt ? t.ai.limits.resetAt.format('{hh}:{mi}:{ss}') : 'in 1h';
  console.log('⏱️ Quota:    ', `${t.ai.limits.remainingRequests} req remaining (resets at ${resetStr})`);
}

return t.iso;
Executes 100% in browser via native ESM sandbox

Installing AiPlugin mounts the frozen Tempo.ai static action namespace onto Tempo:

typescript
import { Tempo } from 'tempo-kit';
import { AiPlugin } from '@tempo-kit/plugin-ai';

Tempo.use(AiPlugin);

// All AI capabilities are available under Tempo.ai.*
await Tempo.ai.init({ provider: 'tempo' });
const event = await Tempo.ai.parse("next Tuesday around 2:30pm");

Auto-Installation (Side-Effect Import) ​

typescript
import { Tempo } from 'tempo-kit';
import '@tempo-kit/plugin-ai/install';

const event = await Tempo.ai.parse("next Tuesday around 2:30pm");

Two Usage Patterns: Namespace vs Tree-Shakeable Functions ​

The AI plugin provides two distinct integration approaches:

ApproachImport SyntaxIdeal For
Cohesive Namespaceimport { AiPlugin } from '@tempo-kit/plugin-ai'Full-featured apps, Node.js backends, REPLs, and IDE auto-complete via Tempo.ai.*
Tree-Shakeable Functionsimport { parseAI, initAI } from '@tempo-kit/plugin-ai'Minimal client-side bundles and microservices importing only specific functions

Tree-Shakeable Standalone Functions ​

For bundle-sensitive projects, import individual functions directly without attaching anything to Tempo:

typescript
import { initAI, parseAI } from '@tempo-kit/plugin-ai';

// 1. Initialize trial sandbox or explicit providers
await initAI({ provider: 'tempo' });

// 2. Call standalone function directly
const dt = await parseAI("The penultimate Tuesday before Thanksgiving in 2026");
console.log(dt.format('{yyyy}-{mm}-{dd}')); // 2026-11-17

API Reference ​

All AI functions return a standard ES Promise and are accessible either as standalone tree-shakeable functions or via the cohesive Tempo.ai.* namespace.

Standalone Function / Tempo.ai MethodInputReturns (Promise<...>)DescriptionDoc
parseAI
Tempo.ai.parse
Natural language text string(s)Tempo | Tempo[] | (Tempo | TempoAiError)[]Single point-in-time Tempo instance (or batch array)
formatAI
Tempo.ai.format
Date-time + prompt / styleTempoAiFormatResult | TempoAiFormatResult[] | (TempoAiFormatResult | TempoAiError)[]Contextual narrative date formatting (formatted, confidence, provider, reasoning)
extractAI
Tempo.ai.extract
Unstructured text string(s)TempoAiExtractResult | TempoAiExtractResult[] | (TempoAiExtractResult | TempoAiError)[]Extracted temporal entities & calendar events (events: TempoExtractedEvent[], confidence, reasoning)
recurrenceAI
Tempo.ai.recurrence
Natural language pattern or RRULE stringTempoRecurrenceResultIterable series of Tempo dates (with .take(n), [Symbol.iterator], & RRULE string)
scheduleAI
Tempo.ai.schedule
Booking prompt + busy constraintsTempoScheduleResultResolved appointment slot (start, end, slot, alternatives, ai.conflictBumped)
diffAI
Tempo.ai.diff
Start & End dates + promptTempoAiDiffResult | TempoAiDiffResult[] | (TempoAiDiffResult | TempoAiError)[]Narrative time delta & business days (formatted, businessDays, days, hours, holidays)
contextAI
Tempo.ai.context
Context text string(s)TempoContext | TempoContext[] | (TempoContext | TempoAiError)[]Inferred regional context (timeZone, locale, calendar, sphere)
initAI
Tempo.ai.init
Provider config & API keysvoidConfigured AI provider farm

Summary of Distinct Return Contracts ​

To streamline error handling and data consumption, return shapes across the AI plugin follow three distinct contracts:

CategoryFunctionsReturn TypeSingle Query Low-Confidence / FailureBatch Array softErrors: true Contract
Point-in-Time DateparseAITempo (with .ai)Throws TempoAiError (or returns invalid Tempo if minConfidence threshold unmet)Returns invalid Tempo (isValid === false) in array position
Structured AI ObjectsformatAI
extractAI
diffAI
contextAI
TempoAiFormatResult
TempoAiExtractResult
TempoAiDiffResult
TempoContext
Throws TempoAiError (422 for low confidence, 429 for quota, 500 for network)Returns typed TempoAiError object directly in array position
Intervals & GeneratorsscheduleAI
recurrenceAI
TempoScheduleResult (Proxied Interval<Tempo>)
TempoRecurrenceResult (.take(n))
Throws TempoAiError (Single item query only)N/A (Single query operations)

Topic Guides ​

IMPORTANT

Production Recommendation: Due to the complexities of LLM APIs, including caching gotchas, context injection, rate limits, and calendar math hallucinations, we strongly recommend reading the dedicated guides below before deploying this plugin in a production environment.


NOTE

Community Feedback & Prompt Engineering: While @tempo-kit/plugin-ai utilizes deterministic grounding, schema enforcement, and confidence validation, LLM outputs can vary across models and prompt styles. We actively welcome community feedback and prompt optimizations—please report any edge cases or suggestions on the Magma GitHub Issue Tracker.

Production Notice & "As-Is" Disclaimer: Magma Computing Solutions and the Tempo core maintainers provide @tempo-kit/plugin-ai "as-is" without warranty of any kind. Large Language Models operate probabilistically; developers and system architects are responsible for validating AI-generated temporal outputs before committing them to financial, legal, medical, or life-critical applications.


License ​

This is a Community plugin. It is completely free and open-source for personal and commercial use under the MIT license.

Released under the MIT License.