Core LangChain.js abstractions and schemas for building applications with Large Language Models
npx @tessl/cli install tessl/npm-langchain--core@0.3.0LangChain Core provides the foundational abstractions and runtime for the LangChain.js ecosystem, serving as the base layer for building applications with Large Language Models (LLMs). It includes base classes for language models, chat models, vectorstores, retrievers, and the LangChain Expression Language (LCEL) runtime that enables composable sequences called "runnables".
npm install @langchain/coreImportant: @langchain/core uses subpath imports for optimal tree-shaking. Always import from specific module paths, never from the root package.
// ✅ Correct - use subpath imports
import { BaseMessage, HumanMessage, AIMessage } from "@langchain/core/messages";
import { BaseChatModel } from "@langchain/core/language_models/chat_models";
import { Runnable } from "@langchain/core/runnables";
import { VectorStore } from "@langchain/core/vectorstores";
import { BaseRetriever } from "@langchain/core/retrievers";
import { PromptTemplate } from "@langchain/core/prompts";
import { StringOutputParser } from "@langchain/core/output_parsers";
// ❌ Incorrect - root imports are not supported
// import { BaseMessage } from "@langchain/core";For CommonJS:
const { BaseMessage, HumanMessage, AIMessage } = require("@langchain/core/messages");
const { BaseChatModel } = require("@langchain/core/language_models/chat_models");
const { Runnable } = require("@langchain/core/runnables");import { StringOutputParser } from "@langchain/core/output_parsers";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { RunnableSequence } from "@langchain/core/runnables";
// Create a prompt template
const prompt = ChatPromptTemplate.fromTemplate(
"Answer the following question: {question}"
);
// Create an output parser
const outputParser = new StringOutputParser();
// Chain components using LCEL (LangChain Expression Language)
const chain = prompt.pipe(outputParser);
// Use the chain
const result = await chain.invoke({
question: "What is the capital of France?"
});LangChain Core is built around several key design patterns:
Core composability framework enabling universal chaining, streaming, and batch operations across all LangChain components.
abstract class Runnable<RunInput, RunOutput, CallOptions = {}> {
abstract invoke(input: RunInput, options?: Partial<CallOptions>): Promise<RunOutput>;
stream(input: RunInput, options?: Partial<CallOptions>): AsyncGenerator<RunOutput>;
batch(inputs: RunInput[], options?: Partial<CallOptions>): Promise<RunOutput[]>;
pipe<NewRunOutput>(coerceable: RunnableLike<RunOutput, NewRunOutput>): Runnable<RunInput, NewRunOutput>;
}Structured message types and conversation management for chat-based applications.
abstract class BaseMessage {
constructor(content: MessageContent, additional_kwargs?: Record<string, unknown>);
readonly content: MessageContent;
readonly additional_kwargs: Record<string, unknown>;
readonly response_metadata: Record<string, unknown>;
abstract getType(): MessageType;
}
class HumanMessage extends BaseMessage {
getType(): "human";
}
class AIMessage extends BaseMessage {
getType(): "ai";
}Abstract base classes for language models and chat models with unified interfaces.
abstract class BaseChatModel<CallOptions = {}, OutputMessageType extends BaseMessage = BaseMessage> extends BaseLanguageModel<OutputMessageType, CallOptions> {
bindTools(tools: BindToolsInput, kwargs?: Record<string, unknown>): BaseChatModel;
withStructuredOutput<T>(outputSchema: z.ZodSchema<T> | Record<string, unknown>): Runnable<BaseMessage[], T>;
}Document storage and similarity search functionality for retrieval-augmented generation (RAG).
abstract class VectorStore {
abstract addDocuments(documents: Document[], options?: Record<string, unknown>): Promise<string[] | void>;
abstract similaritySearch(query: string, k?: number, filter?: object): Promise<Document[]>;
abstract similaritySearchWithScore(query: string, k?: number, filter?: object): Promise<[Document, number][]>;
asRetriever(fields?: VectorStoreRetrieverInput<this>): VectorStoreRetriever<this>;
}Document representation and processing capabilities for content management.
class Document<Metadata = Record<string, unknown>> {
constructor(fields: DocumentInput<Metadata>);
pageContent: string;
metadata: Metadata;
id?: string;
}Document retrieval abstractions for implementing search and information retrieval.
abstract class BaseRetriever<Metadata = Record<string, unknown>> extends Runnable<string, Document<Metadata>[]> {
abstract _getRelevantDocuments(query: string, runManager?: CallbackManagerForRetrieverRun): Promise<Document<Metadata>[]>;
getRelevantDocuments(query: string, config?: RunnableConfig): Promise<Document<Metadata>[]>;
}Template system for creating dynamic prompts with variable substitution and formatting.
abstract class BasePromptTemplate<RunInput extends InputValues = InputValues, RunOutput extends PromptValue = PromptValue> extends Runnable<RunInput, RunOutput> {
abstract format(values: InputValues): Promise<string>;
abstract formatPromptValue(values: InputValues): Promise<PromptValue>;
}Tool definition and execution framework for function calling and external integrations.
abstract class StructuredTool<SchemaT = z.ZodSchema> extends Runnable<z.input<SchemaT>, unknown> {
name: string;
description: string;
schema: SchemaT;
abstract _call(arg: z.input<SchemaT>, runManager?: CallbackManagerForToolRun): Promise<unknown>;
}Structured output parsing for converting LLM responses into typed data structures.
abstract class BaseOutputParser<T = unknown> extends Runnable<string | BaseMessage, T> {
abstract parse(text: string): Promise<T>;
parseResult(result: ChatResult): Promise<T>;
getFormatInstructions(): string;
}Event handling and observability framework for monitoring and debugging LangChain operations.
abstract class BaseCallbackHandler {
name: string;
handleLLMStart?(llm: Serialized, prompts: string[], runId: string): Promise<void>;
handleLLMEnd?(output: LLMResult, runId: string): Promise<void>;
handleLLMError?(err: Error, runId: string): Promise<void>;
}Memory management and storage abstractions for maintaining conversation state and persistence.
abstract class BaseChatMessageHistory {
abstract getMessages(): Promise<BaseMessage[]>;
abstract addMessage(message: BaseMessage): Promise<void>;
abstract clear(): Promise<void>;
}Embedding model abstractions for converting text to vector representations.
abstract class Embeddings {
abstract embedDocuments(documents: string[]): Promise<number[][]>;
abstract embedQuery(document: string): Promise<number[]>;
}Agent framework for autonomous task execution and tool usage.
interface AgentAction {
tool: string;
toolInput: string | Record<string, any>;
log: string;
}
interface AgentFinish {
returnValues: Record<string, any>;
log: string;
}Caching framework for optimizing repeated operations.
abstract class BaseCache<T> {
abstract lookup(prompt: string, llmKey: string): Promise<T | null>;
abstract update(prompt: string, llmKey: string, value: T): Promise<void>;
}type MessageContent = string | MessageContentComplex[];
type MessageType = "human" | "ai" | "generic" | "developer" | "system" | "function" | "tool" | "remove";
interface RunnableConfig {
callbacks?: Callbacks;
tags?: string[];
metadata?: Record<string, unknown>;
runName?: string;
configurable?: Record<string, unknown>;
}
interface InputValues {
[key: string]: unknown;
}
type Callbacks = CallbackManager | (BaseCallbackHandler | CallbackHandlerMethods)[];