0Pricing
AI Agents with LangChain & Autonomous Workflows · Aula

Roteamento e cadeias condicionais

Crie cadeias que escolham dinamicamente um caminho com base na entrada, encaminhando cada solicitação à subcadeia mais apropriada para fluxos de trabalho mais inteligentes e ramificados.

Roteamento e cadeias condicionais é uma aula grátis de AI Agents with LangChain & Autonomous Workflows no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de AI Agents with LangChain & Autonomous Workflows, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de AI Agents with LangChain & Autonomous Workflows inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

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

Perguntas Frequentes

A aula “Roteamento e cadeias condicionais” é grátis?

Sim — o texto completo de “Roteamento e cadeias condicionais” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de AI Agents with LangChain & Autonomous Workflows, atualize para CoddyKit PRO. O curso de AI Agents with LangChain & Autonomous Workflows inclui 4 aulas no total.

O que vou aprender em “Roteamento e cadeias condicionais”?

Crie cadeias que escolham dinamicamente um caminho com base na entrada, encaminhando cada solicitação à subcadeia mais apropriada para fluxos de trabalho mais inteligentes e ramificados. Você pratica AI Agents with LangChain & Autonomous Workflows com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar AI Agents with LangChain & Autonomous Workflows?

Nenhuma experiência prévia é necessária. AI Agents with LangChain & Autonomous Workflows no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “Roteamento e cadeias condicionais”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de AI Agents with LangChain & Autonomous Workflows?

Sim. Cada aula de AI Agents with LangChain & Autonomous Workflows inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Introdução às cadeias do LangChain
  2. Cadeias sequenciais e simples
  3. Personalizando a lógica das cadeias
  4. Roteamento e cadeias condicionais
← Voltar para AI Agents with LangChain & Autonomous Workflows