npm package: @plott-ai/sdk-langgraph
Description: LangGraph integration for Plott Analytics
Author: Plott Analytics
Latest version: 0.0.1-alpha.0

# @plott-ai/sdk-langgraph

[![npm version](https://badge.fury.io/js/@plott-ai/sdk-langgraph.svg)](https://badge.fury.io/js/@plott-ai/sdk-langgraph)
[![Bundle Size](https://img.shields.io/bundlephobia/minzip/@plott-ai/sdk-langgraph)](https://bundlephobia.com/package/@plott-ai/sdk-langgraph)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

LangGraph integration for Plott Analytics - Seamlessly track your LangGraph agent executions with zero code changes.

## Features

- 🤖 **Zero Code Changes** - Drop-in replacement for LangGraph graphs
- 📊 **Automatic Tracking** - Captures states, messages, and errors automatically
- 🔄 **State Monitoring** - Track state changes and transitions
- ⚡ **Performance Insights** - Monitor execution time and resource usage
- 🧠 **Agent Analytics** - Understand agent behavior patterns
- 🔍 **Debug Support** - Enhanced debugging with execution traces

## Installation

```bash
npm install @plott/sdk-langgraph @plott/sdk-core
# or
pnpm add @plott/sdk-langgraph @plott/sdk-core
# or
yarn add @plott/sdk-langgraph @plott/sdk-core
```

### Peer Dependencies

This package requires the following peer dependencies:

```bash
npm install @langchain/core @langchain/langgraph
```

## Quick Start

Simply wrap your existing LangGraph with `PlottTrackedGraph`:

```typescript
import { PlottTrackedGraph } from '@plott-ai/sdk-langgraph'
import { PlottAnalytics } from '@plott-ai/sdk-core'
import { StateGraph } from '@langchain/langgraph'

// Initialize Plott Analytics
const plott = new PlottAnalytics({
  apiKey: 'your-api-key',
  baseUrl: 'https://api.plott-analytics.com'
})

// Create your LangGraph as usual
const workflow = new StateGraph(/* your state definition */)
  .addNode('agent', agentNode)
  .addNode('tools', toolsNode)
  .addEdge('agent', 'tools')
  // ... more nodes and edges

const graph = workflow.compile()

// Wrap with Plott tracking - no other changes needed!
const trackedGraph = new PlottTrackedGraph(graph, plott, {
  runId: 'unique-run-id',
  userId: 'user-123',
  sessionId: 'session-456'
})

// Use exactly like your original graph
const result = await trackedGraph.invoke({
  messages: [{ role: 'user', content: 'Hello!' }]
})
```

## Configuration

```typescript
interface TrackingConfig {
  runId?: string           // Unique identifier for this execution
  userId?: string          // User identifier
  sessionId?: string       // Session identifier
  trackStates?: boolean    // Track state changes (default: true)
  trackMessages?: boolean  // Track message events (default: true)
  trackErrors?: boolean    // Track errors (default: true)
  trackPerformance?: boolean // Track timing metrics (default: true)
  customContext?: Record<string, unknown> // Additional context
}

const trackedGraph = new PlottTrackedGraph(graph, plott, {
  runId: crypto.randomUUID(),
  userId: 'user-123',
  sessionId: 'session-456',
  trackStates: true,
  trackMessages: true,
  trackErrors: true,
  trackPerformance: true,
  customContext: {
    experimentId: 'exp-789',
    version: '1.2.0'
  }
})
```

## What Gets Tracked

### 1. State Changes
Every state transition in your graph:

```typescript
// Automatically tracked
{
  type: 'STATE_SNAPSHOT',
  snapshot: { /* current state */ },
  context: {
    runId: 'run-123',
    nodeId: 'agent',
    transitionType: 'automatic'
  }
}
```

### 2. Messages
All message events from your agents:

```typescript
// Automatically tracked
{
  type: 'MESSAGE',
  role: 'assistant',
  content: 'I can help you with that...',
  context: {
    runId: 'run-123',
    turnId: 'turn-456',
    model: 'gpt-4'
  }
}
```

### 3. Errors
Any errors during execution:

```typescript
// Automatically tracked
{
  type: 'ERROR',
  error: {
    name: 'ValidationError',
    message: 'Invalid state transition',
    stack: '...'
  },
  context: {
    runId: 'run-123',
    nodeId: 'agent'
  }
}
```

### 4. Performance Metrics
Execution timing and resource usage:

```typescript
// Automatically tracked
{
  type: 'CUSTOM',
  value: {
    executionTime: 1500,
    nodeCount: 5,
    stateTransitions: 3
  },
  context: {
    runId: 'run-123'
  }
}
```

## Advanced Usage

### Custom Event Tracking

Add your own events alongside automatic tracking:

```typescript
// During graph execution
await plott.track({
  type: 'CUSTOM',
  value: {
    tool: 'web_search',
    query: 'latest news',
    results: 10
  },
  context: {
    runId: trackedGraph.config.runId,
    nodeId: 'tools'
  }
})
```

### Conditional Tracking

```typescript
const trackedGraph = new PlottTrackedGraph(graph, plott, {
  runId: 'run-123',
  trackStates: process.env.NODE_ENV === 'development',
  trackMessages: true,
  trackErrors: true
})
```

### Stream Support

Works with streaming graphs:

```typescript
const stream = await trackedGraph.stream({
  messages: [{ role: 'user', content: 'Hello!' }]
})

for await (const chunk of stream) {
  console.log(chunk)
  // All events are automatically tracked
}
```

## Integration Examples

### With LangChain Agents

```typescript
import { createReactAgent } from '@langchain/langgraph/prebuilt'

const agent = createReactAgent({
  llm: model,
  tools: [searchTool, calculatorTool]
})

const trackedAgent = new PlottTrackedGraph(agent, plott, {
  runId: 'agent-run-123',
  userId: 'user-456'
})

const result = await trackedAgent.invoke({
  messages: [{ role: 'user', content: 'What is 2+2?' }]
})
```

### With Custom State

```typescript
interface MyState {
  messages: BaseMessage[]
  currentStep: string
  data: Record<string, unknown>
}

const workflow = new StateGraph<MyState>({
  messages: {
    value: (left, right) => left.concat(right),
    default: () => []
  },
  currentStep: {
    value: (left, right) => right,
    default: () => 'start'
  },
  data: {
    value: (left, right) => ({ ...left, ...right }),
    default: () => ({})
  }
})

// Add nodes and compile...
const graph = workflow.compile()

const trackedGraph = new PlottTrackedGraph(graph, plott, {
  runId: 'custom-state-run',
  customContext: {
    graphType: 'custom',
    stateSchema: 'MyState'
  }
})
```

## TypeScript Support

Full TypeScript support with proper type inference:

```typescript
import type { PlottTrackedGraph } from '@plott-ai/sdk-langgraph'

// Your graph types are preserved
const trackedGraph: PlottTrackedGraph<MyStateType, MyConfigType> =
  new PlottTrackedGraph(graph, plott, config)
```

## Performance

- **Minimal Overhead**: < 1ms per state transition
- **Async Tracking**: Non-blocking event delivery
- **Batched Events**: Efficient network usage
- **Memory Efficient**: Automatic cleanup of old state snapshots

## License

MIT © Plott Analytics