1. LangChain智能体开发实战:从提示词工程到高级解析技术
作为一名长期从事AI应用开发的工程师,我深知LangChain在构建智能体(Agent)方面的强大能力。本教程将带您深入探索LangChain的高级应用技巧,从基础的提示词工程到复杂的输出解析,每个环节都配有实战代码和深度解析。
1.1 对话式提示词工程进阶
在传统的小样本学习中,我们通常将示例直接嵌入单一提示词。但随着大模型对话能力的提升,更高效的方式是利用多轮对话历史来引导模型输出。
1.1.1 固定示例模板实现
固定示例是最基础的小样本提示技术,适合需要稳定输出的场景。以下是完整实现方案:
python复制from langchain_core.prompts import (
ChatPromptTemplate,
FewShotChatMessagePromptTemplate,
)
# 定义数学运算示例
examples = [
{"input": "2+2", "output": "4"},
{"input": "2+3", "output": "5"},
]
# 构建示例模板
example_prompt = ChatPromptTemplate.from_messages([
("human", "{input}"),
("ai", "{output}"),
])
# 组装少样本提示模板
few_shot_prompt = FewShotChatMessagePromptTemplate(
example_prompt=example_prompt,
examples=examples,
)
# 最终提示组合
final_prompt = ChatPromptTemplate.from_messages([
("system", "你是一位非常厉害的数学天才。"),
few_shot_prompt,
("human", "{input}"),
])
关键点解析:
FewShotChatMessagePromptTemplate将示例转换为对话格式- 系统消息设定角色定位
- 示例作为上下文嵌入对话历史
1.1.2 动态示例选择技术
当需要根据输入动态选择示例时,语义相似度选择器是更好的选择:
python复制from langchain_core.example_selectors import SemanticSimilarityExampleSelector
from langchain_community.vectorstores import Chroma
from langchain_huggingface import HuggingFaceEmbeddings
# 初始化嵌入模型
embeddings = HuggingFaceEmbeddings(model_name="bge-large-zh-v1.5")
# 准备示例数据集
examples = [
{"input": "2+2", "output": "4"},
{"input": "牛对月亮说了什么?", "output": "什么都没有"},
# 更多示例...
]
# 构建向量存储
to_vectorize = [" ".join(example.values()) for example in examples]
vectorst
