0Pricing
AI Engineering Academy · Lección

Arquitectura de LangChain y abstracciones principales

Comprenderá el modelo de componentes de LangChain, incluidos LLMs, ChatModels, PromptTemplates, OutputParsers y Runnables, y cómo se combinan en pipelines.

Arquitectura de LangChain y abstracciones principales es una lección gratuita de AI Engineering Academy en CoddyKit. Esta es la lección 1 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 Engineering Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de AI Engineering Academy incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

What LangChain Actually Is

LangChain is a framework for building applications powered by language models. Rather than writing raw API calls and glue code yourself, LangChain provides reusable components that snap together into pipelines. It supports multiple LLM providers (OpenAI, Anthropic, Cohere, local models) through a unified interface, so switching providers requires minimal code changes.

The Component Model Overview

LangChain organizes its building blocks into distinct component categories. LLMs and ChatModels wrap model providers. PromptTemplates manage dynamic prompt construction. OutputParsers transform raw model text into structured Python objects. Runnables are the universal interface that ties everything together into composable pipelines.

LLMs vs ChatModels

LangChain distinguishes between two model interfaces. LLM takes a string prompt and returns a string completion — the older text-completion style. ChatModel takes a list of messages (system, human, AI) and returns a message object. Modern OpenAI, Anthropic, and Gemini models are all ChatModels. You should prefer ChatModel for new applications.

from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage, SystemMessage

llm = ChatOpenAI(model='gpt-4o-mini')
response = llm.invoke([
    SystemMessage(content='You are a helpful assistant.'),
    HumanMessage(content='What is LangChain?')
])
print(response.content)

PromptTemplates: Dynamic Prompts

PromptTemplate lets you define a prompt with placeholder variables that get filled in at runtime. ChatPromptTemplate does the same for chat-style prompts with multiple messages. Templates separate the prompt structure from the runtime values, making prompts reusable, testable, and easy to version-control.

from langchain_core.prompts import ChatPromptTemplate

template = ChatPromptTemplate.from_messages([
    ('system', 'You are an expert in {domain}.'),
    ('human', 'Explain {concept} in simple terms.')
])

# Fill in variables at runtime
messages = template.invoke({'domain': 'machine learning', 'concept': 'embeddings'})
print(messages)

OutputParsers: Shaping Model Output

OutputParsers convert the raw string output from a model into structured Python types. StrOutputParser simply extracts the content string. JsonOutputParser parses JSON. PydanticOutputParser validates against a Pydantic schema. Parsers also generate format instructions that you can inject into prompts to guide the model toward the expected format.

from langchain_core.output_parsers import StrOutputParser, JsonOutputParser
from pydantic import BaseModel

class MovieReview(BaseModel):
    title: str
    rating: int
    summary: str

parser = JsonOutputParser(pydantic_object=MovieReview)
# parser.get_format_instructions() returns JSON schema instructions
print(parser.get_format_instructions()[:200])

The Runnable Interface

Every LangChain component implements the Runnable interface, which defines three key methods: invoke() for synchronous single calls, stream() for token-by-token streaming, and batch() for processing multiple inputs in parallel. Because every component is a Runnable, they can all be composed uniformly using the pipe operator.

from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model='gpt-4o-mini')

# Single call
result = llm.invoke('What is 2+2?')

# Streaming tokens
for chunk in llm.stream('Tell me a joke.'):
    print(chunk.content, end='', flush=True)

# Batch processing
results = llm.batch(['What is Paris?', 'What is Rome?'])

Composing with the Pipe Operator

The pipe operator (|) is syntactic sugar for creating RunnableSequence objects. When you write prompt | llm | parser, LangChain creates a chain where the output of each step flows into the input of the next. This is the core of LCEL — LangChain Expression Language — and replaces the older verbose chain classes.

from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser

prompt = ChatPromptTemplate.from_template('Summarize this in one sentence: {text}')
llm = ChatOpenAI(model='gpt-4o-mini')
parser = StrOutputParser()

# Chain composed with pipe operator
chain = prompt | llm | parser

result = chain.invoke({'text': 'LangChain is a framework for LLM applications...'})
print(result)

Document Loaders and Text Splitters

