CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-langchain--langgraph-sdk

TypeScript/JavaScript SDK for interacting with the LangGraph REST API server

Overview
Eval results
Files

client.mddocs/

Core Client API

The core Client API provides the foundation for all interactions with LangGraph API servers, including client configuration, authentication, and access to all resource-specific clients.

Capabilities

Client Class

The main Client class provides centralized access to all LangGraph resources and handles authentication, request management, and base configuration.

/**
 * Main LangGraph API client providing access to all LangGraph resources
 * @template TStateType - Type of thread state values
 * @template TUpdateType - Type of state updates
 * @template TCustomEventType - Type of custom stream events
 */
class Client<
  TStateType = DefaultValues,
  TUpdateType = TStateType,
  TCustomEventType = unknown
> {
  /** Client for managing assistants */
  assistants: AssistantsClient;

  /** Client for managing threads */
  threads: ThreadsClient<TStateType, TUpdateType>;

  /** Client for managing runs */
  runs: RunsClient<TStateType, TUpdateType, TCustomEventType>;

  /** Client for managing scheduled cron jobs */
  crons: CronsClient;

  /** Client for key-value store operations */
  store: StoreClient;

  /**
   * Create a new LangGraph client
   * @param config - Optional client configuration
   */
  constructor(config?: ClientConfig);
}

type DefaultValues = Record<string, any>;

Usage Examples:

import { Client } from "@langchain/langgraph-sdk";

// Basic client with default configuration
const client = new Client();

// Client with custom API endpoint and key
const client = new Client({
  apiUrl: "https://api.langgraph.example.com",
  apiKey: "your-api-key"
});

// Client with advanced configuration
const client = new Client({
  apiUrl: "https://api.langgraph.example.com",
  apiKey: "your-api-key",
  timeoutMs: 30000,
  defaultHeaders: {
    "User-Agent": "MyApp/1.0"
  },
  callerOptions: {
    maxRetries: 3,
    maxConcurrency: 2
  }
});

// Access resource clients
const assistant = await client.assistants.get("assistant-id");
const thread = await client.threads.create();

Client Configuration

Configuration interface for customizing client behavior, authentication, and HTTP options.

/**
 * Configuration options for the LangGraph client
 */
interface ClientConfig {
  /**
   * API endpoint URL. Defaults to http://localhost:8123
   * Remove trailing slash if present
   */
  apiUrl?: string;

  /**
   * API authentication key. Can also be set via environment variables:
   * LANGGRAPH_API_KEY, LANGSMITH_API_KEY, or LANGCHAIN_API_KEY
   */
  apiKey?: string;

  /** HTTP client configuration options */
  callerOptions?: AsyncCallerParams;

  /** Request timeout in milliseconds */
  timeoutMs?: number;

  /** Default headers to include with all requests */
  defaultHeaders?: Record<string, string | undefined | null>;

  /** Request interceptor function */
  onRequest?: RequestHook;
}

/**
 * Request interceptor hook for modifying requests before they are sent
 * @param url - The request URL
 * @param init - The request initialization options
 * @returns Modified request initialization options
 */
type RequestHook = (url: URL, init: RequestInit) => Promise<RequestInit> | RequestInit;

/**
 * HTTP client configuration options
 */
interface AsyncCallerParams {
  /** Maximum number of retry attempts (default: 4) */
  maxRetries?: number;

  /** Maximum concurrent requests (default: 4) */
  maxConcurrency?: number;

  /** Custom fetch implementation */
  fetch?: typeof fetch;

  /** Callback for failed response handling */
  onFailedResponseHook?: (response: Response, request: RequestInit) => void;
}

Usage Examples:

import { Client } from "@langchain/langgraph-sdk";

// Client with request interceptor
const client = new Client({
  apiUrl: "https://api.langgraph.example.com",
  onRequest: async (url, init) => {
    // Add custom headers or modify request
    return {
      ...init,
      headers: {
        ...init.headers,
        "X-Request-ID": generateRequestId()
      }
    };
  }
});

// Client with retry configuration
const client = new Client({
  callerOptions: {
    maxRetries: 5,
    maxConcurrency: 10,
    onFailedResponseHook: (response, request) => {
      console.error(`Request failed: ${response.status}`);
    }
  }
});

API Key Management

Utility function for resolving API keys from various sources with precedence order.

/**
 * Get the API key from environment variables with precedence order
 * @param apiKey - Optional API key provided as an argument
 * @returns The resolved API key or undefined if not found
 *
 * Precedence:
 * 1. Explicit apiKey argument
 * 2. LANGGRAPH_API_KEY environment variable
 * 3. LANGSMITH_API_KEY environment variable
 * 4. LANGCHAIN_API_KEY environment variable
 */
function getApiKey(apiKey?: string): string | undefined;

Usage Examples:

import { getApiKey, Client } from "@langchain/langgraph-sdk";

// Explicitly check API key availability
const apiKey = getApiKey();
if (!apiKey) {
  throw new Error("API key not found");
}

// Use with client
const client = new Client({ apiKey: getApiKey() });

// Let client handle API key resolution automatically
const client = new Client(); // Will use getApiKey() internally

Fetch Override

Global fetch implementation override for custom HTTP handling or testing scenarios.

/**
 * Override the global fetch implementation used by the client
 * @param fetchImpl - Custom fetch implementation to use
 */
function overrideFetchImplementation(fetchImpl: typeof fetch): void;

Usage Examples:

import { overrideFetchImplementation } from "@langchain/langgraph-sdk";
import fetch from "node-fetch";

// Use node-fetch in Node.js environments
overrideFetchImplementation(fetch as any);

// Use custom fetch with logging
overrideFetchImplementation(async (url, init) => {
  console.log(`Making request to ${url}`);
  const response = await fetch(url, init);
  console.log(`Response status: ${response.status}`);
  return response;
});

Error Handling

The client handles various error scenarios and provides detailed error information:

import { Client } from "@langchain/langgraph-sdk";

try {
  const client = new Client({
    apiUrl: "https://api.langgraph.example.com",
    apiKey: "invalid-key"
  });

  const assistant = await client.assistants.get("assistant-id");
} catch (error) {
  if (error.status === 401) {
    console.error("Authentication failed - check API key");
  } else if (error.status === 404) {
    console.error("Assistant not found");
  } else {
    console.error("Request failed:", error.message);
  }
}

Environment Configuration

The client respects various environment variables for configuration:

  • LANGGRAPH_API_KEY - Primary API key environment variable
  • LANGSMITH_API_KEY - Alternative API key environment variable
  • LANGCHAIN_API_KEY - Fallback API key environment variable
# Set API key via environment
export LANGGRAPH_API_KEY="your-api-key"

# Client will automatically detect and use the key
const client = new Client({
  apiUrl: "https://api.langgraph.example.com"
});

Type Safety

The client supports full type safety with generic type parameters:

interface MyState {
  messages: Message[];
  user_id: string;
}

interface MyUpdate {
  new_message: Message;
}

// Typed client with custom state types
const client = new Client<MyState, MyUpdate>({
  apiUrl: "https://api.langgraph.example.com",
  apiKey: "your-api-key"
});

// Type-safe operations
const thread = await client.threads.create(); // Returns Thread<MyState>
const state = await client.threads.getState(thread.thread_id); // Returns ThreadState<MyState>

Install with Tessl CLI

npx tessl i tessl/npm-langchain--langgraph-sdk

docs

assistants.md

auth.md

client.md

crons.md

index.md

react.md

runs.md

store.md

threads.md

tile.json