LangChain
LangChain
AgentOps로 LangChain 에이전트를 추적하는 방법을 소개해요. 설치, API 키 설정, 그리고 LangchainCallbackHandler를 사용한 통합 예제까지 알아볼게요.
출처: 문서
본문
LangChain은 언어 모델로 구동되는 애플리케이션을 개발하기 위한 프레임워크예요. AgentOps는 LangChain의 콜백 핸들러를 통합해 LangChain 에이전트를 자동으로 추적합니다.
설치 (Installation)
AgentOps와 필요한 LangChain 의존성을 설치하세요.
poetry add agentops langchain langchain-community langchain-openai python-dotenv
uv pip install agentops langchain langchain-community langchain-openai python-dotenv
API 키 설정 (Setting Up API Keys)
AgentOps와 OpenAI에 대한 API 키가 필요해요 (ChatOpenAI가 LangChain에서 흔히 사용되기 때문이에요).
- OPENAI_API_KEY: OpenAI Platform에서
- AGENTOPS_API_KEY: AgentOps Dashboard에서
이것들을 환경 변수나 .env 파일로 설정하세요.
OPENAI_API_KEY="your_openai_api_key_here"
AGENTOPS_API_KEY="your_agentops_api_key_here"
그리고 Python 코드에서 로드합니다.
from dotenv import load_dotenv
import os
load_dotenv()
AGENTOPS_API_KEY = os.getenv("AGENTOPS_API_KEY")
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
사용법 (Usage)
AgentOps를 LangChain과 통합하는 것은 LangchainCallbackHandler를 사용하는 것을 포함합니다.
기본 예제는 다음과 같습니다.
from langchain_community.chat_models import ChatOpenAI
from langchain.agents import initialize_agent, AgentType, Tool # Corrected Tool import
from langchain.tools import DuckDuckGoSearchRun # Example tool
from agentops.integration.callbacks.langchain import LangchainCallbackHandler
# 1. Initialize LangchainCallbackHandler
# AGENTOPS_API_KEY can be passed here or loaded from environment
handler = LangchainCallbackHandler(api_key=AGENTOPS_API_KEY, tags=['LangChain Example'])
# 2. Define tools for the agent
search_tool = DuckDuckGoSearchRun()
tools = [
Tool( # Wrap DuckDuckGoSearchRun in a Tool object
name="DuckDuckGo Search",
func=search_tool.run,
description="Useful for when you need to answer questions about current events or the current state of the world."
)
]
# 3. Configure LLM with the AgentOps handler
# OPENAI_API_KEY can be passed here or loaded from environment
llm = ChatOpenAI(openai_api_key=OPENAI_API_KEY,
callbacks=[handler],
model='gpt-3.5-turbo',
temperature=0) # Added temperature for reproducibility
# 4. Initialize your agent, passing the handler to callbacks
agent = initialize_agent(
tools,
llm,
agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,
verbose=True,
callbacks=[handler],
handle_parsing_errors=True
)
# 5. Run your agent
try:
response = agent.run("Who is the current CEO of OpenAI and what is his most recent public statement?")
print(response)
except Exception as e:
print(f"An error occurred: {e}")
AgentOps Dashboard를 방문해 세션을 확인하세요.