For RAG applications, LangChain provides Document Loaders that read files in various formats (PDF, Word, HTML, CSV) and return a list of Document objects with page_content and metadata fields. Text Splitters then divide long documents into smaller chunks suitable for embedding and retrieval.

from langchain_community.document_loaders import PyPDFLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter

loader = PyPDFLoader('report.pdf')
docs = loader.load()  # List of Document objects

splitter = RecursiveCharacterTextSplitter(
    chunk_size=500,
    chunk_overlap=50
)
chunks = splitter.split_documents(docs)
print(f'Split {len(docs)} pages into {len(chunks)} chunks')

Vector Stores as Runnables

LangChain wraps vector databases (Chroma, Pinecone, pgvector) as VectorStore objects that expose a similarity_search() method. You can convert any VectorStore into a Retriever Runnable with .as_retriever(), making it composable in LCEL chains. The retriever takes a query string and returns the top-k most relevant documents.

from langchain_openai import OpenAIEmbeddings
from langchain_community.vectorstores import Chroma

embeddings = OpenAIEmbeddings()
vectorstore = Chroma.from_documents(chunks, embeddings)

# Convert to Retriever Runnable
retriever = vectorstore.as_retriever(
    search_type='similarity',
    search_kwargs={'k': 5}
)

results = retriever.invoke('How does LangChain work?')
for doc in results:
    print(doc.page_content[:100])

Callbacks and Observability

LangChain's callback system lets you hook into every event in a chain's execution: when an LLM starts, when tokens stream, when a chain finishes, when a tool is called. Built-in callbacks include StdOutCallbackHandler for console logging. Third-party integrations like LangSmith attach automatically via environment variables, capturing full execution traces without code changes.

from langchain.callbacks import StdOutCallbackHandler
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model='gpt-4o-mini',
    callbacks=[StdOutCallbackHandler()]
)
# Now every call logs input/output automatically

# Or enable LangSmith tracing globally:
import os
os.environ['LANGCHAIN_TRACING_V2'] = 'true'
os.environ['LANGCHAIN_API_KEY'] = 'your-key'

Memory and State in Chains

By default, LangChain chains are stateless — each invocation is independent. To add conversational memory, you wrap a chain with a memory component that stores and injects conversation history. RunnableWithMessageHistory is the LCEL-native way to add memory, taking a get_session_history function that loads history by session ID.

from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_community.chat_message_histories import ChatMessageHistory

store = {}  # session_id -> ChatMessageHistory

def get_session_history(session_id: str):
    if session_id not in store:
        store[session_id] = ChatMessageHistory()
    return store[session_id]

with_history = RunnableWithMessageHistory(chain, get_session_history)
response = with_history.invoke(
    {'input': 'Hi, my name is Alice'},
    config={'configurable': {'session_id': 'user-1'}}
)

Quick Check

Test your understanding of LangChain Architecture and Core Abstractions.

Lesson Recap

In this lesson you learned: LangChain's component model organizes LLMs, PromptTemplates, OutputParsers, and Retrievers as Runnables with a unified interface, the pipe operator (|) composes Runnables into sequential chains via LCEL, and callbacks enable observability at every step without changing business logic. Next up we explore building chains with LCEL in depth.

Preguntas frecuentes

¿La lección «Arquitectura de LangChain y abstracciones principales» es gratis?

Sí — el texto completo de «Arquitectura de LangChain y abstracciones principales» 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 Engineering Academy, actualiza a CoddyKit PRO. El curso de AI Engineering Academy incluye 4 lecciones en total.

¿Qué aprenderé en «Arquitectura de LangChain y abstracciones principales»?

Comprenderá el modelo de componentes de LangChain, incluidos LLMs, ChatModels, PromptTemplates, OutputParsers y Runnables, y cómo se combinan en pipelines. Practicas AI Engineering Academy 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 Engineering Academy?

No se requiere experiencia previa. AI Engineering Academy 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 1 de 4.

¿Cuánto tiempo toma la lección «Arquitectura de LangChain y abstracciones principales»?

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 Engineering Academy?

Sí. Cada lección de AI Engineering Academy 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. Arquitectura de LangChain y abstracciones principales
  2. Creación de chains con LCEL
  3. Chains ramificadas y paralelas
  4. Streaming de salida en LangChain
← Volver a AI Engineering Academy