Agent는 사용자의 질문이나 요청을 받고, 그에 맞는 작업을 수행하기 위해 여러 도구(tool)를 선택적으로 호출하는 역할을 합니다. LangChain 에이전트는 주로 Zero-Shot Agent, ReAct 에이전트 등의 형태로 구현되며, 사용자 요청에 따라 여러 작업(예: 웹 검색, 계산, 데이터베이스 질의 등)을 수행할 수 있습니다.
1. 기본 Agent 사용
from langchain.agents import initialize_agent, load_tools
from langchain.llms import OpenAI
# 도구를 로드 (예: 구글 검색 도구)
tools = load_tools(["google-search-results"], api_key="YOUR_GOOGLE_SEARCH_API_KEY")
# OpenAI LLM 생성 (온도 및 기타 파라미터 조정 가능)
llm = OpenAI(temperature=0)
# 에이전트 초기화 (zero-shot-react-description 에이전트 사용)
agent = initialize_agent(tools, llm, agent="zero-shot-react-description", verbose=True)
# 사용자 질문에 대해 에이전트 실행
response = agent.run("What is the capital of France?")
print(response)
2. Custom Tool 생성
from langchain.agents import Tool, initialize_agent
from langchain.llms import OpenAI
# 커스텀 계산 함수 정의
def simple_calculator(query: str) -> str:
try:
# eval 사용은 보안상 주의가 필요합니다. 여기서는 예제 목적으로 사용합니다.
result = eval(query)
return str(result)
except Exception as e:
return f"Error: {e}"
# Tool 객체 생성 (도구 이름, 설명, 함수)
calculator_tool = Tool(
name="Simple Calculator",
func=simple_calculator,
description="Evaluates mathematical expressions. Use this tool when the input is a math expression."
)
# OpenAI LLM 생성
llm = OpenAI(temperature=0)
# 에이전트 초기화 (커스텀 도구 포함)
agent = initialize_agent([calculator_tool], llm, agent="zero-shot-react-description", verbose=True)
# 에이전트 실행 예시: 수학 계산 질문
response = agent.run("Calculate 12 * (3 + 2).")
print(response)
'Data & Research' 카테고리의 다른 글
[Langchain & Langgraph] Table of Contents (0) | 2025.04.03 |
---|---|
[LLM & RAG] LCEL Runnable (0) | 2025.04.03 |
[LLM & RAG] Langchain 기초 - Memory (0) | 2025.04.03 |
[LLM & RAG] Langchain 기초 - Output Parser (0) | 2025.04.03 |
[LLM & RAG] Langchain 기초 - LLM (0) | 2025.04.03 |