LangChain Quickstart: Build an AI App in 10 Minutes
LangChain tutorials are everywhere and half of them use APIs that no longer exist. This rewrites the quickstart against the 0.3 interface: one call, one chain, memory, retrieval, tools.
📜 Table of Contents
📖 Keep reading
LangChain Quickstart: From One Call to a RAG Chain
The hard part of LangChain is not the concepts, it is the version. Most tutorials still use the 0.0.x LLMChain and initialize_agent APIs, which fail on a current install. The 0.3 line centers on LCEL: chains built by piping Runnables together.
1. Install and call
pip install -U langchain langchain-openai langchain-community \
langchain-text-splitters langchain-chroma
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
print(llm.invoke("Explain retrieval-augmented generation in one sentence").content)
invoke is the unified entry point; ainvoke and stream mirror it.
2. LCEL
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
prompt = ChatPromptTemplate.from_messages([
("system", "You are a precise technical editor. Answer in three sentences."),
("human", "Explain {topic}"),
])
chain = prompt | llm | StrOutputParser()
print(chain.invoke({"topic": "vector databases"}))
| Old (0.0.x) | New (0.3) |
|---|---|
| LLMChain(llm, prompt) | prompt | llm | parser |
| ConversationChain + Memory | RunnableWithMessageHistory |
| initialize_agent(tools) | create_tool_calling_agent + AgentExecutor |
| RetrievalQA.from_chain_type | create_retrieval_chain |
3. Memory
Memory moved outside the chain into a wrapper:
from langchain_core.chat_history import InMemoryChatMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistory
store = {}
def get_history(sid):
return store.setdefault(sid, InMemoryChatMessageHistory())
chat = RunnableWithMessageHistory(chain, get_history, input_messages_key="topic")
chat.invoke({"topic": "follow-up"}, config={"configurable": {"session_id": "u1"}})
In production, back the history with Redis or a database behind the same interface, and keep only recent turns or a rolling summary.
4. Retrieval
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_openai import OpenAIEmbeddings
from langchain_chroma import Chroma
from langchain.chains import create_retrieval_chain
from langchain.chains.combine_documents import create_stuff_documents_chain
chunks = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=80).split_documents(docs)
vs = Chroma.from_documents(chunks, OpenAIEmbeddings(model="text-embedding-3-small"))
rag_prompt = ChatPromptTemplate.from_messages([
("system", "Answer only from the context below. If it is missing, say you do not know.\n\n{context}"),
("human", "{input}"),
])
rag_chain = create_retrieval_chain(vs.as_retriever(search_kwargs={"k": 4}),
create_stuff_documents_chain(llm, rag_prompt))
print(rag_chain.invoke({"input": "How is annual leave calculated?"})["answer"])
The result also returns context, useful for citations and debugging.
5. Tools
from langchain_core.tools import tool
from langchain.agents import create_tool_calling_agent, AgentExecutor
@tool
def word_count(text: str) -> int:
"""Count characters in a piece of text."""
return len(text)
executor = AgentExecutor(
agent=create_tool_calling_agent(llm, [word_count], prompt),
tools=[word_count], verbose=True)
The docstring is the model's manual; describe purpose and arguments. Group tools by scenario rather than passing twenty at once.
6. Three common traps
- Stale import paths: splitters, embeddings and vector stores moved packages. Check the migration guide on ImportError.
- Chains are Runnables: call
invokewith a dict, not the chain itself. - Print intermediate steps. Adding
RunnableLambda(print)is faster than guessing.
FAQ
LangChain or LlamaIndex? LangChain is broader (tools, agents, providers); LlamaIndex is deeper on indexing and retrieval.
Is LangChain required? No. One model call plus one retrieval step is often cleaner as plain HTTP. The value shows up with many integrations.
How to debug a chain? Insert a print step, or inspect the full output graph.
Can I use domestic models? Yes, most expose OpenAI-compatible endpoints; point base_url at them.
Related
Written by our editorial team; tools listed here are tested or verified against public sources. Links point to official sites or GitHub repos for reference only — no paid placements.