学习笔记3《模型I/O:输入提示、调用模型、解析输出》

51 阅读3分钟

学习笔记:LangChain中的模型调用与输出解析

LangChain模型调用优势

模板管理

LangChain帮助管理多个提示模板,保持代码的清晰和整洁。

变量提取和检查

自动提取模板中的变量并进行检查,确保没有遗漏任何变量。

模型切换

只需更改模型名称即可尝试不同的模型,无需修改代码。

输出解析

提示模板可以嵌入输出格式的定义,方便后续处理已经被格式化的输出。

Model I/O流程

输入提示(Format)

使用LangChain模板根据实际需求动态选择不同的输入。

调用模型(Predict)

通过通用接口调用语言模型,提高灵活性和便利性。

输出解析(Parse)

从模型输出中提取信息,将非结构化文本转换成程序可处理的结构化数据。

提示模板构建

创建提示模板

from langchain.prompts import PromptTemplate

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

模型调用

import os
from langchain import OpenAI

os.environ["OPENAI_API_KEY"] = '你的OpenAI API Key'
model = OpenAI(model_name='gpt-3.5-turbo-instruct')

input_prompt = prompt.format(flower_name="玫瑰", price="50")
output = model(input_prompt)

输出解析

定义响应模式

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()

整合输出解析器到提示模板

prompt_template = """您是一位专业的鲜花店文案撰写员。
对于售价为 {price} 元的 {flower_name},您能提供一个吸引人的简短描述吗?
{format_instructions}"""

prompt = PromptTemplate.from_template(prompt_template, 
                partial_variables={"format_instructions": format_instructions})

处理模型输出

import pandas as pd

df = pd.DataFrame(columns=["flower", "price", "description", "reason"])
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'] = flower
    parsed_output['price'] = price
    df.loc[len(df)] = parsed_output  

print(df.to_dict(orient='records'))
df.to_csv("flowers_with_descriptions.csv", index=False)

思考题解答

LangChain调用大语言模型的优势

  • 模板管理:提高代码的可读性和可维护性。
  • 变量处理:自动处理模板中的变量,减少错误。
  • 模型切换:方便尝试不同的模型,提高灵活性。
  • 输出解析:结构化输出,便于后续处理。

format_instructions的构建与传递

format_instructions由输出解析器生成,指示模型如何生成结构化的输出。通过partial_variables整合到提示模板中,引导模型生成预期格式的输出。

模型生成结构化输出

加入partial_variables后,模型更有可能生成结构化的输出,因为提示中包含了明确的输出格式指示。

输出解析的可能性

即使使用了输出解析器,模型也可能返回格式不完美的输出,因为模型的生成并不总是完全符合预期。需要进一步调整提示模板和输出解析器以提高准确性。

总结

通过LangChain框架,我们可以有效地管理提示模板、处理变量、切换模型,并解析模型输出。这使得基于大模型的应用开发更加高效和灵活。下节课将继续深入探索LangChain中的提示模板和输出解析。