LV015-LangChain链的确定性输出
实验 4:LangChain链的确定性输出
一、实验详情
** 目标**:使用 LangChain 链生成广告文案
文件位置:student_code/lab4/main.py
需要实现:generate_ad() 函数
任务要求:
- 使用PromptTemplate定义模板(包含 {product} 和 {feature})
- 创建LLMChain连接Prompt和LLM
- 生成广告文案并计算字数
- 返回结构化结果
关键要求:
- 使用
PromptTemplate定义模板(包含 {product} 和 {feature}) - 创建
LLMChain连接 Prompt 和 LLM - 返回字典包含 ad_copy, word_count, template_used
- word_count 必须等于 len(ad_copy)
实现提示:
# 当前状态:raise NotImplementedError("请实现 generate_ad 函数")
# 你需要:
# 1. 创建包含{product}和{feature}的PromptTemplate
# 2. 创建Ollama LLM实例
# 3. 创建LLMChain连接prompt和llm
# 4. 调用chain.run()或chain.predict()
# 5. 返回包含ad_copy, word_count, template_used的字典LangChain 示例:
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
template = "为产品 {product} 创作广告,特性:{feature}"
prompt = PromptTemplate(
input_variables=["product", "feature"],
template=template
)
chain = LLMChain(llm=llm, prompt=prompt)
result = chain.run(product="智能手表", feature="心率监测")测试运行:
pytest grader/test_lab4.py -v测试用例:
- ✅ 输出结构验证(20%)
- ✅ 字数一致性(25%)
- ✅ 产品名包含(20%)
- ✅ 特性包含(20%)
- ✅ 长度合理性(15%)
- 🌟 多产品批量测试(加分项)
二、环境准备
1. 系统要求
- Python: 3.10 或更高版本
- 操作系统: Linux / macOS / Windows
- Ollama: 本地 AI 模型服务
2. 安装 Ollama
2.1 Linux / macOS
bash
# 安装 Ollama
curl -fsSL https://ollama.ai/install.sh | sh
# 启动 Ollama 服务
ollama serve
# 下载 Qwen3-8B 模型(新开一个终端)
ollama pull qwen3:8b2.2 Windows
- 访问 Ollama 官网 下载 Windows 安装包
- 安装并启动 Ollama
- 在命令提示符中运行:
ollama pull qwen3:8b
3. 验证 Ollama 服务
bash
# 检查 Ollama 是否运行
curl http://localhost:11434/api/tags
# 应该返回包含 qwen3:8b 的模型列表4. 安装 Python 依赖
bash
# 安装依赖
pip install -r requirements.txtrequirements.txt 内容如下:
markdown
langchain==0.3.27
langchain-community>=0.0.10
pydantic>=2.0.0
pytest>=7.4.0
pytest-timeout>=2.1.0
pytest-json-report>=1.5.0
httpx>=0.25.0三、实验示例
1. main.py
python
"""
实验4:LangChain 链的确定性输出
学生需要使用 LangChain 的 PromptTemplate 和 LLMChain 生成广告文案
"""
# 提示:需要导入 LangChain 相关模块
from langchain_core.prompts import PromptTemplate
from langchain_community.llms import Ollama
from langchain.chains import LLMChain
def generate_ad(input_dict: dict) -> dict:
"""
使用 LangChain 链生成广告文案
参数:
input_dict: 字典,包含:
- product (str): 产品名称
- feature (str): 核心特性
返回:
字典,包含:
- ad_copy (str): 生成的广告文案
- word_count (int): 文案字数(使用 len(ad_copy) 统计)
- template_used (str): 使用的模板名称
实现要求:
1. 使用 PromptTemplate 定义广告文案生成模板
2. 创建 LLMChain,连接 PromptTemplate 和 Ollama LLM
3. 链的输出必须经过后处理,提取文案并计算字数
4. 模板必须包含 {product} 和 {feature} 两个变量
5. word_count 必须与 ad_copy 的实际长度一致
"""
# 1. 创建 PromptTemplate,包含产品和特性变量
prompt = PromptTemplate(
input_variables=["product", "feature"],
template="""你现在是是广告文案设计师。我需要你帮我设计一个广告文案,要求如下:
产品名称:{product}
核心特性:{feature}
要求:
1. 文案中必须包含完整的产品名称"{product}"
2. 文案中必须包含完整的特性名称"{feature}"
3. 文案字数控制在100字以内
4. 语言生动有趣,可以吸引用户
5. 直接输出广告文案,不要包含任何其他内容。"""
)
# 2. 创建 Ollama LLM 实例
llm = Ollama(
model="qwen3:0.6b",
base_url="http://localhost:11434"
)
# 3. 创建 LLMChain,连接 Prompt 和 LLM
chain = LLMChain(
llm=llm,
prompt=prompt
)
# 4. 运行链,传入产品和特性参数,这些参数就是 PromptTemplate 中对应的变量
try:
result = chain.invoke({
"product": input_dict["product"],
"feature": input_dict["feature"]
})
# 5. 提取文案
ad_copy = result.get("text", "") if isinstance(result, dict) else str(result)
# 清理文案(去除多余的空白字符)
ad_copy = ad_copy.strip()
# 计算字数
word_count = len(ad_copy)
# 6. 返回结构化结果
return {
"ad_copy": ad_copy,
"word_count": word_count,
"template_used": "base_template"
}
except Exception as e:
raise Exception(f"生成广告文案时发生错误: {e}")
# 测试代码(可选,用于学生本地调试)
if __name__ == "__main__":
# 测试基础版本
print("=== 测试基础广告生成 ===")
test_inputs = [
{"product": "智能手表", "feature": "心率监测"},
{"product": "无线耳机", "feature": "降噪功能"},
{"product": "扫地机器人", "feature": "自动避障"}
]
for input_data in test_inputs:
try:
result = generate_ad(input_data)
print(f"\n产品: {input_data['product']}")
print(f"文案: {result['ad_copy']}")
print(f"字数: {result['word_count']}")
print(f"模板: {result['template_used']}")
except Exception as e:
print(f"错误: {e}")2. 运行结果
shell
python .\main.py【例】
shell
D:\sumu_blog\python-ai\lab4> python .\main.py
=== 测试基础广告生成 ===
D:\sumu_blog\python-ai\lab4\main.py:54: LangChainDeprecationWarning: The class `LLMChain` was deprecated in LangChain 0.1.17 and will be removed in 1.0. Use RunnableSequence, e.g., `prompt | llm` instead.
chain = LLMChain(
产品: 智能手表
文案: 你的健康,从12小时开始!智能手表心率监测,实时守护你的每一刻。
字数: 32
模板: base_template
产品: 无线耳机
文案: 【沉浸式降噪,让音质更清晰】
无线耳机,降噪功能让音质更清晰,开启你的沉浸式体验。立刻购买,开启你的新音域!
字数: 56
模板: base_template
产品: 扫地机器人
文案: 扫地机器人,自动避障,让生活更轻松!✨
字数: 19
模板: base_template