当前位置:首页>python>Python LangChain模块深度解析:AI应用开发框架,简化大模型应用开发

Python LangChain模块深度解析:AI应用开发框架,简化大模型应用开发

  • 2026-04-12 15:18:20
Python LangChain模块深度解析:AI应用开发框架,简化大模型应用开发
一、引言
当你准备将大语言模型集成到实际业务中时,是否遇到过这些挑战:
  • 大模型一本正经胡说八道:32%的开发者认为质量是头号难题,AI的幻觉问题让业务应用缺乏可靠性
  • 多步推理任务难以控制:传统开发方式无法让LLM自主规划、调用工具、管理状态,复杂业务流程自动化举步维艰
  • 上下文管理混乱:对话历史、文档知识、工具调用结果混杂在一起,上下文窗口爆炸导致性能崩溃
  • 生产部署困难重重:89%的企业需要可观测性,但缺乏标准化工具追踪智能体的思考过程和决策路径
  • 模型切换成本高昂:不同供应商的API差异巨大,迁移模型意味着重写大量底层代码
LangChain正是为破解这些难题而生!作为当前最流行的AI应用开发框架,它通过模块化设计将大模型与外部系统无缝连接,让开发者能够快速构建具备复杂逻辑、上下文感知和多步推理能力的AI应用。
通过本文,你将掌握:
  1. LangChain的核心概念与三层技术体系进化
  2. 5个完整可运行的代码示例,覆盖链式调用、智能代理、RAG全流程
  3. 智能客服、文档分析、代码生成三大实战应用场景
  4. 生产级部署的最佳实践与性能监控方案
  5. 2026年LangChain最新发展趋势与选型指南
二、模块概述
2.1 定位与设计哲学
LangChain是一款专为构建基于大语言模型的应用程序而设计的开源框架。如果说大语言模型是汽车的发动机,那么LangChain就是完整的底盘+传动系统+控制系统,让"发动机"能适配不同的"车身"(应用场景)。
核心设计哲学
  • 模块化:将模型交互、数据处理、工具连接等能力封装为独立组件
  • 可组合性:通过链式结构将多个组件组合成复杂工作流
  • 生产就绪:从原型到生产无需代码更改,支持流式输出、状态持久化
2.2 三层技术体系进化(2026年最新视角)
根据2026年技术趋势,LangChain已演化为三层递进的技术体系:
层级
代表框架
核心定位
解决的核心问题
Framework
LangChain
基础零件库
"怎么写代码" - 提供模型、工具、提示模板等基础组件
Runtime
LangGraph
执行引擎
"怎么让代码跑起来不挂" - 状态管理、持久化、人机协作
Harness
DeepAgents
约束框架
"怎么让Agent稳定跑完复杂任务" - 规划器、子Agent、上下文压缩
三层关系:DeepAgents → 必须依赖 LangGraph → 可选依赖 LangChain,层层叠加而非互相替代。
2.3 核心组件全景图
LangChain生态系统(2026年)
├── LangChain(基础框架)
│   ├── 模型抽象:统一接口支持100+模型供应商
│   ├── 提示工程:模板化管理与优化
│   ├── 工具集成:数百种外部服务连接
│   └── 记忆管理:多种策略解决LLM无状态性
├── LangGraph(运行时编排)
│   ├── 图结构建模:有向图表示智能体系统
│   ├── 多智能体协作:研究→分析→报告全流程
│   └── 可视化调试:直观呈现执行路径
├── DeepAgents(智能体外骨骼)
│   ├── 任务规划:分解长任务为子目标
│   ├── 虚拟文件系统:高效管理大输出
│   └── 子智能体委托:动态创建专项Agent
└── LangSmith(监控平台)
    ├── 追踪:记录每个步骤和工具调用
    ├── 评估:自动化质量检查
    └── 部署:生产环境管理
2.4 适用场景说明
LangChain特别适合以下应用场景:
  • 智能客服系统:基于知识库的精准问答,支持多轮对话
  • 文档分析与总结:自动处理PDF、Word、Excel等格式文档
  • 代码生成与审查:根据需求生成代码片段,自动检测Bug
  • 数据分析助手:将自然语言查询转换为SQL或数据处理脚本
  • 业务流程自动化:多步骤审批、调度、测试等复杂流程
三、核心概念详解
3.1 链(Chains):智能流程的"组装线"
链是LangChain的灵魂,它允许将多个组件组合成一个可执行的流程。通过链式结构,开发者可以轻松构建多步骤推理任务。
核心链类型
  • LLMChain:最基础的链,组合提示模板和LLM
  • RetrievalQAChain:RAG核心链,组合检索器和LLM
  • SequentialChain:串行链,按顺序执行多个链
示例1:基础LLMChain使用
# 安装依赖:pip install langchain langchain-openai
import os
from langchain_openai import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from langchain.chains import LLMChain

# 设置OpenAI API密钥(实际使用时请替换为您的密钥)
os.environ["OPENAI_API_KEY"] = "your-api-key-here"

# 1. 创建大语言模型实例
llm = ChatOpenAI(model="gpt-4o", temperature=0.7)

# 2. 定义提示模板
prompt_template = ChatPromptTemplate.from_messages([
    ("system""你是一个专业的Python技术专家"),
    ("user""请用简洁的语言解释{concept}的概念,并给出一个应用示例")
])

# 3. 创建链
chain = LLMChain(llm=llm, prompt=prompt_template)

# 4. 运行链
result = chain.invoke({"concept""Python装饰器"})
print(f"AI回复:{result['text']}")

# 输出示例:
# AI回复:Python装饰器是一种特殊函数,用于修改其他函数的行为...
示例2:SequentialChain实现多步推理
from langchain.chains import SequentialChain, LLMChain
from langchain.prompts import PromptTemplate

# 第一步:生成问题
problem_template = PromptTemplate(
    input_variables=["topic"],
    template="请生成一个关于{topic}的编程问题,难度适中"
)

# 第二步:生成解决方案
solution_template = PromptTemplate(
    input_variables=["problem"],
    template="针对以下编程问题,提供Python解决方案:{problem}"
)

# 第三步:代码优化建议
optimize_template = PromptTemplate(
    input_variables=["solution"],
    template="分析以下Python代码,提出3条优化建议:{solution}"
)

# 创建三个链
problem_chain = LLMChain(llm=llm, prompt=problem_template, output_key="problem")
solution_chain = LLMChain(llm=llm, prompt=solution_template, output_key="solution")
optimize_chain = LLMChain(llm=llm, prompt=optimize_template, output_key="optimizations")

