How to use AgentOps with LangChain
Quick answer
Use
agentops.init() to enable automatic tracing of LangChain calls by patching the OpenAI client. Then run your LangChain chains or agents normally; all LLM interactions will be tracked by AgentOps without extra code changes.PREREQUISITES
Python 3.8+OpenAI API keypip install langchain openai agentops
Setup
Install the required packages and set your environment variables for OPENAI_API_KEY and AGENTOPS_API_KEY. AgentOps automatically instruments OpenAI SDK calls used by LangChain.
pip install langchain openai agentops output
Collecting langchain Collecting openai Collecting agentops Successfully installed langchain openai agentops
Step by step
This example shows how to initialize AgentOps to auto-track LangChain calls using the OpenAI client. Run a simple LangChain ChatOpenAI chain and see AgentOps capture the session.
import os
import agentops
from langchain_openai import ChatOpenAI
# Initialize AgentOps with your API key to enable automatic tracing
agentops.init(api_key=os.environ["AGENTOPS_API_KEY"])
# Create a LangChain ChatOpenAI client
chat = ChatOpenAI(model="gpt-4o-mini", temperature=0)
# Run a simple prompt
response = chat.invoke([{"role": "user", "content": "What is RAG in AI?"}])
print("Response:", response.content) output
Response: RAG stands for Retrieval-Augmented Generation, a technique that combines retrieval of relevant documents with generative models to improve accuracy and context.
Common variations
- Use
agentops.init()without parameters to auto-patch OpenAI ifAGENTOPS_API_KEYis set in env vars. - For async LangChain usage,
AgentOpstracks calls the same way. - Works with other OpenAI-based LangChain models like
ChatOpenAIorOpenAIEmbeddings.
import asyncio
import agentops
from langchain_openai import ChatOpenAI
agentops.init() # Uses AGENTOPS_API_KEY from env
async def main():
chat = ChatOpenAI(model="gpt-4o-mini", temperature=0)
response = await chat.ainvoke([{"role": "user", "content": "Explain LangChain."}])
print("Async response:", response.content)
asyncio.run(main()) output
Async response: LangChain is a Python framework for building applications with large language models, enabling chaining, memory, and integrations.
Troubleshooting
- If
AgentOpsdoes not track calls, ensureAGENTOPS_API_KEYis set correctly in your environment. - Verify you are using the OpenAI SDK v1+ and LangChain v0.2+ for compatibility.
- Restart your Python environment after installing
agentopsto ensure patching works.
Key Takeaways
- Initialize
AgentOpswithagentops.init()before running LangChain to enable automatic tracing. - AgentOps patches the OpenAI SDK used by LangChain, requiring no code changes to your chains or agents.
- Ensure environment variables
AGENTOPS_API_KEYandOPENAI_API_KEYare set for authentication. - AgentOps supports both synchronous and asynchronous LangChain usage seamlessly.
- Use the latest LangChain and OpenAI SDK versions for best compatibility with AgentOps.