AI Hints
Home›LangChain Tutorial›Wrapping Up
LangChain · Lesson 118 of 120

Cheat Sheet: Agents and RAG

Tools, agents, retrieval.

⏱ 2 min read▶ Video at 2:14:29🎓 Free
Watch this lesson in the LangChain courseWatch on YouTube ↗Full LangChain course

Here's the second reminder page. Tools, agents, middleware, and retrieval. Pause the video, and keep it next to the first one.

Cheat Sheet: Agents and RAG
From the video: Cheat Sheet: Agents and RAG
  • Second reminder page
  • Agents and RAG
  • Pause and keep it

Agents cheat sheet

The tool decorator turns a function into a tool, using its docstring. Create agent takes a model, tools, a system prompt, middleware, and a checkpointer. Each conversation needs a thread ID in the config. The answer is the last message.

cheatsheet_agents.pypython
from langchain.agents import create_agent
from langchain.tools import tool
from langgraph.checkpoint.memory import InMemorySaver

@tool
def check_stock(title: str) -> int:
    """Copies of a book in stock."""
    ...

agent = create_agent("google_genai:gemini-flash-lite-latest", tools=[check_stock],
                     system_prompt="You help Riverside Books.", middleware=[...],
                     checkpointer=InMemorySaver())
out = agent.invoke({"messages": [{"role": "user", "content": "Is Dune in?"}]},
                   config={"configurable": {"thread_id": "c1"}})
print(out["messages"][-1].text)

RAG cheat sheet

For RAG, split documents into chunks, embed them into a vector store, and make a retriever. Then the chain fills the prompt with retrieved context, and the question.

cheatsheet_rag.pypython
from langchain_core.vectorstores import InMemoryVectorStore
from langchain_google_genai import GoogleGenerativeAIEmbeddings
from langchain_text_splitters import RecursiveCharacterTextSplitter

chunks = RecursiveCharacterTextSplitter(chunk_size=300, chunk_overlap=40).split_documents(docs)
store = InMemoryVectorStore.from_documents(chunks, GoogleGenerativeAIEmbeddings(model="gemini-embedding-001"))
retriever = store.as_retriever(search_kwargs={"k": 3})

chain = ({"context": retriever | format_docs, "question": RunnablePassthrough()}
         | prompt | model | StrOutputParser())

Summary

Agents are a model, tools, rules, middleware, and memory. RAG is split, embed, store, retrieve, and answer. Next, the most common mistakes, and their fixes.

Key takeaways
  • @tool + create_agent
  • thread_id
  • Split, embed, retrieve
Next up: Common Mistakes — and fixes