# 组合成顺序链
multi_step_chain = SequentialChain(
    chains=[problem_chain, solution_chain, optimize_chain],
    input_variables=["topic"],
    output_variables=["problem""solution""optimizations"],
    verbose=True# 显示执行过程
)

# 运行多步推理
result = multi_step_chain.invoke({"topic""数据可视化"})
print(f"生成的问题:{result['problem']}")
print(f"解决方案:{result['solution']}")
print(f"优化建议:{result['optimizations']}")
3.2 代理(Agents):让LLM"自主行动"的决策中枢
代理是LangChain的高阶能力,它让大语言模型能够根据任务需求自主选择调用哪些工具,实现多步骤推理。
代理核心组件
  • Agent:决策核心,判断该调用哪个工具
  • Tool:工具接口,包括计算器、搜索引擎、代码执行器等
  • Executor:执行器,负责调用工具并返回结果
示例3:ReAct代理实现复杂任务规划
from langchain.agents import Tool, AgentExecutor, create_react_agent
from langchain.tools import DuckDuckGoSearchRun, PythonREPLTool
from langchain import hub

# 定义可用工具
search = DuckDuckGoSearchRun()
python_repl = PythonREPLTool()

tools = [
    Tool(
        name="Search",
        func=search.run,
        description="用于搜索最新信息,适用于事实性问题和最新动态"
    ),
    Tool(
        name="PythonREPL",
        func=python_repl.run,
        description="用于执行Python代码,适用于计算、数据处理和代码验证"
    )
]

# 从LangChain Hub获取ReAct提示模板
prompt = hub.pull("hwchase17/react")

# 创建代理
agent = create_react_agent(llm, tools, prompt)

# 创建执行器
agent_executor = AgentExecutor(
    agent=agent,
    tools=tools,
    verbose=True,
    handle_parsing_errors=True,
    max_iterations=5# 限制最大迭代次数,避免无限循环
)

# 运行代理处理复杂任务
task = "分析最近一周Python在AI领域的发展趋势,并生成一个简单的数据可视化代码"
result = agent_executor.invoke({"input": task})
print(f"最终结果:{result['output']}")
3.3 记忆(Memory):让对话拥有"历史感"
原生LLM没有记忆功能,Memory模块通过多种策略解决多轮对话的上下文管理问题。
记忆类型
  • ConversationBufferMemory:简单缓存所有对话历史
  • ConversationSummaryMemory:对对话历史进行总结,避免上下文过长
  • ConversationTokenBufferMemory:按Token数限制缓存对话历史
示例4:对话记忆管理
from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain

# 创建记忆实例
memory = ConversationBufferMemory(
    return_messages=True,  # 返回消息对象而非字符串
    memory_key="chat_history"# 记忆在上下文中的键名
)

# 创建对话链
conversation = ConversationChain(
    llm=llm,
    memory=memory,
    verbose=True
)

# 多轮对话演示
print("第一轮对话:")
response1 = conversation.invoke("介绍一下Python的异步编程")
print(f"AI:{response1['response']}")

print("\n第二轮对话(基于历史):")
response2 = conversation.invoke("刚才提到的asyncio有什么优缺点?")
print(f"AI:{response2['response']}")

print("\n第三轮对话(继续深入):")
response3 = conversation.invoke("如何避免异步编程中的常见陷阱?")
print(f"AI:{response3['response']}")

# 查看完整对话历史
print("\n完整对话历史:")
for i, msg in enumerate(memory.chat_history.messages):
    print(f"{i+1}{msg.type}{msg.content[:100]}...")
3.4 工具(Tools):连接外部世界的"接口"
工具是与外部系统交互的接口,LangChain内置了丰富的工具集,也支持自定义工具开发。
示例5:自定义工具与工具调用
from langchain.tools import BaseTool
from typing import Optional
import requests

# 自定义工具:天气查询
classWeatherTool(BaseTool):
    name = "weather_checker"
    description = "查询指定城市的当前天气情况"

def_run(self, city: str) -> str:
"""实际执行逻辑"""
try:
# 模拟API调用(实际使用时请替换为真实天气API)
# 这里使用模拟数据演示
            weather_data = {
"北京": {"temp""18°C""condition""晴朗""humidity""45%"},
"上海": {"temp""22°C""condition""多云""humidity""65%"},
"深圳": {"temp""26°C""condition""小雨""humidity""85%"}
            }

if city in weather_data:
                data = weather_data[city]
returnf"{city}当前天气:温度{data['temp']}{data['condition']},湿度{data['humidity']}"
else:
returnf"抱歉,未找到{city}的天气信息"

except Exception as e:
returnf"查询天气时出错:{str(e)}"

def_arun(self, city: str):
"""异步版本(可选)"""
raise NotImplementedError("此工具不支持异步")

# 使用自定义工具
weather_tool = WeatherTool()

# 创建包含自定义工具的代理
from langchain.agents import initialize_agent

custom_tools = [weather_tool] + tools  # 组合自定义工具和内置工具

custom_agent = initialize_agent(
    tools=custom_tools,
    llm=llm,
    agent="zero-shot-react-description",
    verbose=True
)

# 执行包含天气查询的任务
weather_task = "查询北京的天气,并根据天气建议是否适合户外运动"
result = custom_agent.invoke(weather_task)
print(f"任务结果:{result['output']}")
3.5 大模型集成:多供应商支持策略
LangChain支持100+模型供应商,实现了统一的接口设计,让开发者可以轻松切换不同模型。
集成策略对比:
模型提供商
集成方式
优势
适用场景
OpenAI
ChatOpenAI
性能稳定,功能丰富
通用对话、代码生成
Anthropic
ChatAnthropic
安全性高,长上下文
企业级应用、敏感数据处理
Google
ChatGoogleGenerativeAI
多模态支持好
图像理解、多模态任务
本地部署
Ollama
数据隐私性好
私有化部署、成本敏感场景
开源模型
HuggingFacePipeline
完全免费,可定制
研究实验、特定领域微调
示例6:多模型切换演示
# 多模型配置示例(需要相应API密钥)
from langchain_openai import ChatOpenAI
from langchain_anthropic import ChatAnthropic
from langchain_google_genai import ChatGoogleGenerativeAI

# 初始化不同模型(实际使用时需要相应API密钥)
models = {
"openai": ChatOpenAI(model="gpt-4o", temperature=0.7),
"anthropic": ChatAnthropic(model="claude-3-opus-20240229", temperature=0.5),
"google": ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.6)
}

