Маршрутизация и условные цепочки
Создавайте цепочки, которые динамически выбирают путь на основе входных данных и направляют каждый запрос в наиболее подходящую подцепочку для более интеллектуальных разветвляющихся процессов.
«Маршрутизация и условные цепочки» — бесплатный урок AI Agents with LangChain & Autonomous Workflows на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения AI Agents with LangChain & Autonomous Workflows, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс AI Agents with LangChain & Autonomous Workflows содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Beyond Straight-Line Chains
Sequential chains always run the same steps in order. But real workflows branch: a billing question and a coding question need different handling.
This lesson covers routing chains that choose a path based on the input.
What a Router Does
A router inspects the input, decides which destination chain best fits, and forwards the input there. It is a dispatcher in front of several specialist chains.
input -> router -> { billing_chain | code_chain | general_chain }Defining Destination Chains
Each destination is a normal chain tuned for one kind of task, with its own prompt and configuration.
billing = LLMChain(llm=llm, prompt=billing_prompt)
coding = LLMChain(llm=llm, prompt=coding_prompt)Describing Each Route
The router needs to know what each destination is for. Provide a name and a short description so it can match an input to the right one.
routes = [
{'name': 'billing', 'description': 'invoices, refunds, payments'},
{'name': 'coding', 'description': 'programming and debugging help'}
]LLM-Based Routing
One approach asks the LLM itself to classify the input and name the destination. It is flexible and handles fuzzy intent, but adds a model call and some unpredictability.
# router prompt asks model to output: {'destination': 'billing', 'input': ...}Rule-Based Routing
When intent is clear from structure, a deterministic function can route faster and cheaper than an LLM.
def route(query):
if 'refund' in query.lower():
return 'billing'
return 'general'The Default Route
Some inputs match no specialist. Always provide a default destination so the chain never fails on an unexpected request.
default_chain = LLMChain(llm=llm, prompt=general_prompt)Composing the Router Chain
LangChain's routing chain ties the router, the destination map, and the default together into a single callable that picks the path automatically.
from langchain.chains.router import MultiPromptChain
chain = MultiPromptChain(
router_chain=router,
destination_chains={'billing': billing, 'coding': coding},
default_chain=default_chain)Handling Misroutes
Routing is a prediction and can be wrong. Log the chosen destination, let a destination decline and fall back, and monitor misroute rates so you can refine descriptions over time.
LLM vs Rule-Based Tradeoffs
Choose your router by the situation:
- Rules: fast, cheap, deterministic; brittle for fuzzy intent
- LLM: flexible, handles nuance; slower, costs a call, less predictable
Hybrids use rules first and fall back to the LLM.
A Routing Workflow
Putting it together:
- Build specialist destination chains
- Describe each route clearly
- Choose rule-based, LLM-based, or hybrid routing
- Always include a default and monitor misroutes
Quick Check
Test your understanding of routing chains.
Recap
You learned to build branching, conditional chains.
- A router dispatches input to specialist destination chains
- Routing can be rule-based, LLM-based, or hybrid
- Clear route descriptions improve accuracy
- Always include a default and monitor misroutes
Часто задаваемые вопросы
Урок «Маршрутизация и условные цепочки» бесплатный?
Да — полный текст урока «Маршрутизация и условные цепочки» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс AI Agents with LangChain & Autonomous Workflows, подпишись на CoddyKit PRO. Курс AI Agents with LangChain & Autonomous Workflows содержит 4 уроков всего.
Чему я научусь в уроке «Маршрутизация и условные цепочки»?
Создавайте цепочки, которые динамически выбирают путь на основе входных данных и направляют каждый запрос в наиболее подходящую подцепочку для более интеллектуальных разветвляющихся процессов. Ты практикуешь AI Agents with LangChain & Autonomous Workflows с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать AI Agents with LangChain & Autonomous Workflows?
Предыдущий опыт не требуется. AI Agents with LangChain & Autonomous Workflows на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Маршрутизация и условные цепочки»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке AI Agents with LangChain & Autonomous Workflows?
Да. Каждый урок AI Agents with LangChain & Autonomous Workflows включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Введение в цепочки LangChain
- Последовательные и простые цепочки
- Настройка логики цепочек
- Маршрутизация и условные цепочки