LangGraph-Go Examples
This directory contains working examples demonstrating LangGraph-Go features and patterns. Each example is self-contained and runnable with go run.
Quick Start
# Clone the repository
git clone https://github.com/dshills/langgraph-go.git
cd langgraph-go/examples
# Run any example
cd concurrent_workflow
go run main.go
Examples by Feature
π Concurrent Execution
Level: Intermediate | Time: 5 minutes
Demonstrates concurrent execution of 5 independent nodes that fetch data from different sources (academic papers, news, social media, patents, market data). Shows:
- Fan-out parallelism (5 nodes execute simultaneously)
- Deterministic state merging despite non-deterministic completion order
- Performance speedup measurement (sequential ~4.6s vs parallel ~1.1s)
- Side effect policies for recordable I/O
- Resource control with MaxConcurrentNodes
cd concurrent_workflow
go run main.go
# Expected output:
# - 5 data sources queried in parallel
# - ~4x speedup vs sequential execution
# - Deterministic result merging
Key Concepts:
Options.MaxConcurrentNodes for parallelism control
Next.Many for fan-out routing
SideEffectPolicy.Recordable for replay support
- Deterministic reducer functions
parallel - Simple Parallel Text Processing
Level: Beginner | Time: 2 minutes
A simpler example showing 4 text processing operations running in parallel. Good starting point before concurrent_workflow.
cd parallel
go run main.go
β»οΈ Deterministic Replay
replay_demo - Checkpoint Save and Replay
Level: Advanced | Time: 10 minutes
Demonstrates deterministic replay using seeded random number generation and recorded I/O. Implements a dice game workflow where:
- Original execution records API responses and uses seeded RNG
- Replay execution produces identical results without external calls
- Different runIDs produce different (but still deterministic) random sequences
- Checkpoint save/restore for time-travel debugging
cd replay_demo
go run main.go
# Expected output:
# Part 1: Original execution (makes API calls, records I/O)
# Part 2: Replay execution (uses recorded I/O, no API calls)
# Part 3: Verification (states match exactly)
# Part 4: Different runID (different random sequence)
Key Concepts:
- Seeded RNG via
ctx.Value(graph.RNGKey) for deterministic randomness
Options.ReplayMode for record vs replay
SideEffectPolicy.Recordable for I/O capture
- Checkpoint save/restore with
SaveCheckpointV2/LoadCheckpointV2
- State hash verification for replay correctness
Use Cases:
- Debugging: Replay production failures locally without external dependencies
- Testing: Verify workflow logic with recorded API responses
- Auditing: Reconstruct exact execution flow from checkpoints
- Time Travel: Resume from any checkpoint in execution history
πΎ Checkpoint Management
checkpoint - Basic Checkpoint Save/Resume
Level: Beginner | Time: 3 minutes
Demonstrates basic checkpoint patterns without replay complexity. Shows:
- Saving checkpoints during execution
- Resuming from saved checkpoints
- Checkpoint labeling for named snapshots
cd checkpoint
go run main.go
π€ LLM Integration
llm - Multi-Provider LLM Support
Level: Intermediate | Time: 5 minutes
Demonstrates LLM integration with OpenAI, Anthropic, Google, and Ollama providers. Requires API keys.
cd llm
export OPENAI_API_KEY=your-key
go run main.go
chatbot - Interactive LLM Chatbot
Level: Intermediate | Time: 5 minutes
Build a simple conversational chatbot with memory. Shows:
- Message history management
- Turn-based conversation flow
- Streaming responses
cd chatbot
export OPENAI_API_KEY=your-key
go run main.go
Level: Intermediate | Time: 5 minutes
Demonstrates the tool system with HTTP tool that makes real API requests. Shows:
- Tool definition and registration
- Parameter validation
- Error handling for external calls
- Response parsing
cd tools
go run main.go
π Control Flow
routing - Conditional Routing with Predicates
Level: Beginner | Time: 3 minutes
Shows dynamic routing based on state predicates. Demonstrates:
- Edge predicates for conditional transitions
- Multiple exit paths from a node
- State-based routing decisions
cd routing
go run main.go
π Advanced Workflows
Level: Advanced | Time: 10 minutes
Production-like research workflow with multiple stages, LLM calls, and tool invocations. Demonstrates:
- Multi-stage pipeline (gather β analyze β synthesize)
- LLM + tool integration
- Error handling and retries
- State accumulation across stages
cd research-pipeline
export OPENAI_API_KEY=your-key
go run main.go
Level: Intermediate | Time: 5 minutes
Shows ETL (Extract, Transform, Load) pattern using LangGraph. Good example of non-LLM workflows:
- Data extraction from multiple sources
- Transformation and validation
- Batch processing patterns
cd data-pipeline
go run main.go
Level: Advanced | Time: 10 minutes
Demonstrates human-in-the-loop workflows with approval steps. Shows:
- Workflow pause for human input
- Resume after approval/rejection
- State persistence during pause
- Interactive decision nodes
cd interactive-workflow
go run main.go
π Observability
tracing - OpenTelemetry Integration
Level: Advanced | Time: 10 minutes
Demonstrates observability with OpenTelemetry tracing. Shows:
- Span creation for nodes and edges
- Distributed tracing context propagation
- Metrics collection
- Integration with Jaeger/Zipkin
cd tracing
# Start Jaeger (requires Docker)
docker run -d --name jaeger \
-p 16686:16686 \
-p 4318:4318 \
jaegertracing/all-in-one:latest
go run main.go
# View traces at http://localhost:16686
Level: Advanced | Time: 5 minutes
Benchmarks for comparing concurrent vs sequential execution, checkpoint overhead, and reducer performance.
cd benchmarks
go test -bench=. -benchmem
Example Patterns by Use Case
Building Agent Workflows
- Start with llm for basic LLM integration
- Add tools with tools
- Scale with research-pipeline
- Add human oversight with interactive-workflow
Data Processing Pipelines
- Start with parallel for basic parallelism
- Scale to concurrent_workflow for real-world patterns
- Add ETL patterns with data-pipeline
Production Deployment
- Implement observability with tracing
- Add checkpoint/resume with checkpoint
- Enable replay debugging with replay_demo
- Benchmark performance with benchmarks
Concepts by Example
| Concept |
Example(s) |
| Concurrent execution |
concurrent_workflow, parallel |
| Deterministic replay |
replay_demo |
| Checkpoint/resume |
checkpoint, replay_demo |
| LLM integration |
llm, chatbot, research-pipeline |
| Tool calling |
tools, research-pipeline |
| Conditional routing |
routing |
| State management |
All examples |
| Error handling |
research-pipeline, tools |
| Observability |
tracing |
| Performance tuning |
benchmarks, concurrent_workflow |
Running Examples with Different Configurations
Most examples support configuration via environment variables:
# Adjust concurrency level
export MAX_CONCURRENT_NODES=4
# Enable replay mode
export REPLAY_MODE=true
# Configure timeouts
export NODE_TIMEOUT=30s
export RUN_TIMEOUT=5m
# Run example
go run main.go
Common Patterns
1. Concurrent Fan-Out
// Launch multiple nodes in parallel from a single entry point
opts := graph.Options{
MaxConcurrentNodes: 5,
QueueDepth: 1024,
}
engine := graph.New(reducer, store, emitter, opts)
// All these nodes execute concurrently
engine.Add("fetch_a", nodeA)
engine.Add("fetch_b", nodeB)
engine.Add("fetch_c", nodeC)
// Fan-out from start
engine.AddEdge("start", "fetch_a", nil)
engine.AddEdge("start", "fetch_b", nil)
engine.AddEdge("start", "fetch_c", nil)
See: concurrent_workflow, parallel
2. Deterministic Replay
// Record mode: Capture I/O for later replay
engine := graph.New(reducer, store, emitter, graph.Options{
ReplayMode: false, // Record
StrictReplay: true,
})
// Nodes must use seeded RNG from context
rng := ctx.Value(graph.RNGKey).(*rand.Rand)
randomValue := rng.Intn(100) // Deterministic!
// Replay mode: Use recorded I/O
replayEngine := graph.New(reducer, store, emitter, graph.Options{
ReplayMode: true, // Replay
StrictReplay: true,
})
See: replay_demo
3. Checkpoint Save/Restore
// Save checkpoint after step
err := store.SaveCheckpointV2(ctx, runID, stepID, "label", state, frontier)
// Load checkpoint
checkpoint, err := store.LoadCheckpointV2(ctx, runID, stepID)
// Resume from checkpoint
finalState, err := engine.RunWithCheckpoint(ctx, checkpoint)
See: checkpoint, replay_demo
4. Side Effect Policies
type MyNode struct {
graph.DefaultPolicy
}
// Declare recordable I/O
func (n *MyNode) Effects() graph.SideEffectPolicy {
return graph.SideEffectPolicy{
Recordable: true, // Can be replayed
RequiresIdempotency: true, // Use idempotency keys
}
}
// Pure nodes don't need Effects() - default is no side effects
See: concurrent_workflow, replay_demo
5. Retry Policies
type RobustNode struct {
graph.DefaultPolicy
}
func (n *RobustNode) Policy() graph.NodePolicy {
return graph.NodePolicy{
Timeout: 30 * time.Second,
RetryPolicy: &graph.RetryPolicy{
MaxAttempts: 3,
BaseDelay: time.Second,
MaxDelay: 10 * time.Second,
Retryable: func(err error) bool {
return strings.Contains(err.Error(), "timeout")
},
},
}
}
See: research-pipeline
FAQ
Q: How do I control concurrency level?
A: Set Options.MaxConcurrentNodes. Default is 8. Set to 0 for sequential execution (backward compatible).
See: concurrent_workflow
Q: How do I make replay work with random values?
A: Use the seeded RNG from context: rng := ctx.Value(graph.RNGKey).(*rand.Rand). Never use math/rand directly or crypto/rand in nodes that need replay.
See: replay_demo
Q: How do I add retry logic?
A: Implement Policy() NodePolicy on your node and configure RetryPolicy. The engine automatically retries with exponential backoff.
See: research-pipeline
Q: How do I integrate LLMs?
A: Use the model adapters in graph/model/. Support for OpenAI, Anthropic, Google, and Ollama.
See: llm, chatbot
Q: How do I add observability?
A: Use the OpenTelemetry emitter in graph/emit/otel.go. It emits spans for each node execution.
See: tracing
Q: How do I persist state to a database?
A: Use store.NewMySQLStore() instead of store.NewMemStore(). Requires MySQL/Aurora.
See: Main README for MySQL setup instructions.
Contributing Examples
We welcome new examples! Please:
- Create a new directory under
examples/
- Include a runnable
main.go
- Add comments explaining key concepts
- Update this README with your example
- Test with
go run main.go
- Submit a PR
Example categories we need:
- Multi-modal LLM workflows (vision, audio)
- Integration with specific tools (GitHub, Slack, etc.)
- Industry-specific pipelines (finance, healthcare, etc.)
- Advanced error handling patterns
- Custom reducer patterns
- Streaming response handling
Resources
License
MIT - See LICENSE