# 统一接口调用不同模型
defask_model(model_name, question):
    model = models.get(model_name)
ifnot model:
return"模型未配置"

try:
        response = model.invoke(question)
return response.content
except Exception as e:
returnf"调用{model_name}失败:{str(e)}"

# 测试不同模型
test_question = "用Python实现快速排序算法,并解释其工作原理"

for model_name in ["openai""anthropic""google"]:
    print(f"\n{model_name.upper()}模型回答:")
    answer = ask_model(model_name, test_question)
    print(answer[:200] + "...")  # 只显示前200字符
四、提示模板与输出解析器
4.1 提示模板体系详解
LangChain的提示模板体系提供了灵活的方式管理和优化与大模型的交互。核心模板类型包括:
ChatPromptTemplate:支持多角色对话格式(system/user/assistant)
from langchain.prompts import ChatPromptTemplate

chat_template = ChatPromptTemplate.from_messages([
    ("system""你是一个专业的Python开发助手"),
    ("user""请解释{concept}的概念"),
    ("assistant""好的,我来解释{concept}..."),
    ("user""{question}")
])

formatted_prompt = chat_template.format_messages(
    concept="Python装饰器",
    question="装饰器在Web开发中有哪些应用?"
)
MessagesPlaceholder:动态插入对话历史
from langchain.prompts import MessagesPlaceholder

dynamic_template = ChatPromptTemplate.from_messages([
    MessagesPlaceholder(variable_name="history"),
    ("user""{input}")
])
PromptTemplate:传统的字符串模板
from langchain.prompts import PromptTemplate

simple_template = PromptTemplate(
    input_variables=["topic""difficulty"],
    template="生成一个关于{topic}的{difficulty}难度编程问题"
)
4.2 输出解析器实战
输出解析器确保LLM输出结构化、可预测的结果:
PydanticOutputParser:基于Pydantic模型解析
from langchain.output_parsers import PydanticOutputParser
from pydantic import BaseModel, Field
from typing import List

classCodeExample(BaseModel):
    language: str = Field(description="编程语言")
    code: str = Field(description="完整代码")
    explanation: str = Field(description="代码解释")
    complexity: str = Field(description="时间复杂度")

parser = PydanticOutputParser(pydantic_object=CodeExample)
JsonOutputParser:解析JSON格式输出
from langchain.output_parsers import JsonOutputParser

json_parser = JsonOutputParser()

# 使用时指定输出格式
from langchain.prompts import PromptTemplate

template = """请以JSON格式返回以下信息:
{format_instructions}

问题:{question}
"""


prompt = PromptTemplate(
    template=template,
    input_variables=["question"],
    partial_variables={"format_instructions": json_parser.get_format_instructions()}
)
StructuredOutputParser:结构化输出(兼容旧版本)
from langchain.output_parsers import StructuredOutputParser, ResponseSchema

response_schemas = [
    ResponseSchema(name="function_name", description="函数名称"),
    ResponseSchema(name="code", description="完整代码"),
    ResponseSchema(name="time_complexity", description="时间复杂度")
]

output_parser = StructuredOutputParser.from_response_schemas(response_schemas)
4.3 模板与解析器组合最佳实践
from langchain.chains import LLMChain
from langchain.prompts import ChatPromptTemplate, HumanMessagePromptTemplate
from langchain.output_parsers import PydanticOutputParser

# 1. 定义输出模型
classAlgorithmExplanation(BaseModel):
    name: str = Field(description="算法名称")
    python_code: str = Field(description="Python实现代码")
    explanation: str = Field(description="算法原理解释")
    use_cases: List[str] = Field(description="适用场景列表")

# 2. 创建解析器
parser = PydanticOutputParser(pydantic_object=AlgorithmExplanation)

# 3. 构建提示模板
prompt = ChatPromptTemplate.from_messages([
    ("system""你是一个算法专家,请按照指定格式回答。"),
    ("user""请解释{algorithm}算法:\n{format_instructions}")
])

# 4. 创建链
chain = LLMChain(
    llm=llm,
    prompt=prompt,
    output_parser=parser
)

# 5. 运行
result = chain.invoke({
"algorithm""快速排序",
"format_instructions": parser.get_format_instructions()
})

print(f"算法名称:{result['text'].name}")
print(f"代码:\n{result['text'].python_code}")
五、文档加载与向量存储
5.1 文档加载器生态系统
LangChain支持多种文档格式的加载:
PDF文档:PyPDFLoader
from langchain.document_loaders import PyPDFLoader

loader = PyPDFLoader("example.pdf")
documents = loader.load()
print(f"加载了{len(documents)}页PDF文档")
Word文档:Docx2txtLoader
from langchain.document_loaders import Docx2txtLoader

loader = Docx2txtLoader("report.docx")
documents = loader.load()
网页内容:WebBaseLoader
from langchain.document_loaders import WebBaseLoader

loader = WebBaseLoader(["https://example.com"])
documents = loader.load()
Markdown文件:UnstructuredMarkdownLoader
from langchain.document_loaders import UnstructuredMarkdownLoader

loader = UnstructuredMarkdownLoader("README.md")
documents = loader.load()
5.2 文本分割策略
合理的文本分割是RAG系统成功的关键:
递归字符分割:RecursiveCharacterTextSplitter
from langchain.text_splitter import RecursiveCharacterTextSplitter

text_splitter = RecursiveCharacterTextSplitter(
    chunk_size=500,
    chunk_overlap=50,
    separators=["\n\n""\n""。"","" """]
)

chunks = text_splitter.split_documents(documents)
print(f"原始文档分割为{len(chunks)}个文本块")
Token限制分割:TokenTextSplitter
from langchain.text_splitter import TokenTextSplitter

token_splitter = TokenTextSplitter(
    chunk_size=1000,
    chunk_overlap=100
)

token_chunks = token_splitter.split_documents(documents)
5.3 向量存储与检索
FAISS向量数据库:Facebook开源的向量搜索库
from langchain.embeddings import OpenAIEmbeddings
from langchain.vectorstores import FAISS

# 创建嵌入
embeddings = OpenAIEmbeddings()

# 创建向量存储
vectorstore = FAISS.from_documents(chunks, embeddings)

# 相似性检索
query = "Python异步编程的优势"
docs = vectorstore.similarity_search(query, k=3)

for i, doc in enumerate(docs):
    print(f"结果{i+1}{doc.page_content[:100]}...")
Chroma向量数据库:轻量级、易用的向量存储
from langchain.vectorstores import Chroma

