CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-langchain--core

Core LangChain.js abstractions and schemas for building applications with Large Language Models

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

messages.mddocs/

Message System

The message system provides structured message types and conversation management for chat-based applications. Messages form the core communication format between users, AI models, and tools in LangChain applications.

Capabilities

Base Message

Abstract base class for all message types in LangChain.

/**
 * Abstract base class for all messages
 */
abstract class BaseMessage {
  /** Message content - can be string or complex content array */
  content: MessageContent;
  /** Optional sender name */
  name?: string;
  /** Additional implementation-specific data */
  additional_kwargs: Record<string, unknown>;
  /** Response metadata from model providers */
  response_metadata: Record<string, unknown>;
  /** Unique message identifier */
  id?: string;
  
  constructor(
    content: MessageContent,
    additional_kwargs?: Record<string, unknown>,
    response_metadata?: Record<string, unknown>,
    name?: string,
    id?: string
  );
  
  /** Get the message type identifier */
  abstract getType(): MessageType;
  
  /** Get text representation of content */
  get text(): string;
  
  /** Convert message to serializable dictionary */
  toDict(): StoredMessage;
  
  /** Create message from serialized dictionary */
  static fromDict(message: StoredMessage): BaseMessage;
}

Human Message

Represents messages from human users.

/**
 * Message from a human user
 */
class HumanMessage extends BaseMessage {
  getType(): "human";
  
  constructor(
    content: MessageContent,
    additional_kwargs?: Record<string, unknown>,
    response_metadata?: Record<string, unknown>,
    name?: string,
    id?: string
  );
}

Usage Examples:

import { HumanMessage } from "@langchain/core/messages";

// Simple text message
const message = new HumanMessage("Hello, how are you?");

// Message with metadata
const messageWithMeta = new HumanMessage(
  "What is the weather like?",
  { priority: "high" },
  {},
  "User123"
);

// Complex content with images
const complexMessage = new HumanMessage([
  { type: "text", text: "What do you see in this image?" },
  { type: "image_url", image_url: { url: "data:image/jpeg;base64,..." } }
]);

AI Message

Represents messages from AI assistants or language models.

/**
 * Message from an AI assistant
 */
class AIMessage extends BaseMessage {
  /** Tool calls made by the AI */
  tool_calls?: ToolCall[];
  /** Invalid tool calls that couldn't be parsed */
  invalid_tool_calls?: InvalidToolCall[];
  /** Usage statistics from the model */
  usage_metadata?: UsageMetadata;
  
  getType(): "ai";
  
  constructor(
    content: MessageContent,
    additional_kwargs?: Record<string, unknown>,
    response_metadata?: Record<string, unknown>,
    name?: string,
    id?: string,
    tool_calls?: ToolCall[],
    invalid_tool_calls?: InvalidToolCall[],
    usage_metadata?: UsageMetadata
  );
}

Usage Examples:

import { AIMessage } from "@langchain/core/messages";

// Simple AI response
const response = new AIMessage("I'm doing well, thank you for asking!");

// AI message with tool calls
const messageWithTools = new AIMessage(
  "I'll help you with that calculation.",
  {},
  {},
  undefined,
  undefined,
  [{
    name: "calculator",
    args: { operation: "add", a: 5, b: 3 },
    id: "call_123"
  }]
);

// AI message with usage metadata
const messageWithUsage = new AIMessage(
  "Here's your answer.",
  {},
  {},
  undefined,
  undefined,
  undefined,
  undefined,
  {
    input_tokens: 10,
    output_tokens: 15,
    total_tokens: 25
  }
);

System Message

Represents system-level instructions or context.

/**
 * System message providing context or instructions
 */
class SystemMessage extends BaseMessage {
  getType(): "system";
  
  constructor(
    content: MessageContent,
    additional_kwargs?: Record<string, unknown>,
    response_metadata?: Record<string, unknown>,
    name?: string,
    id?: string
  );
}

Usage Examples:

import { SystemMessage } from "@langchain/core/messages";

const systemMsg = new SystemMessage(
  "You are a helpful assistant that answers questions about science."
);

