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

tools.mddocs/

Tools System

Tool definition and execution framework for function calling and external integrations. Tools enable language models to interact with external systems, APIs, and perform computations.

Capabilities

Structured Tool

Base class for tools with structured input validation using schemas.

/**
 * Base class for tools with structured input validation
 * @template SchemaT - Input schema type (Zod or JSON schema)
 * @template SchemaOutputT - Schema output type (inferred)
 * @template SchemaInputT - Schema input type (inferred) 
 * @template ToolOutputT - Tool execution output type
 */
abstract class StructuredTool<
  SchemaT = z.ZodSchema,
  SchemaOutputT = z.output<SchemaT>,
  SchemaInputT = z.input<SchemaT>,
  ToolOutputT = unknown
> extends Runnable<SchemaInputT, ToolOutputT> {
  /** Tool name for identification */
  name: string;
  /** Human-readable description of tool functionality */
  description: string;
  /** Input validation schema (Zod or JSON schema) */
  schema: SchemaT;
  /** Whether tool output should be returned directly to user */
  returnDirect: boolean;
  /** Output format specification */
  responseFormat?: ResponseFormat;
  /** Whether to show detailed parsing error messages */
  verboseParsingErrors: boolean;
  
  constructor(fields: StructuredToolParams<SchemaT, ToolOutputT>);
  
  /** Abstract method to implement tool functionality */
  abstract _call(arg: SchemaOutputT, runManager?: CallbackManagerForToolRun, parentConfig?: RunnableConfig): Promise<ToolOutputT>;
  
  /** Main execution method with input validation */
  async invoke(input: SchemaInputT, config?: RunnableConfig): Promise<ToolReturnType>;
  
  /** Legacy call method (deprecated) */
  async call(arg: SchemaInputT, config?: RunnableConfig, tags?: string[]): Promise<ToolReturnType>;
}

Usage Examples:

import { StructuredTool } from "@langchain/core/tools";
import { z } from "zod";

// Define a calculator tool
class CalculatorTool extends StructuredTool {
  name = "calculator";
  description = "Perform basic arithmetic operations";
  
  schema = z.object({
    operation: z.enum(["add", "subtract", "multiply", "divide"]),
    a: z.number().describe("First number"),
    b: z.number().describe("Second number")
  });
  
  async _call({ operation, a, b }: z.infer<typeof this.schema>): Promise<number> {
    switch (operation) {
      case "add": return a + b;
      case "subtract": return a - b;
      case "multiply": return a * b;
      case "divide": 
        if (b === 0) throw new Error("Division by zero");
        return a / b;
    }
  }
}

// Use the tool
const calculator = new CalculatorTool();
const result = await calculator.invoke({
  operation: "add",
  a: 5,
  b: 3
}); // Returns 8

Tool

Simplified tool class for string-based input.

/**
 * Tool with string input (extends StructuredTool)
 * @template ToolOutputT - Tool output type
 */
abstract class Tool<ToolOutputT = string> extends StructuredTool<z.ZodString, string, string, ToolOutputT> {
  /** Pre-defined string schema */
  schema: z.ZodString;
  
  constructor(fields: ToolParams<ToolOutputT>);
  
  /** Call tool with string input */
  abstract _call(arg: string, runManager?: CallbackManagerForToolRun, parentConfig?: RunnableConfig): Promise<ToolOutputT>;
}

Usage Examples:

import { Tool } from "@langchain/core/tools";

// Simple string-based tool
class EchoTool extends Tool {
  name = "echo";
  description = "Echo back the input text";
  
  async _call(input: string): Promise<string> {
    return `Echo: ${input}`;
  }
}

const echo = new EchoTool();
const result = await echo.invoke("Hello World"); // "Echo: Hello World"

Dynamic Tool

Runtime-defined tool with function-based implementation.

/**
 * Tool defined at runtime with a function
 * @template ToolOutputT - Tool output type
 */
