[智能体-186]:LLMChain 代码使用示例
2026/6/1 11:14:10 网站建设 项目流程

LLMChain是 LangChain 早期经典链路写法,在 LCEL 管道出现前,是串联提示词 + 大模型的核心组件。下面分基础用法、传参、结合解析器、多示例、对比 LCEL 逐一演示。

环境依赖

bash

运行

pip install langchain langchain-openai

公共导入与模型初始化

python

运行

from langchain_openai import ChatOpenAI from langchain_core.prompts import ChatPromptTemplate, PromptTemplate from langchain.chains import LLMChain from langchain_core.output_parsers import StrOutputParser, JsonOutputParser # 初始化大模型 llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)

一、基础用法:最简 LLMChain

1. 字符串模板 + LLMChain

python

运行

# 1. 定义提示词模板 prompt = PromptTemplate( input_variables=["question"], # 声明输入变量 template="请简要回答问题:{question}" ) # 2. 实例化 LLMChain chain = LLMChain(llm=llm, prompt=prompt) # 3. 执行调用,传入参数字典 result = chain.invoke({"question": "Python 是什么?"}) # 打印结果 print("完整返回:", result) print("模型回答:", result["text"])

返回说明chain.invoke()返回字典,默认模型输出存在text键中。

2. ChatPromptTemplate 对话模板(推荐)

适配聊天模型,写法更贴合对话场景:

python

运行

# 对话风格提示词 chat_prompt = ChatPromptTemplate.from_messages([ ("system", "你是一名技术助手,回答简洁明了"), ("user", "{query}") ]) # 构建链 chain = LLMChain(llm=llm, prompt=chat_prompt) # 执行 res = chain.run(query="什么是 LLMChain?") # 简易 run 方法,直接传参数 print(res)
  • chain.run(变量值):简易调用,适合单变量场景;
  • chain.invoke(字典):标准调用,支持多变量。

二、多输入变量场景

模板包含多个占位符,同时传入多个参数:

python

运行

# 多变量模板 prompt = PromptTemplate( input_variables=["name", "skill"], template="姓名:{name},擅长技能:{skill},请用一句话介绍这个人" ) chain = LLMChain(llm=llm, prompt=prompt) # 传入多个变量 res = chain.invoke({ "name": "张三", "skill": "Python 开发、大模型应用" }) print(res["text"])

三、LLMChain 搭配输出解析器

和解析器结合,实现结构化输出(JSON / 字符串):

示例 1:搭配 StrOutputParser

python

运行

prompt = PromptTemplate(template="总结下文内容:{content}", input_variables=["content"]) parser = StrOutputParser() # 组合:LLMChain + 解析器 chain = LLMChain(llm=llm, prompt=prompt) | parser # 调用,直接得到字符串(不再是字典) result = chain.invoke({"content": "LLMChain 是 LangChain 早期的链路组件,用于串联提示词与大模型。"}) print(result)

示例 2:搭配 JsonOutputParser 输出 JSON

python

运行

prompt = PromptTemplate( input_variables=["info"], template=""" 解析人物信息,只返回标准JSON,字段:name, age 内容:{info} """ ) json_parser = JsonOutputParser() # 链路组合 chain = LLMChain(llm=llm, prompt=prompt) | json_parser # 调用,直接得到字典 data = chain.invoke({"info": "李四,26岁"}) print(type(data), data)

四、批量执行

使用chain.batch()批量处理多组输入:

python

运行

prompt = PromptTemplate(input_variables=["q"], template="回答问题:{q}") chain = LLMChain(llm=llm, prompt=prompt) # 批量输入列表 batch_inputs = [ {"q": "1+1等于几"}, {"q": "地球是什么形状"} ] # 批量调用 batch_results = chain.batch(batch_inputs) for idx, item in enumerate(batch_results): print(f"问题{idx+1}回答:{item['text']}")

五、传统 LLMChain 嵌套(复杂流程)

早期实现多步骤流程需要链式嵌套,写法相比 LCEL 更繁琐:

python

运行

# 第一步:提取关键词 prompt1 = PromptTemplate(input_variables=["text"], template="提取关键词:{text}") chain1 = LLMChain(llm=llm, prompt=prompt1) # 第二步:根据关键词写短句 prompt2 = PromptTemplate(input_variables=["kw"], template="根据关键词写一句话:{kw}") chain2 = LLMChain(llm=llm, prompt=prompt2) # 手动串联:取上一步结果,传给下一步 text = "人工智能赋能传统行业" res1 = chain1.invoke({"text": text}) kw = res1["text"] res2 = chain2.invoke({"kw": kw}) print("关键词:", kw) print("最终句子:", res2["text"])

缺点:需要手动取值、传参,链路越长代码越臃肿。


六、LLMChain 与 LCEL 管道 写法对比

同一功能,两种实现直观对比:

1. LLMChain 写法

python

运行

prompt = ChatPromptTemplate.from_messages([("user", "回答:{question}")]) chain = LLMChain(llm=llm, prompt=prompt) res = chain.invoke({"question": "介绍大模型"}) print(res["text"])

2. 等效 LCEL 管道写法(官方主推)

python

运行

prompt = ChatPromptTemplate.from_messages([("user", "回答:{question}")]) chain = prompt | llm | StrOutputParser() res = chain.invoke({"question": "介绍大模型"}) print(res)

七、核心特点总结

  1. 核心结构LLMChain = 提示词模板 + 大模型,是最基础的执行链;
  2. 返回值:原生返回字典,模型输出默认在text字段;
  3. 调用方式
    • invoke(字典):标准调用
    • run(变量):简易单参数调用
    • batch(列表):批量调用
  4. 优缺点
    • 优点:入门简单,历史项目大量使用,兼容性好;
    • 缺点:多步骤流程需要手动传参、代码冗余,原生流式、并行支持弱,复杂链路维护成本高;
  5. 现状:LangChain 官方现已推荐 LCEL 管道写法LLMChain偏向维护旧项目、学习理解历史架构

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询