LangChain is a framework for developing applications powered by language models. AgentOps automatically tracks your LangChain agents by simply initializing the SDK at the beginning of your application.

Adding AgentOps to LangChain applications

1

Install the AgentOps SDK and the additional LangChain dependencies

pip install agentops langchain langchain-community
Give us a star on GitHub while you’re at it (you may be our 3,000th 😊)
2

Set up your import statements

Import the following LangChain and AgentOps dependencies

import os
from langchain_community.chat_models import ChatOpenAI
from langchain.agents import initialize_agent, AgentType
from langchain.tools import DuckDuckGoSearchRun
from agentops.integration.callbacks.langchain import LangchainCallbackHandler
3

Set up your LangChain handler to make the calls

Note that you don’t need to set up a separate agentops.init() call, as the LangChain callback handler will automatically initialize the AgentOps client for you.

Set up your LangChain agent with the AgentOps callback handler, and AgentOps will automatically record your LangChain sessions.

handler = LangchainCallbackHandler(api_key=AGENTOPS_API_KEY, tags=['LangChain Example'])

# Define tools for the agent
search_tool = DuckDuckGoSearchRun()
tools = [search_tool]

llm = ChatOpenAI(openai_api_key=OPENAI_API_KEY,
	callbacks=[handler],
	model='gpt-3.5-turbo')

agent = initialize_agent(tools,
	llm,
	agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,
	verbose=True,
	callbacks=[handler], # You must pass in a callback handler to record your agent
	handle_parsing_errors=True)

Set your API key as an .env variable for easy access.

AGENTOPS_API_KEY=<YOUR API KEY>

Read more about environment variables in Advanced Configuration

4

Run your agent

Execute your program and visit app.agentops.ai/traces to observe your LangChain Agent! 🕵️

After your run, AgentOps prints a clickable URL to the console linking directly to your session in the Dashboard

Clickable link to session

Full Examples

import os
from langchain_community.chat_models import ChatOpenAI
from langchain.agents import initialize_agent, AgentType
from langchain.tools import DuckDuckGoSearchRun
from agentops.integration.callbacks.langchain import LangchainCallbackHandler

handler = LangchainCallbackHandler(api_key=AGENTOPS_API_KEY, tags=['LangChain Example'])

# Define tools for the agent
search_tool = DuckDuckGoSearchRun()
tools = [search_tool]

llm = ChatOpenAI(openai_api_key=OPENAI_API_KEY,
	callbacks=[handler],
	model='gpt-3.5-turbo')

agent = initialize_agent(tools,
	llm,
	agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,
	verbose=True,
	callbacks=[handler], # You must pass in a callback handler to record your agent
	handle_parsing_errors=True)