Основные компоненты LangChain
Изучите ключевые строительные блоки LangChain, включая LLM, промпты, цепочки и агентов, а также их взаимодействие
«Основные компоненты LangChain» — бесплатный урок AI Agents with LangChain & Autonomous Workflows на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения AI Agents with LangChain & Autonomous Workflows, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс AI Agents with LangChain & Autonomous Workflows содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Welcome to LangChain Core!
Now meet LangChain, a framework for building agents. It gives you modular components you snap together like LEGO bricks.
The Brain: Large Language Models (LLMs)
The agent's brain is the LLM — a model trained on vast text to understand and generate language. LangChain makes it easy to plug into GPT or open-source models.
LLM in Action: A Simple Call
Here's a basic LLM call in LangChain, using a fake model so it runs without any API key.
from langchain_core.llms import FakeListLLM
# Our 'brain' that gives predefined answers
llm = FakeListLLM(responses=[
"The capital of France is Paris.",
"Hello! How can I help you today?"
])
# Ask the LLM a question
response = llm.invoke("What is the capital of France?")
print(response)Guiding the Brain: Prompts
An LLM needs instructions, and those are your prompts — the input text you feed it. Good prompts are crucial for getting the output you want.
Dynamic Prompts: Prompt Templates
For input that changes, use a prompt template: a reusable blueprint with placeholders you fill in at runtime.
from langchain_core.prompts import PromptTemplate
# Define a template with a placeholder '{topic}'
qa_template = """
Answer the following question about {topic}:
Question: {question}
"""
# Create a PromptTemplate object
prompt = PromptTemplate.from_template(qa_template)
# Format the prompt with specific values
formatted_prompt = prompt.format(
topic="Python programming",
question="What is a variable?"
)
print(formatted_prompt)Connecting Steps: Chains
Most agent tasks take several steps. A chain is a predefined sequence that wires LLMs, prompts, and utilities together, passing each output into the next step.
Building a Simple Chain
Here's a simple chain: a prompt template piped into an LLM using LangChain's Runnable interface. The prompt's output feeds straight into the model.
from langchain_core.llms import FakeListLLM
from langchain_core.prompts import PromptTemplate
# 1. Our 'brain'
llm = FakeListLLM(responses=["A variable is a named storage location."])
# 2. Our prompt template
qa_template = """
Explain {concept} in simple terms.
"""
prompt = PromptTemplate.from_template(qa_template)
# 3. Combine them into a chain using '|' operator
# The prompt output goes into the LLM as input
chain = prompt | llm
# Invoke the chain with the input for the template
response = chain.invoke({"concept": "variable"})
print(response)The Orchestrator: Agents
Chains run fixed steps; agents are dynamic. An agent decides which action to take, runs it, observes the result, and repeats until the goal is met.
How Agents Use Components
Agents tie it all together: LLMs for reasoning, prompts to guide thinking, chains for multi-step work, and tools to act on the real world.
Putting it All Together
Picture a smart assistant: a prompt sets the task, the LLM reasons, a chain processes input, and the agent picks a weather tool — then the LLM formats the answer.
Quick Check: Core Components
Which LangChain component is primarily responsible for dynamic decision-making and tool selection in an AI application?
Recap & Next Steps
Recap: the four LangChain building blocks — LLMs (the brain), prompts (instructions), chains (sequences), and agents (dynamic deciders). Next: build one.
Часто задаваемые вопросы
Урок «Основные компоненты LangChain» бесплатный?
Да — полный текст урока «Основные компоненты LangChain» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс AI Agents with LangChain & Autonomous Workflows, подпишись на CoddyKit PRO. Курс AI Agents with LangChain & Autonomous Workflows содержит 4 уроков всего.
Чему я научусь в уроке «Основные компоненты LangChain»?
Изучите ключевые строительные блоки LangChain, включая LLM, промпты, цепочки и агентов, а также их взаимодействие Ты практикуешь AI Agents with LangChain & Autonomous Workflows с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать AI Agents with LangChain & Autonomous Workflows?
Предыдущий опыт не требуется. AI Agents with LangChain & Autonomous Workflows на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.
Сколько времени занимает урок «Основные компоненты LangChain»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке AI Agents with LangChain & Autonomous Workflows?
Да. Каждый урок AI Agents with LangChain & Autonomous Workflows включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Понимание интеллектуальных агентов и моделей LLM
- Основные компоненты LangChain
- Создание первого простого агента
- Память и состояние диалога для агентов