Skip to content

MemberJunction AI Framework

A unified, provider-agnostic AI abstraction layer for TypeScript. Write your AI logic once; swap providers, models, and capabilities without changing application code.

The framework spans 47 packages covering LLMs, embeddings, image generation, audio synthesis, video generation, reranking, vector operations, agent orchestration, and protocol servers — with integrations for 25+ AI services from OpenAI and Anthropic to local inference engines like Ollama and LM Studio.


Install @memberjunction/ai (the Core package) plus any provider. Zero database dependencies. Works in any TypeScript or JavaScript project.

import { ChatParams, ChatMessageRole } from "@memberjunction/ai";
import { AnthropicLLM } from "@memberjunction/ai-anthropic";
const llm = new AnthropicLLM(process.env.ANTHROPIC_API_KEY!);
const result = await llm.ChatCompletion({
model: "claude-sonnet-4-20250514",
messages: [{ role: ChatMessageRole.user, content: "Explain quantum tunneling." }],
});
console.log(result.data.choices[0].message.content);

That is the entire setup. No configuration files, no database, no metadata — just types and a provider.

When running inside MemberJunction, the AI framework gains metadata-driven model selection, prompt template management with hierarchical composition, cost tracking, agent orchestration, and vector synchronization — all configured through the MJ database and entity system.

import { AIPromptRunner } from "@memberjunction/ai-prompts";
import { AIPromptParams } from "@memberjunction/ai-core-plus";
// Model, provider, and prompt template resolved from MJ metadata
const runner = new AIPromptRunner();
const params = new AIPromptParams();
params.promptName = "Summarize Document";
params.data = { content: documentText };
const result = await runner.ExecutePrompt(params);

graph TB
    subgraph Application["Application Layer"]
        APP["Your Code"]
    end

    subgraph Core["@memberjunction/ai  (Zero MJ Dependencies)"]
        BM["BaseLLM"]
        BE["BaseEmbeddings"]
        BIG["BaseImageGenerator"]
        BA["BaseAudio"]
        BV["BaseVideo"]
        BR["BaseReranker"]
        TYPES["Chat/Embed/Image Types"]
        ERR["ErrorAnalyzer"]
    end

    subgraph Providers["Provider Implementations"]
        direction LR
        P_OAI["OpenAI"]
        P_ANT["Anthropic"]
        P_GEM["Gemini"]
        P_MIS["Mistral"]
        P_GRQ["Groq"]
        P_BED["Bedrock"]
        P_MORE["...20+ more"]
    end

    subgraph MJLayer["MJ-Integrated Layer  (Requires MJ Runtime)"]
        ENG["AI Engine"]
        PRM["Prompt Runner"]
        AGT["Agent Framework"]
        VEC["Vector Sync"]
        MCP["MCP Server"]
        A2A["A2A Server"]
    end

    APP --> Core
    APP --> MJLayer
    Core --> Providers
    MJLayer --> Core

    style Core fill:#1a365d,stroke:#2b6cb0,color:#fff
    style Providers fill:#2d6a9f,stroke:#4299e1,color:#fff
    style MJLayer fill:#553c9a,stroke:#805ad5,color:#fff
    style Application fill:#2d8659,stroke:#48bb78,color:#fff

Each provider implements one or more capability interfaces from @memberjunction/ai. The table below shows what each provider supports.

Providernpm PackageLLMEmbeddingsImage GenAudioVideoReranking
OpenAI@memberjunction/ai-openaixxxx
Anthropic@memberjunction/ai-anthropicx
Google Gemini@memberjunction/ai-geminixxx
Mistral@memberjunction/ai-mistralxx
Groq@memberjunction/ai-groqx
xAI (Grok)@memberjunction/ai-xaix
Azure AI@memberjunction/ai-azurexx
Amazon Bedrock@memberjunction/ai-bedrockxx
Google Vertex@memberjunction/ai-vertexx
Fireworks@memberjunction/ai-fireworksx
OpenRouter@memberjunction/ai-openrouterx
Cerebras@memberjunction/ai-cerebrasx
MiniMax@memberjunction/ai-minimaxx
Zhipu (Z.AI)@memberjunction/ai-zhipux
Ollama@memberjunction/ai-ollamaxx
LM Studio@memberjunction/ai-lmstudiox
BettyBot@memberjunction/ai-betty-botx
Black Forest Labs@memberjunction/ai-blackforestlabsx
ElevenLabs@memberjunction/ai-elevenlabsx
HeyGen@memberjunction/ai-heygenx
Cohere@memberjunction/ai-coherexx
Local Embeddings@memberjunction/ai-local-embeddingsx
Pinecone@memberjunction/ai-vectors-pinecone
Rex (rasa.io)@memberjunction/ai-recommendations-rex

Pinecone and Rex implement vector database and recommendation interfaces respectively, not the base AI model interfaces.


