LangChain Basics: Build Your First AI Agent
LangChain is the most-used framework for building LLM applications. This tutorial walks you through your first AI agent in 30 minutes.
What is LangChain?
LangChain is an open-source framework for building applications with large language models. It provides:
- Chains: Composable sequences of LLM calls
- Agents: LLMs that can use tools and make decisions
- Memory: State persistence across calls
- Retrieval: Connect LLMs to your own data
Install
pip install langchain langchain-openai
export OPENAI_API_KEY="sk-..."
Your first chain
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
llm = ChatOpenAI(model="gpt-4")
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant."),
("user", "{question}"),
])
chain = prompt | llm
response = chain.invoke({"question": "What is LangChain?"})
print(response.content)
Your first agent
from langchain.agents import create_react_agent
from langchain.tools import Tool
tools = [Tool(name="search", func=search.run, description="Web search")]
agent = create_react_agent(llm, tools)
agent.invoke({"input": "What's the weather in Beijing?"})
Key takeaways
- LangChain abstracts LLM calls into composable pieces
- Agents let LLMs choose tools dynamically
- Memory lets you build stateful applications