/AI & 자동화/[Advanced Guide] Building an Action-Taking LLM Agent with the ReAct Pattern Combining Tool Calling and Memory
AI & AutomationLLM 에이전트ReAct

[Advanced Guide] Building an Action-Taking LLM Agent with the ReAct Pattern Combining Tool Calling and Memory

This guide covers how to go beyond a simple chatbot and build a real agent with external API calls and long-term memory. It walks through how the ReAct pattern works and through fully automated, hands-on code examples that combine Tool Call

[Advanced Guide] Building an Action-Taking LLM Agent with the ReAct Pattern Combining Tool Calling and Memory

[Advanced Guide] Building an Action-Taking LLM Agent with the ReAct Pattern Combining Tool Calling and Memory

The pace of LLM progress is remarkable. LLMs have moved beyond simple text generators and are entering a stage where they reason and act like software. Yet the first LLM calls most developers make still amount to a one-way conversation: prompt in $\rightarrow$ text out.

If your product needs to “tell the user today’s weather in Seoul and, based on that, put together a personalized outing plan,” a simple chatbot will not cut it. You have to call external APIs and remember prior conversation.

This post goes beyond LLM theory. It walks through a practical, code-first methodology for building a genuinely intelligent agent by combining working complex logic—external tool use (Tool Calling) and long-term memory (Memory).

Why You Need an Action-Taking Agent, Not Just a Chatbot

The AI we actually want does not merely answer questions. It is given a goal and then plans and executes the sequence of steps needed to achieve it. That is the definition of an agent.

Three core capabilities are required to become an agent:

  1. Reasoning: In what order should I think to achieve the given goal? (→ ReAct pattern)
  2. Action: Can I interact with the outside world based on that reasoning? (→ Tool Calling)
  3. Memory: Can I retain and use past experience and external knowledge? (→ Memory Management)

Only when these three work together do you get complex, service-level automation.

Connecting to the Outside World: How Tool Calling Works and How to Implement It in Depth

Tool Calling (also called Function Calling) is the core mechanism that lets an LLM go beyond its own knowledge: it can invoke a specific external function or API to fetch up-to-date information or computation results.

The key idea is to tell the LLM explicitly, “you can use these capabilities,” and let it decide on its own, “I should use this one.”

Simple Prompting vs. Structured Tool Calling: A Performance Comparison

AspectSimple prompt-based callingStructured Tool Calling
How it worksYou must describe how to use the API in the prompt as text.The LLM decides to call based on a defined function signature (schema).
StabilityLow. Easy to omit or misinterpret in complex logic.Very high. Call parameters are enforced via structured JSON/schema.
ReliabilityLow. Heavily dependent on LLM hallucination.High. Results are verified because real code execution happens.
Best forSimple Q&A, creative writingData lookup, calculation, external system integration—any case that requires execution

Hands-on: Defining and Wiring a Custom Tool

Assume the agent we are building needs an “exchange rate lookup” capability. We will define that as a tool.

Python
import json
from typing import List, Dict, Any
# 실제 환경에서는 LangChain의 Tool 클래스를 사용합니다.

def get_exchange_rate(base_currency: str, target_currency: str) -> str:
    """
    주어진 두 통화 간의 실시간 환율을 조회합니다.
    예시: get_exchange_rate("USD", "KRW") 호출 시, 현재 USD 대비 KRW 환율을 반환합니다.
    """
    print(f"--- [SYSTEM LOG] 환율 API 호출 시도: {base_currency} -> {target_currency} ---")
    # 실제로는 외부 API 호출 로직이 들어갑니다.
    if base_currency == "USD" and target_currency == "KRW":
        return json.dumps({"rate": 1350.5, "source": "Mock_API"})
    return json.dumps({"error": "지원하지 않는 통화 조합입니다."})

# 툴 목록 정의 (LLM에게 제공할 도구들의 메타데이터)
available_tools = [
    {
        "name": "get_exchange_rate",
        "description": "두 통화 간의 현재 환율을 조회하는 함수입니다.",
        "parameters": {
            "type": "object",
            "properties": {
                "base_currency": {"type": "string", "description": "기준 통화 (예: USD)"},
                "target_currency": {"type": "string", "description": "목표 통화 (예: KRW)"}
            },
            "required": ["base_currency", "target_currency"]
        }
    }
]

An Agent That Remembers Over Time: Memory Management Strategy

The moment an agent loses conversational context, its intelligence drops sharply. Memory management determines whether the agent can persist.