chroma_store = Chroma.from_documents(
    documents=chunks,
    embedding=embeddings,
    persist_directory="./chroma_db"
)

# 持久化存储
chroma_store.persist()

# 加载已有存储
loaded_store = Chroma(
    persist_directory="./chroma_db",
    embedding_function=embeddings
)
5.4 检索增强生成(RAG)全流程示例
from langchain.chains import RetrievalQA
from langchain.memory import ConversationBufferMemory

classRAGSystem:
"""完整的RAG系统实现"""

def__init__(self, document_paths, embedding_model="text-embedding-ada-002"):
        self.embeddings = OpenAIEmbeddings(model=embedding_model)
        self.documents = self.load_documents(document_paths)
        self.vectorstore = self.create_vectorstore()
        self.memory = ConversationBufferMemory(
            return_messages=True,
            memory_key="chat_history"
        )

# 创建RAG链
        self.qa_chain = RetrievalQA.from_chain_type(
            llm=ChatOpenAI(model="gpt-4o", temperature=0.3),
            chain_type="stuff",
            retriever=self.vectorstore.as_retriever(search_kwargs={"k"4}),
            memory=self.memory,
            return_source_documents=True
        )

defload_documents(self, paths):
"""加载多种格式文档"""
from langchain.document_loaders import (
            PyPDFLoader, Docx2txtLoader, 
            TextLoader, CSVLoader
        )

        all_docs = []
for path in paths:
if path.endswith('.pdf'):
                loader = PyPDFLoader(path)
elif path.endswith('.docx'):
                loader = Docx2txtLoader(path)
elif path.endswith('.txt'):
                loader = TextLoader(path)
elif path.endswith('.csv'):
                loader = CSVLoader(path)
else:
continue

            docs = loader.load()
            all_docs.extend(docs)

return all_docs

defcreate_vectorstore(self):
"""创建向量存储"""
# 分割文本
from langchain.text_splitter import RecursiveCharacterTextSplitter

        text_splitter = RecursiveCharacterTextSplitter(
            chunk_size=500,
            chunk_overlap=50
        )

        chunks = text_splitter.split_documents(self.documents)

# 创建向量存储
        vectorstore = FAISS.from_documents(chunks, self.embeddings)
return vectorstore

defquery(self, question):
"""查询知识库"""
        result = self.qa_chain.invoke({"query": question})

return {
"answer": result["result"],
"sources": [
f"{doc.metadata.get('source''未知')} (第{doc.metadata.get('page''N/A')}页)"
for doc in result["source_documents"]
            ]
        }

# 使用示例
rag_system = RAGSystem([
"docs/project_guide.pdf",
"docs/api_reference.docx",
"docs/faq.txt"
])

response = rag_system.query("项目部署有哪些注意事项?")
print(f"回答:{response['answer']}")
print(f"来源:{response['sources']}")
## 六、高级用法与性能优化

### 4.1 流式输出与实时交互

LangChain支持流式输出,显著提升用户体验,减少等待时间。

#### 示例7:流式输出实现

