LangChain / RAG / Vector DBs · 강의

LangChain 에이전트와 도구 개념

LangChain 에이전트가 추론하고 도구를 사용해 단순한 질문 응답을 넘어 복잡한 작업을 수행하는 방식을 이해합니다.

레슨 1/412개 단계

LangChain 에이전트와 도구 개념은(는) CoddyKit의 무료 LangChain / RAG / Vector DBs 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 LangChain / RAG / Vector DBs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. LangChain / RAG / Vector DBs 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

What are LangChain Agents?

Welcome to Agents! So far, you've learned to build chains that perform a fixed sequence of steps. But what if you need more flexibility?

LangChain Agents are systems that allow an LLM to dynamically decide which actions to take, observe the results, and then decide the next action. Think of them as giving the LLM a 'brain' to reason and 'hands' to interact with the world.

The Agent's Reasoning Loop

Agents operate on a continuous Observe-Think-Act loop:

  • Observe: The agent receives an input (your query) and the results of its last action.
  • Think: The LLM reasons about the current situation and decides what to do next.
  • Act: The agent performs an action, often by using a tool.

This loop continues until the agent determines it has enough information to answer your question or complete its task.

Introducing Tools

An LLM alone can only access the knowledge it was trained on. To perform actions in the real world or access up-to-date information, it needs Tools.

Tools are functions or APIs that an agent can call. They extend the LLM's capabilities, allowing it to:

  • Search the internet for current events.
  • Perform calculations.
  • Query databases.
  • Interact with other applications.

Anatomy of a Tool

Each tool needs a few key pieces of information for the agent to use it effectively:

  • Name: A unique identifier (e.g., 'Google Search').
  • Description: A clear explanation of what the tool does and when it should be used. This is crucial for the LLM's reasoning.
  • Input Schema: What kind of input the tool expects (e.g., a search query string, two numbers).

The LLM reads the descriptions to decide which tool is appropriate for a given step.

Common Built-in Tools

LangChain provides many ready-to-use tools. Here are a couple of popular examples:

  • SerpAPIWrapper: Allows the agent to perform Google searches. Useful for current information or specific data points.
  • LLMMathChain: Enables the agent to perform mathematical calculations. This is more reliable than asking the LLM to do complex math directly.

These tools are like plugins that give your agent superpowers!

Setting Up a Simple Agent

To create an agent, you typically need:

  1. An LLM (e.g., ChatOpenAI).
  2. A list of Tools the agent can use.
  3. An Agent Type or a prompt that defines how the agent should reason (e.g., ReAct framework).

Let's prepare these components to build an agent that can do math!

Agent in Action: Calculator

Here's a Python example of an agent using a custom 'Calculator' tool. The LLM decides when to use the tool based on the question.

Note: For a real application, replace eval() with a secure math parser.

import os
from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor, create_react_agent, Tool
from langchain import hub

# Ensure OPENAI_API_KEY is set in your environment variables

def get_calculator_tool():
    """A simple calculator tool."""
    def calculate(expression: str) -> str:
        try:
            # DANGER: In real apps, use safer math parsers!
            return str(eval(expression))
        except Exception as e:
            return f"Error: {e}"

    return Tool(
        name="Calculator",
        func=calculate,
        description="Useful for when you need to answer questions about math. Input should be a mathematical expression."
    )

def main():
    llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
    tools = [get_calculator_tool()]
    prompt = hub.pull("hwchase17/react") # ReAct agent prompt

    agent = create_react_agent(llm, tools, prompt)
    agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

    print("--- Agent Running ---")
    result = agent_executor.invoke({"input": "What is 123 + 456?"})
    print("\n--- Agent Result ---")
    print(result["output"])

if __name__ == "__main__":
    main()

Tracing Agent's Thought Process

When you run an agent with verbose=True, LangChain shows you the agent's internal monologue:

  • Thought: The LLM's reasoning about the current situation.
  • Action: The tool it decides to use and its input.
  • Observation: The result returned by the tool.

This trace helps you understand how the agent arrived at its answer and debug its behavior.

Different Agent Types

LangChain supports various agent types, each with a specific reasoning strategy:

  • zero-shot-react-description: A general-purpose agent that uses the ReAct framework. It relies heavily on tool descriptions.
  • OpenAIFunctionsAgent: Leverages OpenAI's native function calling capabilities, often leading to more robust and concise tool usage.
  • Others exist for specific use cases or models.

Choosing the right agent type depends on your LLM and task complexity.

Agent Limitations & Considerations

While powerful, agents have limitations:

  • Cost & Latency: Multiple LLM calls and tool invocations can increase cost and response time.
  • Reliability: Agents can still 'hallucinate' or misuse tools if descriptions aren't precise or the LLM struggles with complex reasoning.
  • Security: Tools that interact with external systems (like eval() or APIs) need careful handling to prevent vulnerabilities.

Design your tools and prompts carefully!

Agent Concepts Check

Which of the following statements about LangChain Agents and Tools are TRUE?

Recap: The Power of Agents

You've learned that LangChain Agents empower LLMs to move beyond simple question-answering by enabling them to:

  • Reason dynamically through an 'Observe-Think-Act' loop.
  • Utilize Tools to interact with external data and services.
  • Perform complex tasks that require multiple steps and external interactions.

This combination makes agents incredibly versatile for building intelligent applications!

무료로 시작

AI 튜터와 함께 LangChain / RAG / Vector DBs을(를) 배우세요 — 무료

브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.

코스
12
레슨
48

자주 묻는 질문

“LangChain 에이전트와 도구 개념” 강의는 무료인가요?

네 — “LangChain 에이전트와 도구 개념” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 LangChain / RAG / Vector DBs 강의 전체를 잠금 해제할 수 있습니다. LangChain / RAG / Vector DBs 강의에는 총 4개의 강의가 포함되어 있습니다.

“LangChain 에이전트와 도구 개념”에서 뭘 배우나요?

LangChain 에이전트가 추론하고 도구를 사용해 단순한 질문 응답을 넘어 복잡한 작업을 수행하는 방식을 이해합니다. 브라우저에서 직접 실행하는 실습 코드로 LangChain / RAG / Vector DBs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

LangChain / RAG / Vector DBs을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 LangChain / RAG / Vector DBs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“LangChain 에이전트와 도구 개념” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 LangChain / RAG / Vector DBs 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 LangChain / RAG / Vector DBs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. LangChain 에이전트와 도구 개념
  2. 멀티 에이전트 RAG 워크플로 구축
  3. 외부 API를 도구로 통합
  4. 에이전트형 RAG의 메모리와 상태
← LangChain / RAG / Vector DBs(으)로 돌아가기