Core API
@cognivo/core — framework-agnostic AI integration logic: client interfaces, context building, intents, and result types.
Installation
pnpm add @cognivo/core @cognivo/adapter-openai AiClient Interface
All adapters implement the AiClient interface. Swap providers without changing application code.
interface AiClient {
run(context: AiContext, options?: AiRequestOptions): Promise<AiResult>;
} Intents
Intents describe what you want the AI to do with your data:
import { AiIntent } from '@cognivo/core';
AiIntent.Summarize // Summarize a dataset
AiIntent.Explain // Explain a data point or trend
AiIntent.Forecast // Predict future values
AiIntent.DetectAnomaly // Find outliers or anomalies
AiIntent.Classify // Categorize data points
AiIntent.Recommend // Generate recommendations
AiIntent.Compare // Compare datasets or segments
AiIntent.Ask // Free-form question about data Context Building
Use ContextBuilder to assemble structured context for the AI:
import { ContextBuilder, AiIntent } from '@cognivo/core';
const context = new ContextBuilder()
.withDataset(salesData)
.withIntent(AiIntent.DetectAnomaly)
.withMeta({ timeRange: 'last-30-days', metric: 'revenue' })
.build();
const result = await client.run(context); Result Types
AI responses are returned as typed AiResult objects:
interface AiResult {
answer: string; // Natural language response
confidence: number; // 0-1 confidence score
driver?: AiDriver; // Key driver analysis
anomalies?: AiAnomaly[]; // Detected anomalies
forecasts?: AiForecast[]; // Predicted values
classifications?: AiClassification[];
recommendations?: AiRecommendation[];
} Decorator Pattern
Core clients wrap each other in a decorator pattern. Stack capabilities as needed:
import { OpenAiClient } from '@cognivo/adapter-openai';
import { GuardedClient, CachedClient, ObservableClient, InMemoryLruCache, InMemoryTracer } from '@cognivo/core';
const base = new OpenAiClient({ apiKey: '...' });
const cached = new CachedClient(base, { cache: new InMemoryLruCache() });
const guarded = new GuardedClient(cached, { rules: [noPromptInjectionRule, maxLengthRule(500)] });
const client = new ObservableClient(guarded, { tracer: new InMemoryTracer() });
// Uses all layers: observability → guardrails → caching → OpenAI
const result = await client.run(context); Also Available
Two additional clients pair with any AiClient implementation for stateful conversations and fault tolerance.
ConversationalClient
Wraps any AiClient to maintain conversation history automatically — subsequent calls carry prior turns as context. Pairs with any AiClient implementation.
import { ConversationalClient, AiIntent } from '@cognivo/core';
import { OpenAiClient } from '@cognivo/adapter-openai';
const base = new OpenAiClient({ apiKey: '...' });
const chat = new ConversationalClient(base);
await chat.send({ intent: AiIntent.Generate, input: 'Who are you?' });
// Next call has context automatically
await chat.send({ intent: AiIntent.Generate, input: 'What did I just ask?' }); CircuitBreaker
Short-circuits calls to a failing client so the process fails fast instead of stacking timeouts. Pairs with any AiClient implementation.
import { CircuitBreaker } from '@cognivo/core';
const protectedClient = new CircuitBreaker(baseClient, {
failureThreshold: 3,
resetTimeoutMs: 60_000,
});
// After 3 consecutive failures, subsequent calls fail fast for 60s. Key Exports
BaseAiClient, GuardedClient, CachedClient, FallbackClient, ObservableClient, ConversationalClient
CircuitBreaker, SelfRefineClient, ExtendedThinkingClient, ModelRouterClient, AgentCoordinator
ContextBuilder, PromptOptimizer, PromptEvaluator, InMemoryTracer, InMemoryLruCache, SemanticCacheStore