class DynamicTool<ToolOutputT = unknown> extends Tool<ToolOutputT> {
  /** Tool implementation function */
  func: (input: string, runManager?: CallbackManagerForToolRun, config?: RunnableConfig) => Promise<ToolOutputT>;
  
  constructor(fields: DynamicToolInput<ToolOutputT>);
  
  /** Execute the provided function */
  async _call(input: string, runManager?: CallbackManagerForToolRun, config?: RunnableConfig): Promise<ToolOutputT>;
}

Usage Examples:

import { DynamicTool } from "@langchain/core/tools";

// Create tool from function
const upperCaseTool = new DynamicTool({
  name: "uppercase",
  description: "Convert text to uppercase",
  func: async (input: string) => input.toUpperCase()
});

const result = await upperCaseTool.invoke("hello"); // "HELLO"

Dynamic Structured Tool

Runtime-defined structured tool with schema validation.

/**
 * Structured tool defined at runtime
 * @template SchemaT - Schema type
 * @template SchemaOutputT - Schema output type
 * @template SchemaInputT - Schema input type
 * @template ToolOutputT - Tool output type
 */
class DynamicStructuredTool<
  SchemaT = z.ZodSchema,
  SchemaOutputT = z.output<SchemaT>,
  SchemaInputT = z.input<SchemaT>,
  ToolOutputT = unknown
> extends StructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT> {
  /** Tool implementation function */
  func: (input: SchemaOutputT, runManager?: CallbackManagerForToolRun, config?: RunnableConfig) => Promise<ToolOutputT>;
  
  constructor(fields: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT>);
  
  /** Execute the provided function */
  async _call(input: SchemaOutputT, runManager?: CallbackManagerForToolRun, config?: RunnableConfig): Promise<ToolOutputT>;
}

Usage Examples:

import { DynamicStructuredTool } from "@langchain/core/tools";
import { z } from "zod";

// Create structured tool from function
const weatherTool = new DynamicStructuredTool({
  name: "get_weather",
  description: "Get current weather for a location",
  schema: z.object({
    location: z.string().describe("City name"),
    unit: z.enum(["celsius", "fahrenheit"]).default("celsius")
  }),
  func: async ({ location, unit }) => {
    // Simulate API call
    const temp = unit === "celsius" ? "22°C" : "72°F";
    return `Weather in ${location}: ${temp}, sunny`;
  }
});

const weather = await weatherTool.invoke({
  location: "Paris",
  unit: "celsius"
}); // "Weather in Paris: 22°C, sunny"

Tool Factory Function

Convenient factory function for creating tools.

/**
 * Factory function for creating tools
 * @template SchemaT - Schema type
 * @param func - Tool implementation function
 * @param fields - Tool configuration
 * @returns DynamicTool or DynamicStructuredTool based on schema
 */
function tool<SchemaT = z.ZodString>(
  func: SchemaT extends z.ZodString
    ? (input: string) => unknown | Promise<unknown>
    : (input: z.output<SchemaT>) => unknown | Promise<unknown>,
  fields: SchemaT extends z.ZodString
    ? { name: string; description: string; schema?: SchemaT }
    : { name: string; description: string; schema: SchemaT }
): SchemaT extends z.ZodString ? DynamicTool : DynamicStructuredTool<SchemaT>;

Usage Examples:

import { tool } from "@langchain/core/tools";
import { z } from "zod";

// Simple string tool
const greetTool = tool(
  (name: string) => `Hello, ${name}!`,
  {
    name: "greet",
    description: "Greet someone by name"
  }
);

// Structured tool
const mathTool = tool(
  ({ x, y, operation }) => {
    switch (operation) {
      case "add": return x + y;
      case "multiply": return x * y;
      default: throw new Error("Unknown operation");
    }
  },
  {
    name: "math",
    description: "Perform math operations",
    schema: z.object({
      x: z.number(),
      y: z.number(),
      operation: z.enum(["add", "multiply"])
    })
  }
);

Base Toolkit

Abstract base class for organizing related tools.

/**
 * Base class for tool collections
 */
