Агенты LangChain и концепции инструментов
Разберитесь, как агенты LangChain рассуждают и используют инструменты для выполнения сложных задач, выходящих за рамки простого ответа на вопросы.
«Агенты LangChain и концепции инструментов» — бесплатный урок LangChain / RAG / Vector DBs на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения 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:
- An LLM (e.g.,
ChatOpenAI). - A list of Tools the agent can use.
- 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!
Изучай LangChain / RAG / Vector DBs с ИИ-репетитором — бесплатно
Пиши и запускай код прямо в браузере, получай мгновенную помощь от ИИ-репетитора 24/7 и продолжи учиться на сайте или в приложении.
- Курсы
- 12
- Уроки
- 48
Часто задаваемые вопросы
Урок «Агенты LangChain и концепции инструментов» бесплатный?
Да — полный текст урока «Агенты LangChain и концепции инструментов» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс LangChain / RAG / Vector DBs, подпишись на CoddyKit PRO. Курс LangChain / RAG / Vector DBs содержит 4 уроков всего.
Чему я научусь в уроке «Агенты LangChain и концепции инструментов»?
Разберитесь, как агенты LangChain рассуждают и используют инструменты для выполнения сложных задач, выходящих за рамки простого ответа на вопросы. Ты практикуешь LangChain / RAG / Vector DBs с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать LangChain / RAG / Vector DBs?
Предыдущий опыт не требуется. LangChain / RAG / Vector DBs на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.
Сколько времени занимает урок «Агенты LangChain и концепции инструментов»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке LangChain / RAG / Vector DBs?
Да. Каждый урок LangChain / RAG / Vector DBs включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Агенты LangChain и концепции инструментов
- Создание рабочих процессов RAG с несколькими агентами
- Интеграция внешних API в качестве инструментов
- Память и состояние в агентном RAG