LangChain Academy Basic Introduction Detailed Interpretation
📚 Overview
This document explains in detail the basic entry module (Module 0 - Basics) of LangChain Academy. This is the first step to learn LangGraph, helping you understand the core components of the LangChain ecosystem, the use of Chat Models, and basic tool integration. With this tutorial, you'll master the basics of building AI applications.
🎯 Core Concept
What is LangChain?
LangChain is a development framework for building LLM (Large Language Model) applications. It provides:
- Modular components: Chat Models, Prompts, Tools, Memory, etc.
- Standardized Interface: Unified API, supports multiple LLM providers
- Chain combination: combine multiple components into complex workflows
What is LangGraph?
LangGraph is the graph orchestration framework in the LangChain ecosystem, specifically used to build Agent and multi-Agent applications. Its core advantages:
- Cycles Support (Cycles): Supports workflows with cycles, not just DAGs (Directed Acyclic Graphs)
- Precise control (Controllability): can accurately control the execution process of the Agent
- Persistence: Supports saving and restoring state
Why do you need LangGraph?
There are problems with the traditional Agent framework:
- ❌ Lack of control over execution process
- ❌ Difficulty handling complex decision-making logic
- ❌ Unable to reliably put into production environment
LangGraph’s solution:
- ✅ Model Agent workflow as State Chart
- ✅ Precisely control the execution path through nodes and edges
- ✅ Supports production-level features such as manual intervention and error recovery
🎓 Course Structure
LangChain Academy consists of multiple modules, each focusing on a specific topic:
langchain-academy/
├── module-0/ # 基础入门(本教程)
├── module-1/ # LangGraph 核心概念
├── module-2/ # Agent 架构
├── module-3/ # Multi-Agent 系统
├── module-4/ # 高级模式(Map-Reduce、Sub-graphs 等)
└── ...Each module contains:
- Notebooks: Interactive tutorials (Jupyter Notebook)
- Studio File: Graph definition that can be opened in LangGraph Studio
- Video tutorial: supporting explanation video
🔧 Detailed explanation of environment configuration
1. Install dependencies
pip install --quiet -U langchain_openai langchain_core langchain_community tavily-pythonDependency description:
| Package name | Purpose |
|---|---|
langchain_openai | OpenAI model integration (ChatGPT, GPT-4, etc.) |
langchain_core | LangChain core components (Messages, Runnables, etc.) |
langchain_community | Community tools (Tavily search, etc.) |
tavily-python | Tavily Search Engine SDK |
2. Configure API key
import os, getpass
def _set_env(var: str):
if not os.environ.get(var):
os.environ[var] = getpass.getpass(f"{var}: ")
_set_env("OPENAI_API_KEY")Python knowledge points: Environment variables and security
# 检查环境变量是否存在
os.environ.get(var) # 返回值或 None
# 安全地获取密钥(输入时不显示)
getpass.getpass(f"{var}: ") # 类似密码输入
# 设置环境变量
os.environ[var] = "your-api-key"**Why use environment variables? **
- 🔒 Security: Avoid hardcoding keys in code
- 🔄 Flexibility: different keys can be used in different environments
- ✅ BEST PRACTICE: Follow the 12-Factor App Principles
🤖 Chat Models detailed explanation
What is Chat Model?
Chat Model is a model that accepts a message list as input and returns a chat message as output. Unlike traditional text generation models, the Chat Model understands the context and roles of the conversation.
Core Features
输入:[HumanMessage, AIMessage, SystemMessage, ...]
↓
Chat Model (如 GPT-4)
↓
输出:AIMessageLangChain’s Chat Model Integration
LangChain does not host models but provides a unified interface that supports multiple providers:
| Providers | Model Examples | Integration Packages |
|---|---|---|
| OpenAI | GPT-4, GPT-3.5 | langchain_openai |
| Anthropic | Claude | langchain_anthropic |
| Gemini | langchain_google_genai | |
| Azure | Azure OpenAI | langchain_openai |
Benefits:
- Unified API to easily switch models
- Model-independent application design
- Supports 70+ model providers
💻 Chat Model practice
1. Initialize Chat Model
from langchain_openai import ChatOpenAI
# 初始化 GPT-4o
gpt4o_chat = ChatOpenAI(model="gpt-4o", temperature=0)
# 初始化 GPT-3.5(更便宜)
gpt35_chat = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0)Detailed explanation of key parameters:
model (model name)
# GPT-4 系列 - 高质量、较贵
"gpt-4o" # 最新优化版本
"gpt-4-turbo" # GPT-4 Turbo
# GPT-3.5 系列 - 便宜、快速
"gpt-3.5-turbo-0125" # GPT-3.5 最新版本**How to choose? **
- High quality output required → GPT-4
- Need to reduce costs → GPT-3.5
- Needs balance → GPT-4o (default for this course)
temperature (temperature parameter)
Control the randomness and creativity of your output:
temperature = 0 # 确定性输出(适合事实查询、代码生成)
temperature = 0.7 # 平衡(适合对话)
temperature = 1.0 # 最大创造性(适合创意写作)Example comparison:
# Temperature = 0 (每次输出几乎相同)
"巴黎是法国的首都。"
"巴黎是法国的首都。"
# Temperature = 1.0 (每次输出不同)
"巴黎,这座浪漫之都,是法国的首都。"
"法国的首都是美丽的巴黎。"2. Call Chat Model
Method 1: Using message object
from langchain_core.messages import HumanMessage
# 创建消息
msg = HumanMessage(content="Hello world", name="Lance")
# 调用模型
response = gpt4o_chat.invoke([msg])Output:
AIMessage(
content='Hello! How can I assist you today?',
response_metadata={
'token_usage': {'completion_tokens': 9, 'prompt_tokens': 11, 'total_tokens': 20},
'model_name': 'gpt-4o-2024-05-13',
'finish_reason': 'stop'
},
id='run-d3c4bc85-ef14-49f6-ba7e-91bf455cffee-0'
)LangChain knowledge point: message type
| Message type | Function | Example |
|---|---|---|
HumanMessage | User input | User questions, instructions |
AIMessage | AI reply | Model's answer |
SystemMessage | System command | Set AI role and behavior |
FunctionMessage | Function call result | Return value of Tool execution |
Message object structure:
HumanMessage(
content="Hello world", # 消息内容
name="Lance" # 可选:发送者名称
)Method 2: Use string (simplified writing)
response = gpt4o_chat.invoke("hello world")Internal Conversion:
"hello world" → HumanMessage(content="hello world")**When to use? **
- ✅ Simple one-round dialogue
- ❌ Multiple rounds of dialogue (need to keep history)
3. Switch model
# GPT-4o 回复
gpt4o_chat.invoke("hello world")
# → AIMessage(content='Hello! How can I assist you today?', ...)
# GPT-3.5 回复(使用相同接口!)
gpt35_chat.invoke("hello world")
# → AIMessage(content='Hello! How can I assist you today?', ...)Advantages:
- 🔄 Unified interface, no need to modify the code
- 💰 Flexible switching to optimize costs
- 🧪 A/B testing different models
🔍 Search tool integration: Tavily
What is Tavily?
Tavily is a search engine optimized for LLM that offers:
- 📊 Structured search results
- ⚡ Fast response (optimized for RAG)
- 💎 High-quality content (filter low-quality web pages)
Configure Tavily API
_set_env("TAVILY_API_KEY")Free quota:
- Free credits for new users
- Sufficient to complete this course
Search using Tavily
from langchain_community.tools.tavily_search import TavilySearchResults
# 初始化搜索工具
tavily_search = TavilySearchResults(max_results=3)
# 执行搜索
search_docs = tavily_search.invoke("What is LangGraph?")Example output:
[
{
'url': 'https://www.datacamp.com/tutorial/langgraph-tutorial',
'content': 'LangGraph is a library within the LangChain ecosystem designed to tackle these challenges head-on. LangGraph provides a framework for defining, coordinating, and executing multiple LLM agents (or chains) in a structured manner.'
},
{
'url': 'https://langchain-ai.github.io/langgraph/',
'content': 'Overview LangGraph is a library for building stateful, multi-actor applications with LLMs, used to create agent and multi-agent workflows. Compared to other LLM frameworks, it offers these core benefits: cycles, controllability, and persistence.'
},
{
'url': 'https://www.youtube.com/watch?v=nmDFSVRnr4Q',
'content': 'LangGraph is an extension of LangChain enabling Multi-Agent conversation and cyclic chains.'
}
]Return structure:
{
'url': str, # 来源 URL
'content': str # 提取的文本内容
}🎓 Summary of core knowledge points
LangChain Core Concept
1. Runnable interface
All LangChain components (Chat Models, Tools, Chains) implement the Runnable interface:
| Method | Function | Usage scenarios |
|---|---|---|
invoke(input) | Synchronous call | Single request |
stream(input) | Streaming output | Long text generation |
batch(inputs) | Batch calls | Process multiple inputs in parallel |
ainvoke(input) | Asynchronous call | High concurrency scenario |
Example:
# invoke - 等待完整响应
response = chat.invoke("Tell me a joke")
# stream - 逐 token 返回
for chunk in chat.stream("Tell me a joke"):
print(chunk.content, end="")2. Messages (message system)
LangChain uses message objects instead of plain text:
# ❌ 不推荐:纯文本
"What is the capital of France?"
# ✅ 推荐:消息对象
HumanMessage(content="What is the capital of France?")Advantages:
- 📋 Keep conversation history
- 🎭 Distinguish between different roles
- 🔧 Support multi-modal (text, pictures, audio)
3. Best practices for model initialization
# ✅ 在应用启动时初始化一次
chat = ChatOpenAI(model="gpt-4o", temperature=0)
# ❌ 不要在循环中重复初始化
for _ in range(10):
chat = ChatOpenAI(...) # 性能浪费Python core knowledge points
1. Environment variable management
import os
# 读取环境变量
api_key = os.environ.get("OPENAI_API_KEY")
# 设置环境变量
os.environ["OPENAI_API_KEY"] = "sk-..."
# 检查是否存在
if "OPENAI_API_KEY" in os.environ:
print("API key is set")Best Practices for Production Environments:
# 使用 .env 文件(需要 python-dotenv)
# .env
OPENAI_API_KEY=sk-xxx
TAVILY_API_KEY=tvly-xxx
# Python 代码
from dotenv import load_dotenv
load_dotenv() # 自动加载 .env 文件2. getpass module (secure input)
import getpass
# 不显示输入内容(类似密码输入)
password = getpass.getpass("Enter password: ")
# 用户输入时屏幕不显示
# 对比普通 input()
username = input("Enter username: ") # 输入内容可见3. List comprehension
# 搜索结果处理示例
urls = [doc['url'] for doc in search_docs]
# → ['https://...', 'https://...', ...]
# 等价于:
urls = []
for doc in search_docs:
urls.append(doc['url'])💡 Best Practices
1. API key security
✅ Correct approach
# 1. 使用环境变量
os.environ["OPENAI_API_KEY"] = "sk-..."
# 2. 使用 .env 文件
# .env
OPENAI_API_KEY=sk-xxx
# 3. 使用密钥管理服务(生产环境)
# - AWS Secrets Manager
# - HashiCorp Vault
# - Azure Key Vault❌ Wrong approach
# 不要硬编码在代码中
chat = ChatOpenAI(api_key="sk-xxxxxxxxxxxxxxxx") # ❌
# 不要提交到 Git
# config.py
API_KEY = "sk-xxxxxxxxxxxxxxxx" # ❌2. Model selection strategy
| Task type | Recommended model | Reason |
|---|---|---|
| Fact query | GPT-4o | High accuracy |
| Creative Writing | GPT-4 | Good Quality |
| Simple classification | GPT-3.5 | Low cost |
| Code generation | GPT-4o | High code quality |
| Batch processing | GPT-3.5 | Cost optimization |
3. Temperature Settings Guide
# 事实性任务 - 低 temperature
chat = ChatOpenAI(model="gpt-4o", temperature=0)
# 适合:数学、翻译、数据提取
# 创意任务 - 高 temperature
chat = ChatOpenAI(model="gpt-4o", temperature=0.8)
# 适合:故事创作、营销文案、头脑风暴
# 平衡任务 - 中等 temperature
chat = ChatOpenAI(model="gpt-4o", temperature=0.5)
# 适合:对话、摘要、问答4. Error handling
from langchain_openai import ChatOpenAI
try:
chat = ChatOpenAI(model="gpt-4o", temperature=0)
response = chat.invoke("Hello")
except Exception as e:
print(f"错误:{e}")
# 处理错误:重试、降级到其他模型等Common mistakes:
AuthenticationError: API key errorRateLimitError: Rate limit exceededAPIError: OpenAI service error
🚀 Advanced skills
1. Use SystemMessage to set roles
from langchain_core.messages import SystemMessage, HumanMessage
messages = [
SystemMessage(content="你是一位专业的 Python 教师,善于用简单的例子解释复杂概念。"),
HumanMessage(content="什么是装饰器?")
]
response = chat.invoke(messages)
print(response.content)Effect:
- AI will answer as a teacher
- Use instructional language and examples
2. Streaming output optimizes user experience
# 完整输出(用户等待较久)
response = chat.invoke("写一篇关于 AI 的文章")
print(response.content) # 等待 10 秒后一次性显示
# 流式输出(实时反馈)
for chunk in chat.stream("写一篇关于 AI 的文章"):
print(chunk.content, end="", flush=True) # 逐 token 显示3. Post-processing of search results
# 提取所有 URL
urls = [doc['url'] for doc in search_docs]
# 合并所有内容
combined_content = "\n\n".join([doc['content'] for doc in search_docs])
# 结合搜索结果生成回答
messages = [
SystemMessage(content=f"基于以下信息回答问题:\n{combined_content}"),
HumanMessage(content="什么是 LangGraph?")
]
response = chat.invoke(messages)📊 Cost optimization
Token usage statistics
response = chat.invoke("Hello world")
# 查看 token 使用情况
metadata = response.response_metadata['token_usage']
print(f"输入 tokens: {metadata['prompt_tokens']}")
print(f"输出 tokens: {metadata['completion_tokens']}")
print(f"总计 tokens: {metadata['total_tokens']}")Example output:
输入 tokens: 9
输出 tokens: 9
总计 tokens: 18Cost estimate
| Model | Input price ($/1M tokens) | Output price ($/1M tokens) |
|---|---|---|
| GPT-4o | $5.00 | $15.00 |
| GPT-3.5 | $0.50 | $1.50 |
Calculation example:
# GPT-4o 处理 1000 tokens 输入 + 1000 tokens 输出
cost = (1000/1000000 * 5) + (1000/1000000 * 15)
# = $0.005 + $0.015 = $0.02(2 分钱)🎯 Practical application cases
Case 1: Simple question and answer robot
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage, AIMessage
# 初始化模型
chat = ChatOpenAI(model="gpt-4o", temperature=0.7)
# 对话历史
history = []
def chat_bot(user_input):
# 添加用户消息
history.append(HumanMessage(content=user_input))
# 调用模型
response = chat.invoke(history)
# 添加 AI 回复到历史
history.append(response)
return response.content
# 使用
print(chat_bot("你好"))
print(chat_bot("我刚才说了什么?")) # 能记住上下文Case 2: Search Enhanced Q&A (Simple RAG)
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_openai import ChatOpenAI
chat = ChatOpenAI(model="gpt-4o", temperature=0)
search = TavilySearchResults(max_results=3)
def search_qa(question):
# 1. 搜索相关信息
search_results = search.invoke(question)
context = "\n\n".join([doc['content'] for doc in search_results])
# 2. 结合搜索结果生成答案
prompt = f"""基于以下信息回答问题:
信息:
{context}
问题:{question}
答案:"""
response = chat.invoke(prompt)
return response.content
# 使用
answer = search_qa("LangGraph 的主要优势是什么?")
print(answer)Case 3: Multi-model comparison
models = {
"GPT-4o": ChatOpenAI(model="gpt-4o", temperature=0),
"GPT-3.5": ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
}
question = "解释量子计算"
for name, model in models.items():
response = model.invoke(question)
print(f"\n{name} 的回答:")
print(response.content)
print(f"Token 使用:{response.response_metadata['token_usage']}")🔍 Frequently Asked Questions
Q1: Why use message objects instead of strings?
String mode:
chat.invoke("Hello") # 简单,但丢失上下文Message object mode:
messages = [
SystemMessage(content="你是助手"),
HumanMessage(content="Hello")
]
chat.invoke(messages) # 保留角色、历史Advantages:
- 🔄 Support multiple rounds of dialogue
- 🎭 Distinguish between system/user/AI roles
- 📊 Better debugging and logging
Q2: Is temperature=0 really sure?
**Not entirely sure! **
chat = ChatOpenAI(temperature=0)
# 相同输入,99% 情况输出相同
response1 = chat.invoke("1+1=?") # → "2"
response2 = chat.invoke("1+1=?") # → "2"
# 但模型更新或其他因素可能导致微小差异**When to use temperature=0? **
- ✅ Tasks that require consistency (testing, evaluation)
- ✅ Factual answers
- ❌ Not suitable for creative tasks
Q3: How to choose max_results?
# 搜索结果数量权衡
search = TavilySearchResults(max_results=N)| max_results | Advantages | Disadvantages |
|---|---|---|
| 1-3 | Fast, focused | Information may be missed |
| 5-10 | Comprehensive | High cost and noisy |
| 10+ | Most comprehensive | Exceeds LLM context limits |
Recommended:
- Easy questions: 3
- Complex Research: 5-10
- Comparative analysis: 3-5
📖 Further reading
- LangChain official document
- Detailed explanation of the concept of Chat Models
- OpenAI API Pricing
- Tavily Search API
- LangGraph official document
🎉 Next step
Congratulations on completing the LangChain Academy basic module! You've got it:
✅ Core concepts of LangChain and LangGraph ✅ Initialization and calling of Chat Models ✅ Usage of messaging system ✅ Integration of search tools ✅ API key security management
Learn next:
- Module 1: LangGraph core concepts (State, Graph, Node, Edge)
- Module 2: Build your first Agent
- Module 4: Advanced mode (Map-Reduce, Sub-graphs)
Practical Suggestions:
- 🔨 Modify the code and try different parameters
- 🧪 Test the effects of different models
- 📝 Record problems encountered and solutions
- 💬 Join the community discussion
Summary: This module is the starting point of your LangGraph learning journey. By mastering Chat Models and tool integration, you already have the basic capabilities to build AI applications. Remember: LangChain provides components and LangGraph provides orchestration. Only by combining the two can we build a powerful Agent system!