```python
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler

# 创建支持流式输出的模型
streaming_llm = ChatOpenAI(
    model="gpt-4o",
    temperature=0.7,
    streaming=True,
    callbacks=[StreamingStdOutCallbackHandler()]
)

# 创建对话链(流式版本)
streaming_conversation = ConversationChain(
    llm=streaming_llm,
    memory=ConversationBufferMemory(),
    verbose=False
)

print("开始流式对话(输入'退出'结束):")
whileTrue:
    user_input = input("\n你:")
if user_input.lower() == '退出':
break

    print("AI:", end="")
    response = streaming_conversation.invoke(user_input)
    print()  # 换行
4.2 上下文压缩与Token优化
当对话历史过长时,智能压缩技术可以保留核心信息,减少Token消耗。
示例8:ConversationSummaryMemory应用
from langchain.memory import ConversationSummaryMemory
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate

# 创建总结记忆
summary_memory = ConversationSummaryMemory(
    llm=llm,
    memory_key="chat_history",
    return_messages=True
)

# 定义提示模板
summary_prompt = PromptTemplate(
    input_variables=["chat_history""input"],
    template="基于以下对话历史:{chat_history}\n回答用户问题:{input}"
)

# 创建链
summary_chain = LLMChain(
    llm=llm,
    prompt=summary_prompt,
    memory=summary_memory,
    verbose=True
)

# 模拟长对话
long_conversation = [
"Python有哪些主要的数据类型?",
"列表和元组有什么区别?",
"字典的键有什么要求?",
"集合在什么场景下使用?",
"这些数据类型的内存占用如何?"
]

for i, question in enumerate(long_conversation):
    print(f"\n第{i+1}轮提问:{question}")
    response = summary_chain.invoke({"input": question})
    print(f"回答:{response['text'][:100]}...")

# 查看压缩后的记忆
print("\n压缩后的记忆摘要:")
print(summary_memory.buffer[:500])
4.3 错误处理与重试机制
生产环境中,稳定的错误处理至关重要。
示例9:增强的链式调用错误处理
from langchain.callbacks import CallbackManager
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
from tenacity import retry, stop_after_attempt, wait_exponential

# 使用tenacity实现重试机制
@retry(
    stop=stop_after_attempt(3),  # 最多重试3次
    wait=wait_exponential(multiplier=1, min=4, max=10)  # 指数退避
)
defrobust_chain_invoke(chain, input_data):
"""增强的链调用,包含重试机制"""
try:
return chain.invoke(input_data)
except Exception as e:
        print(f"调用失败:{str(e)},正在重试...")
raise# 触发重试

# 创建带重试的链
callback_manager = CallbackManager([StreamingStdOutCallbackHandler()])

robust_llm = ChatOpenAI(
    model="gpt-4o",
    temperature=0.7,
    callback_manager=callback_manager
)

# 实际使用
try:
    result = robust_chain_invoke(
        LLMChain(llm=robust_llm, prompt=prompt_template),
        {"concept""机器学习"}
    )
    print(f"最终结果:{result['text']}")
except Exception as e:
    print(f"所有重试均失败:{str(e)}")
七、实战应用场景(≥3个完整实现)
5.1 场景一:智能客服系统(知识库问答)
构建基于企业知识库的智能客服,实现7×24小时精准问答。
# 完整实现:智能客服系统
from langchain.vectorstores import FAISS
from langchain.embeddings import OpenAIEmbeddings
from langchain.chains import RetrievalQA
from langchain.text_splitter import RecursiveCharacterTextSplitter

classSmartCustomerService:
"""智能客服系统"""

def__init__(self, documents, api_key):
        self.api_key = api_key
        os.environ["OPENAI_API_KEY"] = api_key

# 1. 文本分割
        text_splitter = RecursiveCharacterTextSplitter(
            chunk_size=500,
            chunk_overlap=50
        )
        texts = text_splitter.split_documents(documents)

# 2. 创建向量数据库
        embeddings = OpenAIEmbeddings()
        self.vectorstore = FAISS.from_documents(texts, embeddings)

# 3. 创建检索链
        self.qa_chain = RetrievalQA.from_chain_type(
            llm=ChatOpenAI(model="gpt-4o", temperature=0.3),
            chain_type="stuff",
            retriever=self.vectorstore.as_retriever(search_kwargs={"k"3}),
            return_source_documents=True
        )

defask(self, question):
"""回答用户问题"""
        result = self.qa_chain.invoke({"query": question})

return {
"answer": result["result"],
"sources": [doc.metadata.get("source""未知"
for doc in result["source_documents"]]
        }

# 模拟企业知识库文档
from langchain.docstore.document import Document

documents = [
    Document(
        page_content="公司产品A支持自动数据分析和可视化,适用于中小型企业。",
        metadata={"source""产品手册""page"1}
    ),
    Document(
        page_content="技术支持服务时间为工作日9:00-18:00,紧急问题可拨打400-xxx-xxxx。",
        metadata={"source""服务协议""page"3}
    ),
    Document(
        page_content="数据导出支持CSV、Excel和JSON格式,单次最多导出10万条记录。",
        metadata={"source""用户指南""page"5}
    )
]

# 创建客服实例
customer_service = SmartCustomerService(
    documents=documents,
    api_key="your-api-key"# 实际使用时替换
)

# 测试客服系统
questions = [
"公司有哪些产品?",
"技术支持时间是什么时候?",
"可以导出哪些格式的数据?"
]

for q in questions:
    print(f"\n用户问:{q}")
    response = customer_service.ask(q)
    print(f"客服答:{response['answer']}")
    print(f"来源:{response['sources']}")
5.2 场景二:文档分析与摘要助手
自动处理各种格式文档,提取关键信息并生成摘要。
# 完整实现:文档分析助手
import PyPDF2
import docx
from langchain.chains.summarize import load_summarize_chain
from langchain.text_splitter import CharacterTextSplitter

classDocumentAnalyzer:
"""文档分析助手"""

def__init__(self, llm):
        self.llm = llm

defread_pdf(self, file_path):
"""读取PDF文件"""
with open(file_path, 'rb'as file:
            pdf_reader = PyPDF2.PdfReader(file)
            text = ""
for page in pdf_reader.pages:
                text += page.extract_text()
return text

defread_docx(self, file_path):
"""读取Word文档"""
        doc = docx.Document(file_path)
return"\n".join([para.text for para in doc.paragraphs])

defsummarize(self, text, summary_type="brief"):
"""生成摘要"""
# 分割文本
        text_splitter = CharacterTextSplitter(
            separator="\n",
            chunk_size=1000,
            chunk_overlap=200
        )
        texts = text_splitter.split_text(text)
        docs = [Document(page_content=t) for t in texts]

# 选择摘要类型
if summary_type == "brief":
            chain_type = "map_reduce"
elif summary_type == "detailed":
            chain_type = "refine"
else:
            chain_type = "stuff"

# 加载摘要链
        chain = load_summarize_chain(
            self.llm,
            chain_type=chain_type,
            verbose=False
        )

return chain.invoke(docs)["output_text"]

defextract_key_points(self, text, num_points=5):
"""提取关键点"""
        prompt = f"""请从以下文本中提取{num_points}个关键点:

{text[:2000]}...

        以列表形式返回关键点,每个关键点用简短的一句话描述。"""


        response = self.llm.invoke(prompt)
return response.content

# 使用示例
analyzer = DocumentAnalyzer(llm)

# 模拟文档内容(实际使用时从文件读取)
sample_text = """Python是一种高级编程语言,由Guido van Rossum于1991年创建。
它具有简单易学的语法,强调代码的可读性。
Python支持多种编程范式,包括面向对象、命令式、函数式和过程式编程。
它拥有丰富的标准库和第三方库,广泛应用于Web开发、数据分析、人工智能等领域。
Python的解释器可以在多种操作系统上运行,包括Windows、Linux和macOS。"""


# 生成摘要
summary = analyzer.summarize(sample_text, "brief")
print(f"文档摘要:\n{summary}")

# 提取关键点
key_points = analyzer.extract_key_points(sample_text, 3)
print(f"\n关键点:\n{key_points}")
5.3 场景三:代码生成与审查工具
根据需求生成代码,并自动检测潜在问题和优化建议。
# 完整实现:代码生成与审查工具
import ast
import subprocess
from typing import List, Dict

classCodeAssistant:
"""代码生成与审查助手"""

def__init__(self, llm):
        self.llm = llm

defgenerate_code(self, requirement, language="python"):
"""根据需求生成代码"""
        prompt = f"""根据以下需求,生成{language}代码:

        需求:{requirement}

        要求:
        1. 代码完整可运行
        2. 包含必要的注释
        3. 考虑异常处理
        4. 遵循最佳实践

        只返回代码,不要有其他说明。"""


        response = self.llm.invoke(prompt)
return response.content

defreview_code(self, code):
"""代码审查"""
        prompt = f"""审查以下Python代码,提供:

        <!-- list-split -->

        1. 潜在Bug(3个)
        2. 性能优化建议(3条)
        3. 代码风格改进(3条)

        代码:
{code}

        以结构化方式返回结果。"""


        response = self.llm.invoke(prompt)
return response.content

defexplain_code(self, code):
"""代码解释"""
        prompt = f"""用通俗易懂的语言解释以下代码的功能和工作原理:

{code}

        解释内容包括:

        <!-- list-split -->

        1. 代码的整体功能
        2. 关键函数的作用
        3. 主要逻辑流程
        4. 可能的输入输出示例"""


        response = self.llm.invoke(prompt)
return response.content

defdebug_code(self, code, error_message):
"""调试代码"""
        prompt = f"""帮助调试以下代码:

        代码:
{code}

        错误信息:
{error_message}

        请:

        <!-- list-split -->

        1. 分析错误原因
        2. 提供修复方案
        3. 给出修复后的完整代码"""


        response = self.llm.invoke(prompt)
return response.content

# 使用示例
assistant = CodeAssistant(llm)

# 生成代码
requirement = "实现一个函数,计算斐波那契数列的第n项,要求使用缓存优化性能"
generated_code = assistant.generate_code(requirement)
print(f"生成的代码:\n{generated_code}")

# 审查代码
review = assistant.review_code(generated_code)
print(f"\n代码审查结果:\n{review}")

# 解释代码
explanation = assistant.explain_code(generated_code)
print(f"\n代码解释:\n{explanation[:500]}...")
八、常见问题与解决方案
8.1 问题一:LangChain响应速度慢,延迟高
问题表现
  • 多步骤任务执行时间长,用户等待不耐
  • 流式输出首次令牌时间(TTFT)过长
  • 复杂链式调用累积延迟明显
解决方案
  1. 启用流式输出:减少用户感知等待时间
llm = ChatOpenAI(model="gpt-4o", streaming=True, temperature=0.7)
  1. 优化Token使用:使用ConversationSummaryMemory压缩历史
memory = ConversationSummaryMemory(llm=llm, memory_key="chat_history")
  1. 并行处理:对于独立任务使用异步调用
import asyncio

asyncdefparallel_invoke(chains, inputs):
    tasks = [chain.ainvoke(input) for chain in chains]
returnawait asyncio.gather(*tasks)
  1. 缓存优化:启用提示缓存减少重复计算
from langchain.cache import InMemoryCache
from langchain.globals import set_llm_cache

set_llm_cache(InMemoryCache())
8.2 问题二:大模型"幻觉"现象严重
问题表现
  • AI生成看似合理但实际错误的信息
  • 缺乏事实依据,编造不存在的内容
  • 关键数据不准确,影响业务决策
解决方案
  1. 检索增强生成(RAG):基于知识库提供准确信息
qa_chain = RetrievalQA.from_chain_type(
    llm=llm,
    retriever=vectorstore.as_retriever(),
    return_source_documents=True
)
  1. 输出约束:使用Pydantic模型约束输出格式
from langchain.output_parsers import PydanticOutputParser
from pydantic import BaseModel, Field

classCodeResponse(BaseModel):
    function_name: str = Field(description="函数名称")
    code: str = Field(description="完整代码")
    explanation: str = Field(description="代码说明")

parser = PydanticOutputParser(pydantic_object=CodeResponse)
  1. 事实校验:多模型交叉验证关键信息
deffact_check(answer, reference_sources):
"""使用参考源校验答案准确性"""
    prompt = f"""验证以下答案是否与参考源一致:

    答案:{answer}
    参考源:{reference_sources}

    返回:'一致'或'不一致'及具体差异"""


return llm.invoke(prompt).content
8.3 问题三:生产部署复杂,监控困难
问题表现
  • 难以追踪智能体的决策过程
  • 错误调试困难,缺乏日志和指标
  • 多环境部署一致性差
解决方案
  1. 使用LangSmith:官方监控平台提供完整可观测性
# 配置LangSmith(需要API密钥)
os.environ["LANGCHAIN_TRACING_V2"] = "true"
os.environ["LANGCHAIN_ENDPOINT"] = "https://api.smith.langchain.com"
os.environ["LANGCHAIN_API_KEY"] = "your-langsmith-api-key"
  1. 结构化日志:统一日志格式便于分析和报警
import logging

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

# 在链中记录关键信息
chain = LLMChain(llm=llm, prompt=prompt, verbose=True)
  1. 版本管理:使用LangChain Hub管理提示模板版本
from langchain import hub

# 拉取最新提示模板
prompt = hub.pull("hwchase17/react")

# 推送更新
# hub.push("your-username/your-prompt", updated_prompt)
8.4 问题四:上下文窗口溢出,性能下降
问题表现
  • 长对话历史导致Token数超过模型限制
  • 响应时间随上下文增长而显著增加
  • 核心信息被稀释,回答质量下降
解决方案
  1. 动态记忆管理:根据重要性选择记忆策略
from langchain.memory import ConversationTokenBufferMemory

memory = ConversationTokenBufferMemory(
    llm=llm,
    max_token_limit=4000,  # 根据模型调整
    return_messages=True
)
  1. 分层压缩:重要细节保留,次要信息摘要化
defhierarchical_compression(messages, llm):
"""分层压缩对话历史"""
# 第一层:提取关键实体
# 第二层:总结次要对话
# 第三层:保留最近详细对话
pass
  1. 选择性加载:根据当前问题加载相关历史
defselective_memory_loading(query, full_history):
"""根据查询选择加载相关历史"""
# 使用嵌入相似度筛选相关对话
pass
8.5 问题五:模型切换成本高,供应商锁定
问题表现
  • 不同供应商API接口差异大
  • 迁移模型需要重写大量代码
  • 功能特性不一致,适配困难
解决方案
  1. 统一接口抽象:使用LangChain的标准化接口
# 无论底层模型如何,接口一致
llm = ChatOpenAI()  # OpenAI
llm = ChatAnthropic()  # Anthropic
llm = ChatGoogleGenerativeAI()  # Google
  1. 配置文件驱动:模型配置外部化,便于切换
# config.yaml
# model:
#   provider: "openai"
#   name: "gpt-4o"
#   temperature: 0.7

import yaml

with open("config.yaml""r"as f:
    config = yaml.safe_load(f)

defcreate_model(config):
    provider = config["model"]["provider"]
if provider == "openai":
return ChatOpenAI(**config["model"])
elif provider == "anthropic":
return ChatAnthropic(**config["model"])
# ... 其他供应商
  1. 功能降级兼容:确保核心功能在多个模型上可用
deffallback_invoke(primary_chain, fallback_chain, input_data):
"""主模型失败时自动切换备用模型"""
try:
return primary_chain.invoke(input_data)
except Exception:
        print("主模型失败,切换备用模型")
return fallback_chain.invoke(input_data)
九、总结与扩展学习
9.1 核心要点回顾
  1. 三层技术体系:从Framework到Runtime再到Harness,LangChain已演化为完整的AI工程化平台
  2. 五大核心概念:链、代理、记忆、工具、检索器构成LangChain的基础能力框架
  3. 统一模型接口:支持100+模型供应商,实现"一次编写,多处运行"
  4. 生产级特性:流式输出、状态持久化、可观测性等特性确保应用稳定性
  5. 丰富生态组件:LangGraph、DeepAgents、LangSmith等组件覆盖开发到部署全流程
9.2 2026年技术趋势与选型建议
根据2026年最新调研数据:
  • 企业采用率:57%的企业已投产智能体,大公司采用率高达67%
  • 主要挑战:质量(32%)和延迟(20%)是最大障碍
  • 技术栈:89%组织部署可观测性,超75%采用多模型策略
  • 主流场景:编码智能体(38%)、深度研究(22%)、定制化Agent(18%)
选型指南
  • 简单RAG/单次调用:直接使用模型API,避免框架开销
  • 多步推理/状态管理:LangGraph是最佳选择,提供运行时能力
  • 企业级生产部署:考虑AgentScope或Semantic Kernel,关注安全与生态集成
  • 长时程复杂任务:DeepAgents或Claude Agent SDK提供必要的约束控制
  • 快速原型开发:Dify/Coze等低代码平台加速验证过程
9.3 延伸学习路径
官方资源
  • LangChain官方文档:最新API参考和教程
  • LangChain Hub:社区分享的提示模板和工具
  • LangSmith:生产监控和调试平台
开源项目
  • LangChain中文社区:中文文档和示例
  • awesome-langchain:精选资源和工具集合
  • LangChain实战案例:官方示例代码库
进阶书籍
  • 《LangChain实战:从入门到精通》:系统学习LangChain核心概念
  • 《AI工程化:智能体系统设计与实现》:深入理解AI应用架构
  • 《大模型应用开发最佳实践》:掌握生产级部署技巧
社区与活动
  • Interrupt 2026大会:LangChain年度开发者大会
  • LangChain中文社区Meetup:定期技术分享和交流
  • AI工程化论坛:行业最佳实践讨论
9.4 下一篇预告
下周我们将深入解析Python Scikit-learn模块,作为机器学习领域的"瑞士军刀",Scikit-learn为数据科学家提供了从数据预处理到模型部署的全流程工具。我们将重点讲解:
  1. 统一API设计哲学:如何通过fit/predict/transform接口实现算法统一
  2. 特征工程全流程:从缺失值处理到特征选择的完整解决方案
  3. 模型选择与评估:交叉验证、网格搜索、模型评估的实战技巧
  4. 集成学习进阶:Bagging、Boosting、Stacking的深度解析
  5. 生产部署优化:模型持久化、API服务化、性能监控方案
如果你对机器学习有浓厚兴趣,或者正在寻找提高模型效果的方法,请持续关注"Python与AI智能研习社",我们将在下周为你带来更多实用干货!

版权声明:本文为"Python与AI智能研习社"原创内容,转载请注明出处。
互动环节:你在使用LangChain过程中遇到过哪些挑战?欢迎在评论区留言分享,我们将挑选优质问题在后续文章中详细解答!

最新文章

随机文章

基本 文件 流程 错误 SQL 调试
  1. 请求信息 : 2026-04-15 21:02:01 HTTP/2.0 GET : https://f.mffb.com.cn/a/486029.html
  2. 运行时间 : 0.098912s [ 吞吐率:10.11req/s ] 内存消耗:5,867.87kb 文件加载:140
  3. 缓存信息 : 0 reads,0 writes
  4. 会话信息 : SESSION_ID=a9a7d9633a94501f5033cefb08aad172
  1. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/public/index.php ( 0.79 KB )
  2. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/autoload.php ( 0.17 KB )
  3. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/autoload_real.php ( 2.49 KB )
  4. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/platform_check.php ( 0.90 KB )
  5. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/ClassLoader.php ( 14.03 KB )
  6. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/autoload_static.php ( 4.90 KB )
  7. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/helper.php ( 8.34 KB )
  8. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-validate/src/helper.php ( 2.19 KB )
  9. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/helper.php ( 1.47 KB )
  10. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/stubs/load_stubs.php ( 0.16 KB )
  11. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Exception.php ( 1.69 KB )
  12. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-container/src/Facade.php ( 2.71 KB )
  13. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/deprecation-contracts/function.php ( 0.99 KB )
  14. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/polyfill-mbstring/bootstrap.php ( 8.26 KB )
  15. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/polyfill-mbstring/bootstrap80.php ( 9.78 KB )
  16. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/var-dumper/Resources/functions/dump.php ( 1.49 KB )
  17. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-dumper/src/helper.php ( 0.18 KB )
  18. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/var-dumper/VarDumper.php ( 4.30 KB )
  19. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/App.php ( 15.30 KB )
  20. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-container/src/Container.php ( 15.76 KB )
  21. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/container/src/ContainerInterface.php ( 1.02 KB )
  22. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/provider.php ( 0.19 KB )
  23. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Http.php ( 6.04 KB )
  24. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/helper/Str.php ( 7.29 KB )
  25. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Env.php ( 4.68 KB )
  26. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/common.php ( 0.03 KB )
  27. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/helper.php ( 18.78 KB )
  28. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Config.php ( 5.54 KB )
  29. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/app.php ( 0.95 KB )
  30. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/cache.php ( 0.78 KB )
  31. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/console.php ( 0.23 KB )
  32. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/cookie.php ( 0.56 KB )
  33. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/database.php ( 2.48 KB )
  34. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/facade/Env.php ( 1.67 KB )
  35. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/filesystem.php ( 0.61 KB )
  36. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/lang.php ( 0.91 KB )
  37. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/log.php ( 1.35 KB )
  38. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/middleware.php ( 0.19 KB )
  39. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/route.php ( 1.89 KB )
  40. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/session.php ( 0.57 KB )
  41. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/trace.php ( 0.34 KB )
  42. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/view.php ( 0.82 KB )
  43. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/event.php ( 0.25 KB )
  44. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Event.php ( 7.67 KB )
  45. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/service.php ( 0.13 KB )
  46. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/AppService.php ( 0.26 KB )
  47. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Service.php ( 1.64 KB )
  48. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Lang.php ( 7.35 KB )
  49. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/lang/zh-cn.php ( 13.70 KB )
  50. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/initializer/Error.php ( 3.31 KB )
  51. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/initializer/RegisterService.php ( 1.33 KB )
  52. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/services.php ( 0.14 KB )
  53. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/service/PaginatorService.php ( 1.52 KB )
  54. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/service/ValidateService.php ( 0.99 KB )
  55. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/service/ModelService.php ( 2.04 KB )
  56. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-trace/src/Service.php ( 0.77 KB )
  57. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Middleware.php ( 6.72 KB )
  58. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/initializer/BootService.php ( 0.77 KB )
  59. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/Paginator.php ( 11.86 KB )
  60. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-validate/src/Validate.php ( 63.20 KB )
  61. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/Model.php ( 23.55 KB )
  62. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/Attribute.php ( 21.05 KB )
  63. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/AutoWriteData.php ( 4.21 KB )
  64. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/Conversion.php ( 6.44 KB )
  65. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/DbConnect.php ( 5.16 KB )
  66. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/ModelEvent.php ( 2.33 KB )
  67. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/RelationShip.php ( 28.29 KB )
  68. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/contract/Arrayable.php ( 0.09 KB )
  69. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/contract/Jsonable.php ( 0.13 KB )
  70. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/contract/Modelable.php ( 0.09 KB )
  71. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Db.php ( 2.88 KB )
  72. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/DbManager.php ( 8.52 KB )
  73. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Log.php ( 6.28 KB )
  74. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Manager.php ( 3.92 KB )
  75. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/log/src/LoggerTrait.php ( 2.69 KB )
  76. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/log/src/LoggerInterface.php ( 2.71 KB )
  77. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Cache.php ( 4.92 KB )
  78. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/simple-cache/src/CacheInterface.php ( 4.71 KB )
  79. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/helper/Arr.php ( 16.63 KB )
  80. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/cache/driver/File.php ( 7.84 KB )
  81. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/cache/Driver.php ( 9.03 KB )
  82. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/CacheHandlerInterface.php ( 1.99 KB )
  83. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/Request.php ( 0.09 KB )
  84. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Request.php ( 55.78 KB )
  85. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/middleware.php ( 0.25 KB )
  86. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Pipeline.php ( 2.61 KB )
  87. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-trace/src/TraceDebug.php ( 3.40 KB )
  88. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/middleware/SessionInit.php ( 1.94 KB )
  89. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Session.php ( 1.80 KB )
  90. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/session/driver/File.php ( 6.27 KB )
  91. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/SessionHandlerInterface.php ( 0.87 KB )
  92. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/session/Store.php ( 7.12 KB )
  93. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Route.php ( 23.73 KB )
  94. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/RuleName.php ( 5.75 KB )
  95. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/Domain.php ( 2.53 KB )
  96. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/RuleGroup.php ( 22.43 KB )
  97. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/Rule.php ( 26.95 KB )
  98. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/RuleItem.php ( 9.78 KB )
  99. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/route/app.php ( 1.72 KB )
  100. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/facade/Route.php ( 4.70 KB )
  101. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/dispatch/Controller.php ( 4.74 KB )
  102. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/Dispatch.php ( 10.44 KB )
  103. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/controller/Index.php ( 4.81 KB )
  104. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/BaseController.php ( 2.05 KB )
  105. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/facade/Db.php ( 0.93 KB )
  106. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/connector/Mysql.php ( 5.44 KB )
  107. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/PDOConnection.php ( 52.47 KB )
  108. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/Connection.php ( 8.39 KB )
  109. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/ConnectionInterface.php ( 4.57 KB )
  110. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/builder/Mysql.php ( 16.58 KB )
  111. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/Builder.php ( 24.06 KB )
  112. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/BaseBuilder.php ( 27.50 KB )
  113. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/Query.php ( 15.71 KB )
  114. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/BaseQuery.php ( 45.13 KB )
  115. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/TimeFieldQuery.php ( 7.43 KB )
  116. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/AggregateQuery.php ( 3.26 KB )
  117. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/ModelRelationQuery.php ( 20.07 KB )
  118. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/ParamsBind.php ( 3.66 KB )
  119. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/ResultOperation.php ( 7.01 KB )
  120. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/WhereQuery.php ( 19.37 KB )
  121. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/JoinAndViewQuery.php ( 7.11 KB )
  122. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/TableFieldInfo.php ( 2.63 KB )
  123. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/Transaction.php ( 2.77 KB )
  124. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/log/driver/File.php ( 5.96 KB )
  125. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/LogHandlerInterface.php ( 0.86 KB )
  126. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/log/Channel.php ( 3.89 KB )
  127. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/event/LogRecord.php ( 1.02 KB )
  128. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/Collection.php ( 16.47 KB )
  129. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/facade/View.php ( 1.70 KB )
  130. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/View.php ( 4.39 KB )
  131. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Response.php ( 8.81 KB )
  132. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/response/View.php ( 3.29 KB )
  133. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Cookie.php ( 6.06 KB )
  134. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-view/src/Think.php ( 8.38 KB )
  135. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/TemplateHandlerInterface.php ( 1.60 KB )
  136. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-template/src/Template.php ( 46.61 KB )
  137. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-template/src/template/driver/File.php ( 2.41 KB )
  138. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-template/src/template/contract/DriverInterface.php ( 0.86 KB )
  139. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/runtime/temp/067d451b9a0c665040f3f1bdd3293d68.php ( 11.98 KB )
  140. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-trace/src/Html.php ( 4.42 KB )
  1. CONNECT:[ UseTime:0.000585s ] mysql:host=127.0.0.1;port=3306;dbname=f_mffb;charset=utf8mb4
  2. SHOW FULL COLUMNS FROM `fenlei` [ RunTime:0.000891s ]
  3. SELECT * FROM `fenlei` WHERE `fid` = 0 [ RunTime:0.000328s ]
  4. SELECT * FROM `fenlei` WHERE `fid` = 63 [ RunTime:0.000293s ]
  5. SHOW FULL COLUMNS FROM `set` [ RunTime:0.000477s ]
  6. SELECT * FROM `set` [ RunTime:0.000215s ]
  7. SHOW FULL COLUMNS FROM `article` [ RunTime:0.000544s ]
  8. SELECT * FROM `article` WHERE `id` = 486029 LIMIT 1 [ RunTime:0.000710s ]
  9. UPDATE `article` SET `lasttime` = 1776258121 WHERE `id` = 486029 [ RunTime:0.006825s ]
  10. SELECT * FROM `fenlei` WHERE `id` = 66 LIMIT 1 [ RunTime:0.000279s ]
  11. SELECT * FROM `article` WHERE `id` < 486029 ORDER BY `id` DESC LIMIT 1 [ RunTime:0.003071s ]
  12. SELECT * FROM `article` WHERE `id` > 486029 ORDER BY `id` ASC LIMIT 1 [ RunTime:0.000385s ]
  13. SELECT * FROM `article` WHERE `id` < 486029 ORDER BY `id` DESC LIMIT 10 [ RunTime:0.002749s ]
  14. SELECT * FROM `article` WHERE `id` < 486029 ORDER BY `id` DESC LIMIT 10,10 [ RunTime:0.002913s ]
  15. SELECT * FROM `article` WHERE `id` < 486029 ORDER BY `id` DESC LIMIT 20,10 [ RunTime:0.003810s ]
0.100601s