PackagenpmStandaloneDescription
Core@memberjunction/aiYesBase classes (BaseLLM, BaseEmbeddings, BaseImageGenerator, BaseAudio, BaseVideo, BaseReranker), type definitions, error analysis, API key management
CorePlus@memberjunction/ai-core-plusExtended AI types that reference MJ entity concepts; shared by server and client
BaseAIEngine@memberjunction/ai-engine-baseYesBase engine class with extended types and data caching
Reranker@memberjunction/ai-rerankerAI reranker service with LLM-based two-stage retrieval
PackagenpmStandaloneDescription
Engine@memberjunction/aiengineAI orchestration engine — automatic execution of Entity AI Actions using configured models
Prompts@memberjunction/ai-promptsPrompt execution engine with hierarchical template composition, system placeholders, parallel runs, and output validation
Agents@memberjunction/ai-agentsAgent execution and management with metadata-driven agent types, sub-agent delegation, and client tool invocation for browser-side UI operations
PackagenpmStandaloneDescription
AgentManager/core@memberjunction/ai-agent-managerCore interfaces, types, and AgentSpec for agent metadata management
AgentManager/actions@memberjunction/ai-agent-manager-actionsAgent management actions (create, update, list, deactivate, export)
PackagenpmStandaloneDescription
MCPServer@memberjunction/ai-mcp-serverModel Context Protocol server exposing MJ entity CRUD and agent execution to MCP-compatible clients
MCPClient@memberjunction/ai-mcp-clientMCP client for consuming external MCP tool servers
A2AServer@memberjunction/a2aserverAgent-to-Agent (A2A) protocol server for cross-system agent interoperability
PackagenpmStandaloneDescription
Vectors/Core@memberjunction/ai-vectorsCore vector operations and abstractions for entity vectorization
Vectors/Database@memberjunction/ai-vectordbVector database abstraction layer (index management, query operations)
Vectors/Sync@memberjunction/ai-vector-syncSynchronization between MJ entities and vector databases
Vectors/Dupe@memberjunction/ai-vector-dupeDuplicate record detection using vector similarity
Vectors/Memory@memberjunction/ai-vectors-memoryIn-memory vector utilities
PackagenpmStandaloneDescription
Recommendations/Engine@memberjunction/ai-recommendationsProvider-agnostic recommendation engine with run tracking and entity integration
PackagenpmStandaloneDescription
ComputerUse@memberjunction/computer-useYesVision-to-action browser automation engine for LLM-driven web interactions
MJComputerUse@memberjunction/computer-use-engineMJ-integrated computer use engine with entity-backed configuration
PackagenpmStandaloneDescription
AICLI@memberjunction/ai-cliAI agent, prompt, and action execution CLI integrated with the MJ CLI

All 25 provider packages are listed in the Providers README. The meta-package @memberjunction/ai-provider-bundle imports all standard providers to prevent tree-shaking in bundled applications.


Terminal window
# Core + one provider (pick any from the table above)
npm install @memberjunction/ai @memberjunction/ai-openai
Terminal window
export AI_VENDOR_API_KEY__OPENAILLM=sk-...

Or pass the key directly when constructing the provider.

import { ChatParams, ChatMessageRole } from "@memberjunction/ai";
import { OpenAILLM } from "@memberjunction/ai-openai";
const llm = new OpenAILLM(process.env.AI_VENDOR_API_KEY__OPENAILLM!);
const result = await llm.ChatCompletion({
model: "gpt-4.1",
messages: [{ role: ChatMessageRole.user, content: "Hello, world!" }],
});
console.log(result.data.choices[0].message.content);
await llm.ChatCompletion({
model: "gpt-4.1",
messages: [{ role: ChatMessageRole.user, content: "Write a haiku about TypeScript." }],
streaming: true,
streamingCallbacks: {
OnContent: (chunk) => process.stdout.write(chunk),
OnComplete: () => console.log(),
},
});
import { OpenAIEmbedding } from "@memberjunction/ai-openai";
const embedder = new OpenAIEmbedding(process.env.AI_VENDOR_API_KEY__OPENAILLM!);
const result = await embedder.EmbedText({
text: "Semantic search is powerful",
model: "text-embedding-3-small",
});
console.log(`Vector dimensions: ${result.vector.length}`);

Because all providers implement the same BaseLLM interface, switching is a one-line change:

// Before: OpenAI
import { OpenAILLM } from "@memberjunction/ai-openai";
const llm = new OpenAILLM(openaiKey);
// After: Anthropic
import { AnthropicLLM } from "@memberjunction/ai-anthropic";
const llm = new AnthropicLLM(anthropicKey);
// After: Local (Ollama)
import { OllamaLLM } from "@memberjunction/ai-ollama";
const llm = new OllamaLLM(""); // No API key needed

Your ChatCompletion() calls, streaming callbacks, and error handling remain identical.


Extend the appropriate base class and register it with the class factory:

import { BaseLLM, ChatParams, ChatResult } from "@memberjunction/ai";
import { RegisterClass } from "@memberjunction/global";
@RegisterClass(BaseLLM, "MyCustomLLM")
export class MyCustomLLM extends BaseLLM {
protected async nonStreamingChatCompletion(params: ChatParams): Promise<ChatResult> {
// Call your provider API here
}
// For streaming, override SupportsStreaming + streaming hooks
}

If your provider uses an OpenAI-compatible API, extend OpenAILLM instead and override the base URL. See the Groq or xAI providers for examples.


The framework resolves API keys through environment variables using the convention:

AI_VENDOR_API_KEY__<DRIVER_CLASS>

For example:

  • AI_VENDOR_API_KEY__OPENAILLM for OpenAI
  • AI_VENDOR_API_KEY__ANTHROPICLLM for Anthropic
  • AI_VENDOR_API_KEY__GEMINILLM for Google Gemini

You can also pass keys directly to provider constructors or supply runtime overrides via GetAIAPIKey().


All providers use a unified ErrorAnalyzer that classifies failures into structured error types:

const result = await llm.ChatCompletion(params);
if (!result.success) {
console.error(result.errorMessage);
// result.exception contains the original error
// ErrorAnalyzer provides: errorType, severity, isRetryable, failoverRecommended
}

Error types include rate limiting, authentication failures, context length exceeded, content filtering, and more — enabling intelligent retry and failover logic.



See the MemberJunction repository root for license details.