1. 项目概述
在LangChain生态中,LLM(大语言模型)与提示词(Prompt)的协作机制是构建智能应用的核心枢纽。作为长期使用LangChain框架的开发者,我发现许多初学者常陷入两个极端:要么过度依赖LLM的原始能力而忽视提示词工程,要么陷入复杂的提示词设计却未充分利用框架特性。本文将基于实战经验,拆解两者在LangChain中的7种典型协作模式。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 核心概念解析
2.1 LangChain中的LLM抽象层
LangChain通过统一的LLM抽象接口支持多种模型接入,包括:
- OpenAI GPT系列
- Anthropic Claude
- 本地部署的Llama.cpp等开源模型
关键设计在于BaseLLM抽象类,它定义了_generate()和_agenerate()两个核心方法。这种设计使得不同模型的差异被标准化处理,开发者可以无缝切换模型提供商而不必重写业务逻辑。
2.2 提示词工程的三层结构
在LangChain框架中,提示词的处理分为:
- 模板层:使用
PromptTemplate定义变量插值
python复制from langchain.prompts import PromptTemplate
template = "作为{role},请用{style}风格回答:{question}"
prompt = PromptTemplate.from_template(template)
- 组装层:通过
PipelinePrompt组合多个子提示 - 优化层:应用
FewShotPromptTemplate等增强技巧
3. 七种协作模式详解
3.1 基础直连模式
最简单的协作方式,适合简单问答场景:
python复制from langchain.llms import OpenAI
llm = OpenAI(temperature=0.7)
prompt = "解释量子计算的基本概念"
response = llm(prompt)
注意事项:
- 温度参数(temperature)建议设置在0.5-0.9之间
- 最大token数需根据模型上下文窗口调整
3.2 模板变量注入
生产环境推荐的标准做法:
python复制template = """你是一位{expert_type}专家,请用{audience}能理解的方式解释{concept}"""
prompt = PromptTemplate(
input_variables=["expert_type", "audience", "concept"],
template=template
)
formatted_prompt = prompt.format(
expert_type="量子物理",
audience="高中生",
concept="量子纠缠"
)
llm_response = llm(formatted_prompt)
3.3 少样本学习增强
通过示例提升模型表现:
python复制from langchain.prompts import FewShotPromptTemplate
examples = [
{"input": "光合作用", "output": "植物利用阳光将CO2和水转化为糖分的过程"},
{"input": "细胞分裂", "output": "一个细胞分裂产生两个子细胞的生物学过程"}
]
example_prompt = PromptTemplate(
input_variables=["input", "output"],
template="输入:{input}\n输出:{output}"
)
few_shot_prompt = FewShotPromptTemplate(
examples=examples,
example_prompt=example_prompt,
suffix="输入:{query}\n输出:",
input_variables=["query"]
)
3.4 链式协作
将多个LLM调用串联:
python复制from langchain.chains import LLMChain
first_prompt = PromptTemplate(...)
second_prompt = PromptTemplate(...)
chain1 = LLMChain(llm=llm, prompt=first_prompt)
chain2 = LLMChain(llm=llm, prompt=second_prompt)
overall_chain = SimpleSequentialChain(chains=[chain1, chain2])
result = overall_chain.run(input="原始输入")
3.5 动态提示选择
根据输入选择不同提示模板:
python复制from langchain.chains.router import MultiPromptChain
prompt_infos = [
{
"name": "physics",
"description": "适合物理相关问题",
"prompt_template": "..."
},
{
"name": "math",
"description": "适合数学问题",
"prompt_template": "..."
}
]
chain = MultiPromptChain.from_prompts(
llm,
prompt_infos,
default_chain=default_chain
)
3.6 记忆增强提示
在对话中保持上下文:
python复制from langchain.memory import ConversationBufferMemory
memory = ConversationBufferMemory()
conversation = ConversationChain(
llm=llm,
memory=memory,
prompt=prompt
)
3.7 外部工具集成
结合搜索、计算等工具:
python复制from langchain.agents import load_tools
tools = load_tools(['serpapi', 'wolfram-alpha'], llm=llm)
agent = initialize_agent(
tools,
llm,
agent="zero-shot-react-description",
verbose=True
)
4. 性能优化技巧
4.1 提示词压缩技术
对于长上下文场景:
python复制from langchain.text_splitter import TokenTextSplitter
splitter = TokenTextSplitter(chunk_size=2000)
texts = splitter.split_text(long_text)
4.2 缓存策略
减少重复计算:
python复制from langchain.cache import InMemoryCache
langchain.llm_cache = InMemoryCache()
4.3 异步处理
提升吞吐量:
python复制async def generate_concurrently():
tasks = [llm.agenerate(prompts) for prompt in prompt_list]
await asyncio.gather(*tasks)
5. 常见问题排查
5.1 输出不符合预期
检查清单:
- 确认提示词中的变量已正确填充
- 检查模型temperature参数设置
- 验证是否有足够的示例样本
5.2 处理长文本时截断
解决方案:
- 使用
RecursiveCharacterTextSplitter分段处理 - 调整模型的
max_tokens参数
5.3 API调用超时
优化建议:
- 实现指数退避重试机制
- 使用
timeout=30参数显式设置超时
6. 进阶应用场景
6.1 构建领域知识库
结合RAG架构:
python复制from langchain.vectorstores import FAISS
from langchain.embeddings import OpenAIEmbeddings
vectorstore = FAISS.from_texts(
texts,
embedding=OpenAIEmbeddings()
)
retriever = vectorstore.as_retriever()
6.2 实现复杂工作流
使用LangGraph编排:
python复制from langgraph.graph import Graph
workflow = Graph()
workflow.add_node("research", research_node)
workflow.add_node("write", write_node)
workflow.set_entry_point("research")
workflow.add_edge("research", "write")
6.3 质量评估体系
构建自动评估链:
python复制eval_prompt = """根据以下标准评估回答质量:
- 准确性:{criteria1}
- 完整性:{criteria2}
"""
evaluation_chain = LLMChain(llm=llm, prompt=eval_prompt)
在实际项目中,我发现LLM与提示词的最佳协作需要遵循"3C原则":Context(明确上下文)、Clarity(指令清晰)、Consistency(风格一致)。当遇到复杂场景时,采用分阶段验证法——先测试核心提示词的有效性,再逐步添加业务逻辑层。