abstract class BaseToolkit {
  /** Collection of tools in this toolkit */
  abstract tools: StructuredToolInterface[];
  
  /** Get all tools in the toolkit */
  getTools(): StructuredToolInterface[];
}

Usage Examples:

import { BaseToolkit } from "@langchain/core/tools";

class MathToolkit extends BaseToolkit {
  tools = [
    new CalculatorTool(),
    new StatisticsTool(),
    new GeometryTool()
  ];
}

const toolkit = new MathToolkit();
const allTools = toolkit.getTools();

Tool Utilities

Tool Type Checking

/**
 * Check if object is a LangChain tool
 */
function isLangChainTool(tool: unknown): tool is ToolInterface;

/**
 * Check if tool has structured input
 */
function isStructuredTool(tool: unknown): tool is StructuredToolInterface;

/**
 * Check if object is runnable-like tool
 */
function isRunnableToolLike(tool: unknown): tool is RunnableToolLike;

Usage Examples:

import { isLangChainTool, isStructuredTool } from "@langchain/core/tools";

const myTool = new CalculatorTool();

if (isLangChainTool(myTool)) {
  console.log("This is a LangChain tool");
}

if (isStructuredTool(myTool)) {
  console.log("This tool has structured input");
  console.log("Schema:", myTool.schema);
}

Error Handling

Tool Input Parsing Exception

/**
 * Exception thrown when tool input fails validation
 */
class ToolInputParsingException extends Error {
  /** The tool that failed parsing */
  tool: string;
  /** Original input that failed */
  input: unknown;
  /** Validation error details */
  errors: unknown[];
  
  constructor(message: string, tool: string, input: unknown, errors: unknown[]);
}

Usage Examples:

import { ToolInputParsingException } from "@langchain/core/tools";

try {
  await calculator.invoke({
    operation: "invalid_op", // Invalid enum value
    a: 5,
    b: 3
  });
} catch (error) {
  if (error instanceof ToolInputParsingException) {
    console.log(`Tool ${error.tool} failed parsing:`, error.errors);
  }
}

Types

interface StructuredToolInterface<SchemaT = any, SchemaInputT = any, ToolOutputT = any> {
  name: string;
  description: string;
  schema: SchemaT;
  invoke(input: SchemaInputT, config?: RunnableConfig): Promise<ToolReturnType>;
  call(arg: SchemaInputT, config?: RunnableConfig): Promise<ToolReturnType>;
}

interface ToolInterface<SchemaT = any, SchemaInputT = any, ToolOutputT = any> extends StructuredToolInterface<SchemaT, SchemaInputT, ToolOutputT> {
  returnDirect?: boolean;
  responseFormat?: ResponseFormat;
  verboseParsingErrors?: boolean;
}

type ResponseFormat = "content" | "content_and_artifact";

interface ToolParams<ToolOutputT = unknown> {
  name: string;
  description: string;
  returnDirect?: boolean;
  responseFormat?: ResponseFormat;
  verboseParsingErrors?: boolean;
}

interface StructuredToolParams<SchemaT, ToolOutputT = unknown> extends ToolParams<ToolOutputT> {
  schema: SchemaT;
}

interface DynamicToolInput<ToolOutputT = unknown> extends ToolParams<ToolOutputT> {
  func: (input: string, runManager?: CallbackManagerForToolRun, config?: RunnableConfig) => Promise<ToolOutputT>;
}

interface DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT = unknown> extends StructuredToolParams<SchemaT, ToolOutputT> {
  func: (input: SchemaOutputT, runManager?: CallbackManagerForToolRun, config?: RunnableConfig) => Promise<ToolOutputT>;
}

interface RunnableToolLike {
  name: string;
  description?: string;
  parameters?: Record<string, unknown>;
  invoke(input: unknown, config?: RunnableConfig): Promise<unknown>;
}

interface ToolRunnableConfig extends RunnableConfig {
  /** Additional tool-specific configuration */
  toolConfig?: Record<string, unknown>;
}

type ToolReturnType = string | { content: string; artifact?: unknown };

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