or run

tessl search
Log in

Version

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/langsmith@0.4.x

docs

index.md
tile.json

tessl/npm-langsmith

tessl install tessl/npm-langsmith@0.4.3

TypeScript client SDK for the LangSmith LLM tracing, evaluation, and monitoring platform.

index.mddocs/api/

API Reference

Complete API documentation for programmatic access to LangSmith.

Overview

The LangSmith API provides comprehensive programmatic access to all platform features. This section documents the Client class, type definitions, and all available methods.

Quick Navigation

Core Client

  • Client Overview - Start here for API overview
  • Client Construction - Setup and configuration
  • Utilities - Helper functions (uuid7, cache, etc.)

Resource Management

Type Reference

  • Schemas - Complete TypeScript types

Method Selection Guide

Quick reference for choosing between similar methods.

Creating Examples

MethodSignatureUse WhenBest For
createExample()(example: ExampleCreate)Single example creationIndividual examples, source run conversion
createExamples() (arrays)({ inputs: [], outputs: [] })Bulk with uniform structureCSV import, parallel arrays, simple bulk data
createExamples() (objects)({ examples: [{...}] })Bulk with per-item configVaried metadata, explicit per-example settings
createLLMExample()(input: string, output: string, options)Text completion datasetsLLM-format data, simple text in/out
createChatExample()(messages: [], response: [], options)Chat conversation datasetsMulti-turn chats, message arrays
uploadExamplesMultipart()({ examples with attachments })Large or binary dataImages, files, attachments

See Examples API for detailed documentation.

Listing Data

MethodReturnsIterationBest ForPerformance
listRuns()AsyncIterable<Run>StreamLarge result sets, real-time processingMemory efficient, no size limit
listProjects()Promise<TracerSession[]>ArraySmall result sets, all-at-onceFast, full array in memory
listDatasets()AsyncIterable<Dataset>StreamMany datasetsMemory efficient
listExamples()AsyncIterable<Example>StreamLarge datasetsMemory efficient
listFeedback()AsyncIterable<Feedback>StreamMany feedback itemsMemory efficient
listGroupRuns()AsyncIterable<Thread>StreamGrouped analytics by conversation/userAggregated stats, efficient
getRunStats()Promise<RunStats>N/AAggregate metrics only (no individual runs)Fastest, minimal data transfer

Key Principle: Use AsyncIterable methods for large result sets (stream processing), Promise<array> methods for small sets.

Tracing Approaches

ApproachControl LevelComplexitySetupUse When
traceable()Low (automatic)Simple1 lineAutomatic function tracing
RunTreeHigh (manual)ComplexMultiple callsFine-grained control, distributed tracing
wrapOpenAI()MediumSimple1 lineOpenAI SDK integration
wrapAnthropic()MediumSimple1 lineAnthropic SDK integration
wrapAISDK()MediumMediumConfig requiredVercel AI SDK integration
wrapSDK()Low-MediumSimple1 lineGeneric SDK, custom APIs
getLangchainCallbacks()MediumSimplePass callbacksLangChain integration

Decision Flow:

  1. Using specific SDK? β†’ Use specialized wrapper (wrapOpenAI, etc.)
  2. Own functions? β†’ Use traceable()
  3. Non-function code or custom events? β†’ Use RunTree
  4. Generic SDK without wrapper? β†’ Use wrapSDK()

Querying Runs

MethodGranularityResponse TypeUse Case
readRun(runId)Single runPromise<Run>Fetch specific run by ID
listRuns({ projectName })Multiple runsAsyncIterable<Run>All runs in project, with filtering
listRuns({ traceId })All runs in traceAsyncIterable<Run>All runs in a trace tree
listRuns({ parentRunId })Children of runAsyncIterable<Run>All child runs of a parent
listRuns({ isRoot: true })Root runs onlyAsyncIterable<Run>Top-level runs without parents
listGroupRuns({ groupBy })Grouped runsAsyncIterable<Thread>Analytics by conversation/session
getRunStats({ projectName })Aggregates onlyPromise<Stats>Summary statistics without individual runs

See Runs API for detailed filtering options.

Feedback Collection

MethodAuth RequiredUse WhenSecurity
createFeedback()API keyDirect server-side accessSecure (API key required)
createPresignedFeedbackToken()API key (creation only)Public feedback collectionToken-based, time-limited
logEvaluationFeedback()API keyFrom evaluator functionsSecure
evaluateRun()API keySingle-run evaluationSecure

Presigned tokens enable feedback collection without exposing API key - ideal for frontend/mobile apps.

Dataset Versioning

OperationMethodUse Case
Auto-versionAdd/modify examplesAutomatic versioning on changes
Tag versionupdateDatasetTag({ tag, asOf })Label specific versions (v1, v2, prod)
Read versionreadDatasetVersion({ asOf })Access historical snapshot
Compare versionsdiffDatasetVersions({ from, to })See what changed between versions
List splitslistDatasetSplits()View train/test/validation splits

