0Pricing
AI Agents with LangChain & Autonomous Workflows · Lección

Enrutamiento y cadenas condicionales

Construya cadenas que elijan dinámicamente una ruta según la entrada y envíen cada solicitud a la subcadena más adecuada para crear flujos de trabajo ramificados más inteligentes.

Enrutamiento y cadenas condicionales es una lección gratuita de AI Agents with LangChain & Autonomous Workflows en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de AI Agents with LangChain & Autonomous Workflows, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de AI Agents with LangChain & Autonomous Workflows incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en 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

Preguntas frecuentes

¿La lección «Enrutamiento y cadenas condicionales» es gratis?

Sí — el texto completo de «Enrutamiento y cadenas condicionales» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de AI Agents with LangChain & Autonomous Workflows, actualiza a CoddyKit PRO. El curso de AI Agents with LangChain & Autonomous Workflows incluye 4 lecciones en total.

¿Qué aprenderé en «Enrutamiento y cadenas condicionales»?

Construya cadenas que elijan dinámicamente una ruta según la entrada y envíen cada solicitud a la subcadena más adecuada para crear flujos de trabajo ramificados más inteligentes. Practicas AI Agents with LangChain & Autonomous Workflows con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar AI Agents with LangChain & Autonomous Workflows?

No se requiere experiencia previa. AI Agents with LangChain & Autonomous Workflows en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.

¿Cuánto tiempo toma la lección «Enrutamiento y cadenas condicionales»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de AI Agents with LangChain & Autonomous Workflows?

Sí. Cada lección de AI Agents with LangChain & Autonomous Workflows incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Introducción a las cadenas de LangChain
  2. Cadenas secuenciales y sencillas
  3. Personalización de la lógica de las cadenas
  4. Enrutamiento y cadenas condicionales
← Volver a AI Agents with LangChain & Autonomous Workflows