const contextMsg = new SystemMessage(
  "The current date is 2024-01-15. Answer all questions with this context in mind."
);

Function Message

Represents messages from function/tool executions (deprecated in favor of ToolMessage).

/**
 * Message from a function execution (deprecated)
 * @deprecated Use ToolMessage instead
 */
class FunctionMessage extends BaseMessage {
  /** Name of the function that was called */
  name: string;
  
  getType(): "function";
  
  constructor(
    content: MessageContent,
    name: string,
    additional_kwargs?: Record<string, unknown>,
    response_metadata?: Record<string, unknown>,
    id?: string
  );
}

Tool Message

Represents responses from tool executions.

/**
 * Message containing tool execution results
 */
class ToolMessage extends BaseMessage {
  /** ID of the tool call this message responds to */
  tool_call_id: string;
  /** Name of the tool that was executed */
  name?: string;
  /** Artifact returned by the tool */
  artifact?: unknown;
  
  getType(): "tool";
  
  constructor(
    content: MessageContent,
    tool_call_id: string,
    name?: string,
    artifact?: unknown,
    additional_kwargs?: Record<string, unknown>,
    response_metadata?: Record<string, unknown>,
    id?: string
  );
}

Usage Examples:

import { ToolMessage } from "@langchain/core/messages";

// Tool execution result
const toolResult = new ToolMessage(
  "The calculation result is 42",
  "call_123",
  "calculator"
);

// Tool result with artifact
const toolWithArtifact = new ToolMessage(
  "Chart generated successfully",
  "call_456",
  "chart_generator",
  { chartUrl: "https://example.com/chart.png", format: "png" }
);

Chat Message

Generic chat message with custom roles for non-standard message types.

/**
 * Generic chat message with custom role
 */
class ChatMessage extends BaseMessage {
  /** Custom role identifier */
  role: string;
  
  getType(): "generic";
  
  constructor(
    content: MessageContent,
    role: string,
    additional_kwargs?: Record<string, unknown>,
    response_metadata?: Record<string, unknown>,
    name?: string,
    id?: string
  );
}

Usage Examples:

import { ChatMessage } from "@langchain/core/messages";

// Custom role message
const customMessage = new ChatMessage(
  "Processing your request...",
  "processing_bot"
);

// Assistant with specific role
const assistantMessage = new ChatMessage(
  "I'm a specialized code reviewer.",
  "code_reviewer"
);

Remove Message

Special message type for indicating message removal in message streams.

/**
 * Special message indicating removal from message stream
 */
class RemoveMessage extends BaseMessage {
  getType(): "remove";
  
  constructor(id: string);
}

Base Message Chunk

Base class for streamable message chunks that can be concatenated.

/**
 * Base class for streamable message chunks
 */
abstract class BaseMessageChunk extends BaseMessage {
  /** Combine this chunk with another chunk */
  abstract concat(chunk: BaseMessageChunk): BaseMessageChunk;
}

/**
 * Streamable chunk of an AI message
 */
class AIMessageChunk extends BaseMessageChunk {
  getType(): "ai";
  
  concat(chunk: AIMessageChunk): AIMessageChunk;
}

/**
 * Streamable chunk of a human message
 */
class HumanMessageChunk extends BaseMessageChunk {
  getType(): "human";
  
  concat(chunk: HumanMessageChunk): HumanMessageChunk;
}

/**
 * Streamable chunk of a system message
 */
class SystemMessageChunk extends BaseMessageChunk {
  getType(): "system";
  
  concat(chunk: SystemMessageChunk): SystemMessageChunk;
}

/**
 * Streamable chunk of a function message
 */
class FunctionMessageChunk extends BaseMessageChunk {
  /** Name of the function */
  name: string;
  
  getType(): "function";
  
  concat(chunk: FunctionMessageChunk): FunctionMessageChunk;
}

/**
 * Streamable chunk of a tool message
 */
class ToolMessageChunk extends BaseMessageChunk {
  /** ID of the tool call this chunk responds to */
  tool_call_id: string;
  /** Name of the tool */
  name?: string;
  /** Artifact from the tool */
  artifact?: unknown;
  
