[랭체인] 지능형 에이전트 구축하기steemCreated with Sketch.

in #kr-devlast month (edited)

안녕하세요, 여러분! 오늘은 LangGraph를 사용하여 지능형 에이전트를 구축하는 방법에 대해 알아보겠습니다. LangGraph는 대규모 언어 모델(LLM)을 기반으로 복잡한 워크플로우를 만들 수 있게 해주는 강력한 도구입니다. 이 글에서는 LangGraph의 주요 컴포넌트들을 살펴보고, 간단한 검색 에이전트를 만드는 과정을 단계별로 설명하겠습니다.

1. 필요한 라이브러리 임포트하기

먼저, 필요한 라이브러리들을 임포트합니다:

import operator
from typing import TypedDict, Annotated

from langgraph.graph import StateGraph, END, START

from langchain_openai import ChatOpenAI
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_core.messages import AnyMessage, SystemMessage, HumanMessage, ToolMessage

여기서 StateGraph는 LangGraph의 핵심 컴포넌트로, 에이전트의 워크플로우를 정의하는 데 사용됩니다.

2. 검색 도구 설정하기

우리의 에이전트는 Tavily 검색 API를 사용하여 정보를 찾습니다:

tool = TavilySearchResults(max_results=4)

3. 에이전트 상태 정의하기

에이전트의 상태를 정의하는 클래스를 만듭니다:

class AgentState(TypedDict):
    messages: Annotated[list[AnyMessage], operator.add]

이 상태는 에이전트와 사용자 간의 대화 기록을 저장합니다.

참고: 아래 take_action에서는 LLM이 존재하지 않는 도구 이름을 반환하는 경우를 처리하기 위해 일부 로직이 추가되었습니다. 함수 호출을 사용하더라도 LLM은 때때로 환각을 일으킬 수 있습니다. 이 경우 LLM에 다시 시도하도록 지시하기만 하면 됩니다! 에이전트 조직의 장점입니다.

4. 에이전트 클래스 구현하기

이제 에이전트 클래스를 구현합니다:

class Agent:
    def __init__(self, model, tools, system=""):
        self.system = system
        graph = StateGraph(AgentState)
        graph.add_node("llm", self.call_openai)
        graph.add_node("action", self.take_action)
        graph.add_conditional_edges(
            "llm",
            self.exists_action,
            {True: "action", False: END}
        )
        graph.add_edge("action", "llm")
        graph.set_entry_point("llm")
        self.graph = graph.compile()
        self.tools = {t.name: t for t in tools}
        self.model = model.bind_tools(tools)

    def exists_action(self, state: AgentState):
        result = state['messages'][-1]
        return len(result.tool_calls) > 0

    def call_openai(self, state: AgentState):
        messages = state['messages']
        if self.system:
            messages = [SystemMessage(content=self.system)] + messages
        message = self.model.invoke(messages)
        return {'messages': [message]}

    def take_action(self, state: AgentState):
        tool_calls = state['messages'][-1].tool_calls
        results = []
        for t in tool_calls:
            print(f"Calling: {t}")
            if not t['name'] in self.tools: # LLM에서 잘못된 도구 이름 확인
                print("\n ....bad tool name....")
                result = "bad tool name, retry" # 불량인 경우 LLM에 재시도하도록 지시
            else:
                result = self.tools[t['name']].invoke(t['args'])
            results.append(
                ToolMessage(
                    tool_call_id=t['id'], 
                    name=t['name'], 
                    content=str(result)
                )
            )
        print("Back to the model!")
        return {'messages': results}

이 Agent 클래스는 LLM 호출, 액션 실행, 조건부 로직 처리 등 에이전트의 핵심 기능을 담당합니다.

5. 에이전트 초기화 및 사용하기

에이전트를 초기화하고 사용하는 방법은 다음과 같습니다:

prompt = """당신은 똑똑한 연구 조수입니다. 검색 엔진을 사용하여 정보를 찾습니다. 
여러 번 호출할 수 있습니다(함께 또는 순서대로). 
원하는 정보가 확실할 때만 정보를 찾아보세요. 
후속 질문을 하기 전에 일부 정보를 조회해야 하는 경우에는 그렇게 해도 됩니다!
"""

model = ChatOpenAI(model="gpt-3.5-turbo")
abot = Agent(model, [tool], system=prompt)

messages = [HumanMessage(content="SF와 LA의 날씨는 어떤가요?")]
result = abot.graph.invoke({"messages": messages})

6. 복잡한 쿼리 처리하기

우리의 에이전트는 여러 단계의 추론이 필요한 복잡한 쿼리도 처리할 수 있습니다:

query = """2024년 슈퍼볼 우승팀은 어디인가요? 우승한 팀의 본사는 어느 주에 있나요? 
해당 주의 GDP는 얼마인가요? 각 질문에 답하세요."""
messages = [HumanMessage(content=query)]

model = ChatOpenAI(model="gpt-4")  # 더 고급 모델 사용
abot = Agent(model, [tool], system=prompt)
result = abot.graph.invoke({"messages": messages})

이 예제에서 에이전트는 여러 검색을 수행하고, 결과를 종합하여 복잡한 질문에 답변합니다.

마치며

LangGraph를 사용하면 복잡한 추론 과정을 필요로 하는 지능형 에이전트를 쉽게 구축할 수 있습니다. 이 프레임워크는 LLM의 능력을 최대한 활용하면서도, 개발자가 에이전트의 행동을 세밀하게 제어할 수 있게 해줍니다.

여러분도 이 예제를 바탕으로 자신만의 지능형 에이전트를 만들어보세요. 다양한 도구와 LLM을 조합하여 더욱 강력한 에이전트를 만들 수 있을 것입니다. 즐거운 코딩 되세요!

#LangChain

Posted using Obsidian Steemit plugin

Sort:  

[광고] STEEM 개발자 커뮤니티에 참여 하시면, 다양한 혜택을 받을 수 있습니다.

Congratulations, your post has been upvoted by @upex with a 0.22% upvote. We invite you to continue producing quality content and join our Discord community here. Visit https://botsteem.com to utilize usefull and productive automations #bottosteem #upex

Coin Marketplace

STEEM 0.19
TRX 0.16
JST 0.033
BTC 64349.87
ETH 2775.11
USDT 1.00
SBD 2.65