Integrate AgenticAnts with LangChain for automatic tracing of your LLM applications.
Overview
LangChain is the most popular framework for building LLM applications. AgenticAnts provides seamless integration through callbacks and auto-instrumentation.
The integration works through a LangChain callback handler. Attach it per-invocation and every chain, LLM, and tool call is traced.
typescript
import { CallbackHandler } from'@antsplatform/langchain'import { ChatOpenAI } from'@langchain/openai'// ANTS_PLATFORM_PUBLIC_KEY / ANTS_PLATFORM_SECRET_KEY are read from the envconst handler = new CallbackHandler()
const llm = new ChatOpenAI({ model: 'gpt-4' })
const response = await llm.invoke('What is AI?', {
callbacks: [handler],
})
// Automatically traced in AgenticAnts.
Tracing requires Node.js 20+. Set ANTS_PLATFORM_PUBLIC_KEY, ANTS_PLATFORM_SECRET_KEY, and ANTS_PLATFORM_BASE_URL=https://api.agenticants.ai in your environment.
Adding Session, User, and Metadata
For richer traces, pass sessionId, userId, tags, and traceMetadata when constructing the handler:
typescript
import { CallbackHandler } from'@antsplatform/langchain'import { ChatOpenAI } from'@langchain/openai'const handler = new CallbackHandler({
sessionId: 'customer-support',
userId: 'user_123',
tags: ['production'],
traceMetadata: {
environment: 'production',
version: '1.0.0',
},
})
const llm = new ChatOpenAI({ model: 'gpt-4' })
const response = await llm.invoke('Help me with my order', {
callbacks: [handler],
})
Advanced Usage
Chains
Track complex chains:
python
from langchain.chains import ConversationalRetrievalChain
from langchain_openai import ChatOpenAI
from langchain_community.vectorstores import Pinecone
from ants_platform.langchain import CallbackHandler
# Set up components
llm = ChatOpenAI()
vectorstore = Pinecone.from_existing_index('my-index')
# Create the AgenticAnts callback handler
handler = CallbackHandler()
chain = ConversationalRetrievalChain.from_llm(
llm=llm,
retriever=vectorstore.as_retriever(),
)
# Run chain - fully traced!
result = chain.invoke(
{"question": "What are the product features?", "chat_history": []},
config={"callbacks": [handler]},
)
# AgenticAnts captures:# - Question asked# - Documents retrieved# - LLM prompt and response# - Total tokens and cost# - Execution time per step
Agents
Monitor LangChain agents:
typescript
const llm = new ChatOpenAI({ temperature: 0 })
const tools = [new SerpAPI()]
const handler = new CallbackHandler({
sessionId: 'research-agent',
traceMetadata: { agentType: 'zero-shot' },
})
const agent = ZeroShotAgent.fromLLMAndTools(llm, tools)
const executor = new AgentExecutor({ agent, tools })
const result = await executor.invoke(
{ input: "What's the weather in San Francisco?" },
{ callbacks: [handler] },
)
// AgenticAnts tracks:// - Agent planning steps// - Tool calls (SerpAPI)// - LLM reasoning// - Final answer
Memory
Track conversation memory:
python
from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain
memory = ConversationBufferMemory()
chain = ConversationChain(llm=llm, memory=memory)
# Each conversation turn is traced
config = {"callbacks": [handler]}
chain.invoke({"input": "Hi, I'm looking for a laptop"}, config=config)
chain.invoke({"input": "What are some good options under $1000?"}, config=config)
chain.invoke({"input": "Tell me more about the first one"}, config=config)
# AgenticAnts shows:# - Full conversation history# - Memory usage# - Context provided to LLM
LangGraph Integration
For LangGraph (stateful multi-actor applications):
python
from langgraph.graph import StateGraph
from ants_platform.langchain import CallbackHandler
# Define your graph
workflow = StateGraph(AgentState)
# Add nodes
workflow.add_node("researcher", research_node)
workflow.add_node("writer", write_node)
workflow.add_node("editor", edit_node)
# Add edges
workflow.add_edge("researcher", "writer")
workflow.add_edge("writer", "editor")
# Compile with AgenticAnts tracing
app = workflow.compile()
handler = CallbackHandler()
# Run with tracing
result = app.invoke(
{"topic": "AI agents"},
config={"callbacks": [handler]}
)
# AgenticAnts visualizes:# - Complete graph execution# - Each node's input/output# - State transitions# - Timing per node
# Make sure callbacks are passed correctly via config
chain.invoke({"input": query}, config={"callbacks": [handler]}) # Correct# Not this - constructing the chain without passing the handler at invocation
chain.invoke({"input": query}) # Won't be traced
Missing Token Counts
typescript
// Ensure you're using a model that reports usageconst llm = new ChatOpenAI({
model: 'gpt-4', // Reports usage
})
await llm.invoke(prompt, { callbacks: [handler] })
High Credit Usage
python
# Use sampling to reduce costs
callbacks = [handler] if random.random() < 0.1else [] # 10% sampling
chain.invoke({"input": query}, config={"callbacks": callbacks})