  getType(): "tool";
  
  concat(chunk: ToolMessageChunk): ToolMessageChunk;
}

Usage Examples:

import { AIMessageChunk } from "@langchain/core/messages";

// Streaming AI response
const chunk1 = new AIMessageChunk("Hello");
const chunk2 = new AIMessageChunk(" world");
const combined = chunk1.concat(chunk2); // "Hello world"

Message Utilities

Message Conversion Functions

/**
 * Convert various message-like inputs to BaseMessage instances
 */
function convertToMessage(message: BaseMessageLike): BaseMessage;

/**
 * Convert array of message-like inputs to BaseMessage array
 */
function convertToMessages(messages: BaseMessageLike[]): BaseMessage[];

/**
 * Get buffer string representation of messages
 */
function getBufferString(messages: BaseMessage[], humanPrefix?: string, aiPrefix?: string): string;

/**
 * Convert message to OpenAI format
 */
function messageToOpenAIRole(message: BaseMessage): { role: string; content: string };

/**
 * Convert various message-like inputs to BaseMessage
 */
function coerceMessageLikeToMessage(message: BaseMessageLike): BaseMessage;

/**
 * Convert message to chunk for streaming
 */
function convertToChunk(message: BaseMessage): BaseMessageChunk;

/**
 * Check if message is an AI message
 */
function isAIMessage(message: BaseMessage): message is AIMessage;

/**
 * Check if message is a human message
 */
function isHumanMessage(message: BaseMessage): message is HumanMessage;

/**
 * Check if message is a system message
 */
function isSystemMessage(message: BaseMessage): message is SystemMessage;

/**
 * Check if message is a function message
 */
function isFunctionMessage(message: BaseMessage): message is FunctionMessage;

/**
 * Check if message is a tool message
 */
function isToolMessage(message: BaseMessage): message is ToolMessage;

/**
 * Check if message is a chat message
 */
function isChatMessage(message: BaseMessage): message is ChatMessage;

/**
 * Default tool call parser for OpenAI-style tool calls
 */
function defaultToolCallParser(rawToolCalls: any[]): ToolCall[];

Usage Examples:

import { convertToMessages, getBufferString } from "@langchain/core/messages";

// Convert mixed message types
const messages = convertToMessages([
  "Hello there",  // Becomes HumanMessage
  ["system", "You are helpful"],  // Becomes SystemMessage  
  new AIMessage("How can I help?")
]);

// Get conversation as string
const conversationText = getBufferString(messages);

Types

type MessageContent = string | MessageContentComplex[];

interface MessageContentComplex {
  type: "text" | "image_url";
  text?: string;
  image_url?: {
    url: string;
    detail?: "auto" | "low" | "high";
  };
}

type MessageType = "human" | "ai" | "generic" | "developer" | "system" | "function" | "tool" | "remove";

interface ToolCall {
  name: string;
  args: Record<string, unknown>;
  id: string;
}

interface ToolCallChunk {
  name?: string;
  args?: string;
  id?: string;
  index?: number;
}

interface InvalidToolCall {
  name?: string;
  args?: string;
  id: string;
  error: string;
}

interface UsageMetadata {
  input_tokens: number;
  output_tokens: number;
  total_tokens: number;
}

interface StoredMessage {
  type: MessageType;
  content: MessageContent;
  name?: string;
  additional_kwargs?: Record<string, unknown>;
  response_metadata?: Record<string, unknown>;
  id?: string;
}

interface FunctionCall {
  name: string;
  arguments: string;
}

interface DirectToolOutput {
  content: string;
  artifact?: unknown;
}

interface MessageLikeDict {
  role: string;
  content: string;
}

type BaseMessageLike = 
  | BaseMessage
  | string
  | [string, string]  // [role, content]
  | { role: string; content: string };

docs

agents.md

caches.md

callbacks.md

documents.md

embeddings.md

index.md

language-models.md

memory-storage.md

messages.md

output-parsers.md

prompts.md

retrievers.md

runnables.md

tools.md

vectorstores.md

tile.json