LangChain est le framework de reference pour construire des applications avec des LLMs. En entretien, on evalue la capacite a architecturer des agents robustes, pas juste a faire des POCs.
1Architecture LangChain
Question discriminante
Quels sont les composants principaux de LangChain ?
- LLM / ChatModel — interface unifiee pour appeler GPT, Claude, Gemini, Llama
- Prompt Templates — templates parametrables pour construire les prompts
- Chains — sequences d operations : prompt → LLM → parser → action suivante
- Agents — LLM qui decide dynamiquement quels outils appeler et dans quel ordre
- Tools — fonctions que l agent peut appeler (recherche web, calcul, requetes DB)
- Memory — stockage du contexte de conversation
2LCEL : LangChain Expression Language
Question discriminante
Qu est-ce que LCEL ? Pourquoi remplace-t-il les anciennes LLMChain ?
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
llm = ChatOpenAI(model='gpt-4o-mini')
# LCEL : composition avec l operateur |
prompt = ChatPromptTemplate.from_template(
'Tu es un expert data. Reponds a : {question}'
)
chain = prompt | llm | StrOutputParser()
result = chain.invoke({'question': 'Qu est-ce que dbt ?'})
# RAG chain avec LCEL
rag_chain = (
{'context': retriever, 'question': RunnablePassthrough()}
| prompt
| llm
| StrOutputParser()
)
- LCEL — composition declarative avec l operateur |. Supporte le streaming, le batch et l async nativement
- Avantage — lisible, composable, compatible LangSmith pour le tracing
3Agents et tools : le coeur de LangChain
Question discriminante
Comment creez-vous un agent qui peut interroger une base de donnees et chercher sur le web ?
from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain_core.tools import tool
import duckdb
@tool
def query_sales_db(query: str) -> str:
'''Execute une requete SQL sur la base de ventes.
Utiliser pour repondre aux questions sur les ventes, CA, clients.'''
try:
conn = duckdb.connect('sales.db')
result = conn.execute(query).fetchdf()
return result.to_string()
except Exception as e:
return f'Erreur SQL : {e}'
@tool
def search_web(query: str) -> str:
'''Recherche sur le web des informations actuelles.'''
# implementation avec Tavily, SerpAPI, etc.
...
tools = [query_sales_db, search_web]
agent = create_tool_calling_agent(llm, tools, prompt)
executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
4Memoire et gestion du contexte
Question discriminante
Comment gerez-vous la memoire d un chatbot pour maintenir le contexte de la conversation ?
- ConversationBufferMemory — stocke toute la conversation. Simple mais consomme des tokens
- ConversationSummaryMemory — resume l historique pour economiser les tokens
- ConversationBufferWindowMemory — garde seulement les N derniers echanges
- Persistance — Redis, PostgreSQL, MongoDB pour la memoire persistante entre sessions
- LangGraph checkpointer — persistance du state dans les workflows LangGraph
5LangGraph : agents multi-etapes
Question discriminante
Quand utilisez-vous LangGraph plutot qu un simple agent LangChain ?
- LangGraph — framework pour les agents avec des workflows cycliques et conditionnels. State machine pour les LLMs
- Quand — workflows avec boucles (retry, self-correction), decision conditionnelle, agents paralleles, human-in-the-loop
- Exemple — agent qui ecrit du code, l execute, analyse l erreur, corrige, re-execute jusqu au succes
- Human-in-the-loop — pause du workflow pour validation humaine avant certaines actions critiques
6LangSmith : observabilite des LLMs
Question discriminante
Comment deboguez-vous et monitorez-vous un agent LangChain en production ?
- LangSmith — plateforme de tracing et d evaluation pour les applications LangChain
- Tracing — voir chaque appel LLM, chaque tool call, les tokens consommes, la latence
- Evaluation — noter les reponses (automatique ou humaine) pour mesurer la qualite
- Datasets — constituer des jeux de test pour les regressions
from langchain_anthropic import ChatAnthropic
from langchain_core.prompts import ChatPromptTemplate
from langchain_community.vectorstores import Qdrant
from langchain_openai import OpenAIEmbeddings
from langchain_core.runnables import RunnableParallel, RunnablePassthrough
# RAG avec LCEL (LangChain Expression Language)
embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
vectorstore = Qdrant.from_existing_collection("knowledge_base", embeddings)
retriever = vectorstore.as_retriever(search_kwargs={"k": 5})
prompt = ChatPromptTemplate.from_messages([
("system", "Réponds en te basant uniquement sur ce contexte:
{context}"),
("human", "{question}")
])
llm = ChatAnthropic(model="claude-3-5-sonnet-20241022")
# Chain composable (LCEL)
chain = (
RunnableParallel(context=retriever, question=RunnablePassthrough())
| prompt
| llm
)
# Avec historique de conversation
from langchain_core.chat_history import InMemoryChatMessageHistory
chain_with_history = chain.with_types(input_type=str) .with_config({"run_name": "RAG_conversation"})
- LCEL — LangChain Expression Language : syntaxe pipe pour composer des chains. Plus lisible et plus performant que les classes héritées (LLMChain deprecated)
- LangSmith — tracing et évaluation des chains. Indispensable en prod pour débugger les hallucinations et mesurer faithfulness/relevancy automatiquement
- Agents vs Chains — Chain : séquence fixe d'étapes. Agent : le LLM décide dynamiquement quels outils appeler (search, SQL, API). Plus puissant mais moins prévisible
- Alternatives — LlamaIndex (focus RAG, plus simple à déployer), LangGraph (graphs d'agents avec état), code Python pur (plus de contrôle, moins de magie)
- Memory stratégies — ConversationBufferMemory (tout garder), ConversationSummaryMemory (résumer l'historique), RedisChatMessageHistory (persistance multi-sessions)
- LCEL (LangChain Expression Language) - syntaxe pipe pour composer des chains. Plus lisible et plus performant que les classes heritees (LLMChain deprecated en 2024)
- LangSmith - tracing et evaluation des chains. Indispensable en prod pour debugger les hallucinations et mesurer faithfulness/relevancy automatiquement
- Agents vs Chains - Chain : sequence fixe d etapes. Agent : le LLM decide dynamiquement quels outils appeler. Plus puissant mais moins predictible
- Alternatives - LlamaIndex (focus RAG, plus simple), LangGraph (graphs d agents avec etat), code Python pur (plus de controle, moins de magie noire)
- Memory strategies - ConversationBufferMemory (tout garder), ConversationSummaryMemory (resumer l historique), RedisChatMessageHistory (persistance multi-sessions)
7Grille par niveau
| Niveau | Maitrise | Signal GO | NO-GO |
|---|
| Confirme | LCEL, chains simples, RAG avec LangChain | A construit un RAG avec LCEL, connait la syntaxe | | N utilise que les anciennes LLMChain, ne connait pas LCEL |
| Senior | Agents avec tools, LangGraph, LangSmith, production | A deploye un agent avec tools custom, a trace avec LangSmith, connait LangGraph | N a fait que des POCs, ne sait pas monitorer un agent en production |
1LangChain Architecture
Discriminating question
What are the main components of LangChain?
- LLM / ChatModel — unified interface to call GPT, Claude, Gemini, Llama
- Prompt Templates — parameterizable templates to build prompts
- Chains — sequences of operations: prompt → LLM → parser → next action
- Agents — LLM that dynamically decides which tools to call and in what order
- Tools — functions the agent can call (web search, calculation, DB queries)
- Memory — storage of conversation context
2LCEL: LangChain Expression Language
Discriminating question
What is LCEL? Why does it replace the old LLMChain?
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
llm = ChatOpenAI(model='gpt-4o-mini')
# LCEL : composition with the | operator
prompt = ChatPromptTemplate.from_template(
'You are a data expert. Answer: {question}'
)
chain = prompt | llm | StrOutputParser()
result = chain.invoke({'question': 'What is dbt?'})
# RAG chain with LCEL
rag_chain = (
{'context': retriever, 'question': RunnablePassthrough()}
| prompt
| llm
| StrOutputParser()
)
- LCEL — declarative composition with the | operator. Natively supports streaming, batch and async
- Advantage — readable, composable, compatible with LangSmith for tracing
3Agents and tools: the heart of LangChain
Discriminating question
How do you create an agent that can query a database and search the web?
from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain_core.tools import tool
import duckdb
@tool
def query_sales_db(query: str) -> str:
'''Executes a SQL query on the sales database.
Use to answer questions about sales, revenue, customers.'''
try:
conn = duckdb.connect('sales.db')
result = conn.execute(query).fetchdf()
return result.to_string()
except Exception as e:
return f'SQL Error: {e}'
@tool
def search_web(query: str) -> str:
'''Searches the web for current information.'''
# implementation with Tavily, SerpAPI, etc.
...
tools = [query_sales_db, search_web]
agent = create_tool_calling_agent(llm, tools, prompt)
executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
4Memory and context management
Discriminating question
How do you manage a chatbot's memory to maintain conversation context?
- ConversationBufferMemory — stores the entire conversation. Simple but consumes tokens
- ConversationSummaryMemory — summarizes history to save tokens
- ConversationBufferWindowMemory — keeps only the last N exchanges
- Persistence — Redis, PostgreSQL, MongoDB for persistent memory between sessions
- LangGraph checkpointer — state persistence in LangGraph workflows
5LangGraph: multi-step agents
Discriminating question
When do you use LangGraph rather than a simple LangChain agent?
- LangGraph — framework for agents with cyclic and conditional workflows. State machine for LLMs
- When — workflows with loops (retry, self-correction), conditional decision, parallel agents, human-in-the-loop
- Example — agent that writes code, executes it, analyzes the error, fixes it, re-executes until success
- Human-in-the-loop — workflow pause for human validation before certain critical actions
6LangSmith: LLM observability
Discriminating question
How do you debug and monitor a LangChain agent in production?
- LangSmith — tracing and evaluation platform for LangChain applications
- Tracing — see every LLM call, every tool call, tokens consumed, latency
- Evaluation — score responses (automated or human) to measure quality
- Datasets — build test sets for regression testing
from langchain_anthropic import ChatAnthropic
from langchain_core.prompts import ChatPromptTemplate
from langchain_community.vectorstores import Qdrant
from langchain_openai import OpenAIEmbeddings
from langchain_core.runnables import RunnableParallel, RunnablePassthrough
# RAG with LCEL (LangChain Expression Language)
embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
vectorstore = Qdrant.from_existing_collection("knowledge_base