Short-term vs. Long-term Memory

  • Short-term memory (context window): The recent conversation still sitting in the current chat. It is strictly limited by how many tokens the LLM can process at once (the context window). (e.g., the last 10 turns)
  • Long-term memory (vector DB): All past conversations, user-uploaded documents, and external knowledge bases are embedded and stored in a vector database. When needed, the agent retrieves relevant information and injects it into context. (the core of RAG)

In a real implementation you combine both. As the conversation grows, the oldest turns are summarized into the context, and important information is stored in a vector DB so it can be retrieved whenever needed. That is the standard approach.

🚀 Putting It Together: The ReAct Pattern and Error Handling

The strongest agents follow the ReAct (Reasoning + Acting) pattern. They solve complex problems through a loop of Thought $\rightarrow$ Action $\rightarrow$ Observation $\rightarrow$ next Thought.

Below is a conceptual flow that combines tool use and error handling on top of this pattern.

Python
# --- 가상의 에이전트 프레임워크 ---

def run_agent_cycle(initial_query: str, tools: dict):
    """
    ReAct 패턴을 사용하여 에이전트의 추론 및 행동 사이클을 실행합니다.
    """
    current_state = initial_query
    max_iterations = 5
    
    print(f"--- [START] 초기 쿼리: {initial_query} ---")

    for i in range(max_iterations):
        print(f"\n===== [Iteration {i+1}] =====")
        
        # 1. Thought (추론): 에이전트가 스스로 생각하는 과정
        thought = f"현재 상태 '{current_state}'를 바탕으로, 어떤 도구를 사용해야 할지 추론합니다."
        print(f"[Thought]: {thought}")
        
        # 2. Action (행동): 가장 적절한 도구와 입력값을 결정
        # (실제로는 LLM이 이 부분을 결정함)
        action_name = "search_weather" # 예시로 결정
        action_input = {"city": "서울", "date": "오늘"}
        print(f"[Action]: {action_name} 실행, 입력: {action_input}")

        try:
            # 3. Tool Execution (도구 실행): 실제 함수 호출
            if action_name in tools:
                tool_function = tools[action_name]
                observation = tool_function(action_input)
                
                # 4. Observation (관찰): 도구 실행 결과
                print(f"[Observation]: {observation}")
                
                # 5. 다음 상태 업데이트: 관찰 결과를 다음 추론의 기반으로 사용
                current_state = f"도구 실행 결과: {observation}. 이제 이 정보를 바탕으로 최종 답변을 구성해야 합니다."
            else:
                current_state = "오류: 정의되지 않은 도구입니다."
                break
                
        except Exception as e:
            # 에러 핸들링: 도구 사용 실패 시, 에러 메시지를 다음 추론에 포함
            error_message = f"도구 실행 중 예외 발생: {str(e)}"
            print(f"[Observation]: {error_message}")
            current_state = error_message
            break
            
    print("\n--- [END] 최종 추론 완료 ---")
    return current_state

# --- 도구 정의 (Tool Definition) ---
def search_weather(params: dict) -> str:
    """도시와 날짜를 받아 현재 날씨 정보를 검색합니다."""
    city = params.get("city")
    date = params.get("date")
    if not city:
        raise ValueError("도시 이름은 필수입니다.")
    return f"'{city}'의 '{date}' 날씨는 맑고 기온은 25도입니다. (API 호출 성공)"

def get_user_profile(user_id: str) -> str:
    """사용자 ID를 받아 프로필 정보를 검색합니다."""
    return f"User ID {user_id}의 프로필은 '프리미엄 회원'입니다."

available_tools = {
    "search_weather": search_weather,
    "get_user_profile": get_user_profile
}

# --- 실행 ---
final_result = run_agent_cycle("이번 주말 서울 날씨와 내 프로필을 알려줘.", available_tools)
print(f"\n[최종 결과 요약]: {final_result}")
확인 정보
✦ ✦ ✦
편집 검토 · Editorial Review

Nodelog는 모든 콘텐츠의 내용과 출처를 공개 전에 검토합니다. 환경(OS·버전)에 따라 결과가 달라질 수 있는 기술 정보는 공식 문서와 함께 확인하며, 검토 기준과 정정 원칙은 편집 정책에서 안내합니다. 오류를 발견하시면 이메일로 제보해 주세요 — 확인 후 신속히 정정합니다.

편집 책임 · Nodelog 기술 편집팀·발행 · ·업데이트 ·
관련 공식 문서LangChain 공식 문서

Comments

Be the first to comment.