Synthèse automatique
Guide la construction de modèles de prompts LangChain et de chaînes LCEL (séquentielles, parallèles, conditionnelles) avec parseurs de sortie.
Points forts
- Fournit des exemples de code directement réutilisables pour ChatPromptTemplate, MessagesPlaceholder et les parseurs Str/Json
- Couvre les principaux motifs de composition LCEL : RunnableParallel, RunnableBranch et l'enchaînement multi-étapes
- Montre un pipeline complet d'extraction de points clés puis de résumé avec injection de contexte
- Explique clairement le flux de données entre les étapes via des dictionnaires intermédiaires
Limites
- Suppose que l'installation et l'authentification LangChain sont déjà faites et se limite à gpt-4o-mini via OpenAI
- N'aborde ni la gestion d'erreurs, ni le streaming, ni les retries, ni les tests des chaînes
- Ne traite pas des agents, des outils ou du RAG : uniquement les prompts et les chaînes
À utiliser lorsque vous écrivez ou refactorisez des modèles de prompts et des pipelines LCEL en Python avec LangChain.
À éviter si vous n'utilisez pas LangChain ou si votre besoin porte sur des agents, des outils ou une architecture de retrieval RAG.
Analyse de sécurité
SûrThe skill is instructional documentation for building LangChain chains and prompt templates. Declared tools are limited to Read, Write, and Edit, with no bash, network, credential handling, or destructive operations. Code examples are benign and do not exfiltrate data or disable safety controls.
Aucun point d'attention détecté
Comment cette analyse est faiteExemples
Build an LCEL chain that takes an article, extracts 3 key points, then produces a one-sentence summary — use ChatPromptTemplate and StrOutputParser.Create a ChatPromptTemplate with a system message, a MessagesPlaceholder for chat history and a human input, then wire it into a chain with gpt-4o-mini.I need to run summary, keywords and sentiment over the same text in parallel — show me a RunnableParallel setup in LangChain.name: langchain-core-workflow-a description: | Build LangChain chains and prompts for structured LLM workflows. Use when creating prompt templates, building LCEL chains, or implementing sequential processing pipelines. Trigger with phrases like "langchain chains", "langchain prompts", "LCEL workflow", "langchain pipeline", "prompt template". allowed-tools: Read, Write, Edit version: 1.0.0 license: MIT author: Jeremy Longshore jeremy@intentsolutions.io
LangChain Core Workflow A: Chains & Prompts
Overview
Build production-ready chains using LangChain Expression Language (LCEL) with prompt templates, output parsers, and composition patterns.
Prerequisites
- Completed
langchain-install-authsetup - Understanding of prompt engineering basics
- Familiarity with Python type hints
Instructions
Step 1: Create Prompt Templates
from langchain_core.prompts import (
ChatPromptTemplate,
SystemMessagePromptTemplate,
HumanMessagePromptTemplate,
MessagesPlaceholder
)
# Simple template
simple_prompt = ChatPromptTemplate.from_template(
"Translate '{text}' to {language}"
)
# Chat-style template
chat_prompt = ChatPromptTemplate.from_messages([
SystemMessagePromptTemplate.from_template(
"You are a {role}. Respond in {style} style."
),
MessagesPlaceholder(variable_name="history", optional=True),
HumanMessagePromptTemplate.from_template("{input}")
])
Step 2: Build LCEL Chains
from langchain_openai import ChatOpenAI
from langchain_core.output_parsers import StrOutputParser, JsonOutputParser
llm = ChatOpenAI(model="gpt-4o-mini")
# Basic chain: prompt -> llm -> parser
basic_chain = simple_prompt | llm | StrOutputParser()
# Invoke the chain
result = basic_chain.invoke({
"text": "Hello, world!",
"language": "Spanish"
})
print(result) # "Hola, mundo!"
Step 3: Chain Composition
from langchain_core.runnables import RunnablePassthrough, RunnableParallel
# Sequential chain
chain1 = prompt1 | llm | StrOutputParser()
chain2 = prompt2 | llm | StrOutputParser()
sequential = chain1 | (lambda x: {"summary": x}) | chain2
# Parallel execution
parallel = RunnableParallel(
summary=prompt1 | llm | StrOutputParser(),
keywords=prompt2 | llm | StrOutputParser(),
sentiment=prompt3 | llm | StrOutputParser()
)
results = parallel.invoke({"text": "Your input text"})
# Returns: {"summary": "...", "keywords": "...", "sentiment": "..."}
Step 4: Branching Logic
from langchain_core.runnables import RunnableBranch
# Conditional branching
branch = RunnableBranch(
(lambda x: x["type"] == "question", question_chain),
(lambda x: x["type"] == "command", command_chain),
default_chain # Fallback
)
result = branch.invoke({"type": "question", "input": "What is AI?"})
Output
- Reusable prompt templates with variable substitution
- Type-safe LCEL chains with clear data flow
- Composable chain patterns (sequential, parallel, branching)
- Consistent output parsing
Examples
Multi-Step Processing Chain
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
llm = ChatOpenAI(model="gpt-4o-mini")
# Step 1: Extract key points
extract_prompt = ChatPromptTemplate.from_template(
"Extract 3 key points from: {text}"
)
# Step 2: Summarize
summarize_prompt = ChatPromptTemplate.from_template(
"Create a one-sentence summary from these points: {points}"
)
# Compose the chain
chain = (
{"points": extract_prompt | llm | StrOutputParser()}
| summarize_prompt
| llm
| StrOutputParser()
)
summary = chain.invoke({"text": "Long article text here..."})
With Context Injection
from langchain_core.runnables import RunnablePassthrough
def get_context(input_dict):
"""Fetch relevant context from database."""
return f"Context for: {input_dict['query']}"
chain = (
RunnablePassthrough.assign(context=get_context)
| prompt
| llm
| StrOutputParser()
)
result = chain.invoke({"query": "user question"})
Error Handling
| Error | Cause | Solution | |-------|-------|----------| | Missing Variable | Template variable not provided | Check input dict keys match template | | Type Error | Wrong input type | Ensure inputs match expected schema | | Parse Error | Output doesn't match parser | Use more specific prompts or fallback |
Resources
Next Steps
Proceed to langchain-core-workflow-b for agents and tools workflow.
Ingénierie de Prompts
Data & IA
Bonnes pratiques et templates de prompt engineering pour maximiser les résultats IA.
Visualisation de Données
Data & IA
Génère des visualisations de données et graphiques adaptés à vos données.
Architecture RAG
Data & IA
Guide de configuration d'architectures RAG (Retrieval-Augmented Generation).