HOW-TO · RAG
How to Create Basic LangChain Chains with LCEL
Target environment
Ubuntu 24.04 · Ollama 0.4.x
PREREQUISITES
LangChain installed, Ollama running, Python 3.10+
What this does
LangChain Expression Language (LCEL) provides a declarative way to compose chains using the | pipe operator. Each component (prompt, model, output parser) is a Runnable that can be chained together.
Steps
- Set up the LLM and prompt. Create a ChatOllama instance and a prompt template.
from langchain_ollama import ChatOllama
from langchain.prompts import ChatPromptTemplate
from langchain.schema.output_parser import StrOutputParser
llm = ChatOllama(model="llama3.2", temperature=0.7)
prompt = ChatPromptTemplate.from_template(
"You are a helpful assistant. Answer the question: {question}"
)
- Compose the chain with LCEL. Use the pipe operator to connect prompt, model, and parser.
chain = prompt | llm | StrOutputParser()
- Invoke the chain. Call
invokewith input matching the prompt variables.
result = chain.invoke({"question": "What is the capital of France?"})
print(result)
# Output: The capital of France is Paris.
- Add a RunnablePassthrough for debugging. Inject intermediate values without disrupting the chain.
from langchain.schema.runnable import RunnablePassthrough
chain = (
RunnablePassthrough.assign(question=lambda x: x["question"])
| prompt
| llm
| StrOutputParser()
)
- Batch multiple inputs. LCEL supports batching natively.
results = chain.batch([
{"question": "What is 2+2?"},
{"question": "What is the capital of Japan?"}
])
for r in results:
print(r)
Verification
python -c "
from langchain_ollama import ChatOllama
from langchain.prompts import ChatPromptTemplate
from langchain.schema.output_parser import StrOutputParser
llm = ChatOllama(model='llama3.2')
prompt = ChatPromptTemplate.from_template('Say: {word}')
chain = prompt | llm | StrOutputParser()
print(chain.invoke({'word': 'hello'}))
# Expected: hello
"
Common failures
- Missing output parser. Forgetting
StrOutputParser()returns anAIMessageobject instead of a string. - Prompt variable mismatch. Template expects
{question}butinvokepasses{query}. Keys must match exactly. - Ollama not running. Chain hangs or raises
ConnectionError. Verify withollama list. - Version mismatch - The installed package or runtime differs from the command shown; check the version first and rerun the smallest verification command.
- Local environment drift - Another service, virtual environment, model, or path is being used; print the active binary path and configuration before changing the guide steps.
Related guides
- How to Compose Multiple Chains with Pipe Operator
- How to Build Custom LLM Chain with Prompt Templates