Privacy Controls

LevelMethodGranularityFlexibility
Client-widenew Client({ hideInputs: true })All tracesBoolean only
Client-wide selectivenew Client({ hideInputs: fn })All tracesFunction transform
Client-wide patternsnew Client({ anonymizer })All tracesRegex/processor rules
Per-functiontraceable(fn, { processInputs })Specific functionFunction transform
Per-fieldAnonymizer with pathsSpecific fieldsPath-based rules

Recommendation: Use anonymizer for pattern-based PII, hideInputs/Outputs for structural filtering.

API by Use Case

πŸš€ Getting Started

  1. Client Construction - Create and configure client
  2. Projects - Create your first project
  3. Runs - Create your first run

πŸ“Š Data Management

πŸ” Querying & Analytics

πŸ’‘ Advanced Features

Client Methods Overview

Project Operations

// Create, read, update, delete, list projects
createProject(params) β†’ TracerSession
readProject(params) β†’ TracerSession
updateProject(projectId, params) β†’ TracerSession
deleteProject(params) β†’ void
listProjects(params?) β†’ AsyncIterable<TracerSession>
hasProject(params) β†’ boolean
getProjectUrl(params) β†’ string

Run Operations

// Create, read, update, list, share runs
createRun(run) β†’ void
updateRun(runId, update) β†’ void
readRun(runId) β†’ Run
listRuns(params) β†’ AsyncIterable<Run>
shareRun(runId) β†’ string
getRunUrl(params) β†’ string
getRunStats(params) β†’ RunStats

Dataset Operations

// Create, read, update, delete, list, share datasets
createDataset(params) β†’ Dataset
readDataset(params) β†’ Dataset
updateDataset(params) β†’ Dataset
deleteDataset(params) β†’ void
listDatasets(params?) β†’ AsyncIterable<Dataset>
shareDataset(datasetId) β†’ string
indexDataset(params) β†’ void
similarExamples(params) β†’ Example[]

Example Operations

// Create, read, update, delete examples
createExample(example) β†’ Example
createExamples(params) β†’ void
updateExample(params) β†’ Example
updateExamples(examples) β†’ void
listExamples(params) β†’ AsyncIterable<Example>
deleteExample(exampleId) β†’ void

Feedback Operations

// Create, read, update, delete, list feedback
createFeedback(feedback) β†’ Feedback
updateFeedback(feedbackId, update) β†’ void
readFeedback(feedbackId) β†’ Feedback
listFeedback(params) β†’ AsyncIterable<Feedback>
deleteFeedback(feedbackId) β†’ void
createPresignedFeedbackToken(params) β†’ FeedbackIngestToken

Prompt Operations

// Create, pull, push, list prompts
createPrompt(name, params?) β†’ Prompt
pullPrompt(name, params?) β†’ PromptCommit
pushPrompt(name, params) β†’ string
listPrompts(params?) β†’ AsyncIterable<Prompt>
deletePrompt(name) β†’ void
likePrompt(name) β†’ void
unlikePrompt(name) β†’ void

Common Patterns

Initialization

import { Client } from "langsmith";

// Default configuration
const client = new Client();

// Custom configuration
const client = new Client({
  apiKey: process.env.LANGSMITH_API_KEY,
  timeout_ms: 10000,
  autoBatchTracing: true,
});

Async Iteration

// Iterate through all results
for await (const run of client.listRuns({ projectName: "my-project" })) {
  console.log(run.name);
}

// With filtering
for await (const dataset of client.listDatasets({ datasetName: "test" })) {
  console.log(dataset.name);
}

Error Handling

try {
  const run = await client.readRun(runId);
} catch (error) {
  if (error.status === 404) {
    console.error("Run not found");
  } else if (error.status === 401) {
    console.error("Authentication failed");
  } else {
    console.error("API error:", error.message);
  }
}

Type Safety

All API methods are fully typed. Import types from langsmith/schemas:

import type {
  Run,
  RunCreate,
  Dataset,
  Example,
  Feedback,
  TracerSession,
} from "langsmith/schemas";

See Schemas for complete type reference.

Configuration Best Practices

Production Setup

const client = new Client({
  apiKey: process.env.LANGSMITH_API_KEY,
  autoBatchTracing: true,
  tracingSamplingRate: 0.1,  // 10% sampling
  hideInputs: (inputs) => redactPII(inputs),
  blockOnRootRunFinalization: false,
});

Development Setup

const client = new Client({
  apiKey: process.env.LANGSMITH_API_KEY,
  debug: true,  // Log all requests
  blockOnRootRunFinalization: true,  // Ensure traces complete
});

Serverless Setup

const client = new Client({
  apiKey: process.env.LANGSMITH_API_KEY,
  autoBatchTracing: true,
  batchSizeLimit: 10,  // Lower batch size for serverless
});

// Always flush before function ends
await client.awaitPendingTraceBatches();

Related Documentation

Getting Started

Using the API

Advanced Topics