03_模型I/O:输入提示、调用模型、解析输出 | 豆包MarsCode AI刷题

68 阅读5分钟

用LangChain实现鲜花文案自动生成器:深入理解模型 I/O


模型在LangChain中的核心地位

LangChain框架的核心逻辑是基于语言模型(LLM)来驱动的。我们通过LangChain调用大语言模型,将其强大的文本处理和生成能力应用到实际问题中,比如本文的鲜花文案自动生成器。

在LangChain的应用开发中,模型的使用过程可以被分解为三个环节:输入提示(Input/Format)调用模型(Predict)解析输出(Output/Parse) 。这三个环节被统称为 Model I/O,也是LangChain提供的一整套解决方案的基础。

下面,我们通过一个鲜花文案生成器的完整案例,带你深入理解 Model I/O 的每个环节。


1. 提示模板(Prompt Template)

提示模板是模型的起点,定义了模型输入的内容格式。一个好的提示可以大幅提高模型输出的质量。

示例:为鲜花生成描述文案

我们希望模型为每种鲜花生成一段吸引人的描述。模板如下:

python
复制代码
from langchain.prompts import PromptTemplate

# 创建提示模板
template = """您是一位专业的鲜花店文案撰写员。
对于售价为 {price} 元的 {flower_name} ,您能提供一个吸引人的简短描述吗?
"""
prompt = PromptTemplate.from_template(template)  # 将字符串模板转化为LangChain的PromptTemplate对象

这个模板中有两个占位符变量 {flower_name}{price},分别表示鲜花名称和价格。你可以在需要时动态替换它们。

使用提示模板生成输入

python
复制代码
input_prompt = prompt.format(flower_name="玫瑰", price=50)
print(input_prompt)

输出内容:

复制代码
您是一位专业的鲜花店文案撰写员。
对于售价为 50 元的 玫瑰 ,您能提供一个吸引人的简短描述吗?

模板的意义:

  • 易于复用:不同场景下只需替换变量即可。
  • 提高清晰度:让模型明确任务,生成更加符合预期的结果。

2. 调用模型

LangChain支持多种语言模型(LLM)接口,包括OpenAI、HuggingFace等。我们使用OpenAI的gpt-3.5-turbo模型来生成文案。

代码示例:调用模型

python
复制代码
import os
from langchain.llms import OpenAI

# 设置OpenAI API Key
os.environ["OPENAI_API_KEY"] = "你的OpenAI API Key"

# 创建模型实例
model = OpenAI(model_name="gpt-3.5-turbo")

# 输入提示
input_prompt = prompt.format(flower_name="玫瑰", price=50)

# 调用模型生成输出
output = model(input_prompt)
print(output)

输出结果:

复制代码
让你心动!50元就可以拥有这支充满浪漫气息的玫瑰花束,让TA感受你的真心爱意。

3. 解析输出(Output Parsing)

有时候,我们不仅需要文本,还希望提取出具体的结构化数据。LangChain提供了 输出解析器(Output Parser) ,帮助我们将非结构化文本转化为程序可以处理的结构化数据。

定义输出结构

假设我们希望模型返回两个字段:

  1. description:鲜花的描述文案。
  2. reason:描述文案的理由。

创建输出解析器

python
复制代码
from langchain.output_parsers import StructuredOutputParser, ResponseSchema

# 定义响应模式
response_schemas = [
    ResponseSchema(name="description", description="鲜花的描述文案"),
    ResponseSchema(name="reason", description="撰写文案的理由")
]

# 创建输出解析器
output_parser = StructuredOutputParser.from_response_schemas(response_schemas)

# 获取输出格式说明
format_instructions = output_parser.get_format_instructions()

结合解析器生成提示模板

我们将解析器的格式指令整合到提示模板中:

python
复制代码
prompt_template = """您是一位专业的鲜花店文案撰写员。
对于售价为 {price} 元的 {flower_name} ,您能提供一个吸引人的简短描述吗?
{format_instructions}
"""
prompt = PromptTemplate.from_template(prompt_template, partial_variables={"format_instructions": format_instructions})

完整调用过程

我们将调用模型并解析输出为结构化数据:

python
复制代码
# 输入数据
flowers = ["玫瑰", "百合", "康乃馨"]
prices = [50, 30, 20]

# 存储结果的列表
results = []

for flower, price in zip(flowers, prices):
    # 生成输入提示
    input_prompt = prompt.format(flower_name=flower, price=price)
    
    # 获取模型输出
    output = model(input_prompt)
    
    # 解析输出
    parsed_output = output_parser.parse(output)
    
    # 添加额外信息
    parsed_output["flower_name"] = flower
    parsed_output["price"] = price
    results.append(parsed_output)

# 打印解析后的结构化数据
for result in results:
    print(result)

解析后的输出:

json
复制代码
[  {    "flower_name": "玫瑰",    "price": 50,    "description": "这支玫瑰花色浓郁,象征深沉的爱意。",    "reason": "玫瑰是爱情的象征,吸引热恋中的情侣购买。"  },  {    "flower_name": "百合",    "price": 30,    "description": "洁白的百合象征着纯洁与美好。",    "reason": "百合的象征意义能打动追求简约浪漫的顾客。"  },  {    "flower_name": "康乃馨",    "price": 20,    "description": "康乃馨代表关爱,是母亲节的最佳选择。",    "reason": "康乃馨的寓意使其成为送礼首选,尤其适合表达感恩之情。"  }]

4. 保存到文件

将解析结果保存为CSV文件,便于后续分析或使用:

python
复制代码
import pandas as pd

# 转换为DataFrame
df = pd.DataFrame(results)

# 保存到CSV文件
df.to_csv("flower_descriptions.csv", index=False)
print("文件保存成功:flower_descriptions.csv")

LangChain的优势总结

  1. 模板管理:LangChain提供了强大的提示模板工具,让提示构建更高效、更可复用。
  2. 灵活调用:支持多种语言模型接口(如OpenAI、HuggingFace)。
  3. 输出解析:将非结构化文本转化为结构化数据,便于后续处理。
  4. 扩展性强:只需修改模型配置即可轻松切换不同的语言模型。

小提示

在运行 DocQA.py 文件时,如果终端等待很久没有输出,不要着急!这是因为程序在处理模型请求。等待程序完成后,可以点击右侧工具栏中的“眼睛”图标展开结果,查看生成内容。


希望这篇教程帮助你更清晰地理解LangChain的Model I/O流程,同时激发你在实际项目中应用LangChain的兴趣!如果你有更多想法,欢迎留言交流! 😊