Langchain 的 LLMChain

LLMChain 是一个简单的链,它围绕语言模型添加了一些功能。它在整个LangChain中广泛使用,包括在其他链和代理中。

LLMChain 由 PromptTemplate 和语言模型(LLM 或聊天模型)组成。它使用提供的输入键值(以及内存键值,如果可用)格式化提示模板,将格式化的字符串传递给 LLM 并返回 LLM 输出。

1. 开始使用

示例代码,

import os
import openai

from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv()) # read local .env file
os.environ['OPENAI_API_KEY'] = os.environ['OPENAI_API_KEY']
os.environ['OPENAI_API_BASE'] = os.environ['OPENAI_API_BASE']
openai.api_key = os.environ['OPENAI_API_KEY']
openai.api_base = os.environ['OPENAI_API_BASE']

import warnings
warnings.filterwarnings('ignore')
from langchain import PromptTemplate, OpenAI, LLMChain

prompt_template = "对于一家生产{产品}的公司来说,取一个什么中文名字好?只需回复一个答案。"

llm = OpenAI(temperature=0)
llm_chain = LLMChain(
    llm=llm,
    prompt=PromptTemplate.from_template(prompt_template)
)
llm_chain("彩色袜子")

输出结果,

{'产品': '彩色袜子', 'text': '\n\n彩趣袜业'}

运行 LLM 链的其他方式

除了所有 Chain 对象共享的 call 和 run 方法之外, LLMChain 还提供了几种调用链逻辑的方法:

apply 允许您针对输入列表运行链:

示例代码,

input_list = [
    {"产品": "袜子"},
    {"产品": "计算机"},
    {"产品": "鞋"}
]

llm_chain.apply(input_list)

输出结果,

[{'text': '\n\n袜袜家'}, {'text': '\n\n计算之星'}, {'text': '\n\n鞋之家'}]

generate 与 apply 类似,只是它返回 LLMResult 而不是字符串。 LLMResult 通常包含有用的生成,例如令牌用法和完成原因。

llm_chain.generate(input_list)

输出结果,

LLMResult(generations=[[Generation(text='\n\n袜袜家', generation_info={'finish_reason': 'stop', 'logprobs': None})], [Generation(text='\n\n计算之星', generation_info={'finish_reason': 'stop', 'logprobs': None})], [Generation(text='\n\n鞋之家', generation_info={'finish_reason': 'stop', 'logprobs': None})]], llm_output={'token_usage': {'prompt_tokens': 198, 'total_tokens': 227, 'completion_tokens': 29}, 'model_name': 'text-davinci-003'}, run=[RunInfo(run_id=UUID('4c04d0ca-c183-4723-a1ad-8949ec0a67c9')), RunInfo(run_id=UUID('c581efac-f58d-447d-a7d7-df84088987db')), RunInfo(run_id=UUID('932ab858-8eda-494d-91b4-8f75dbfa1096'))])

predict 与 run 方法类似,只不过输入键被指定为关键字参数而不是 Python 字典。

# 单个输入示例
llm_chain.predict(产品="彩色袜子")

输出结果,

'\n\n彩趣袜业'
# 多个输入示例

template = """告诉我一个关于{主题}的{形容词}笑话。"""
prompt = PromptTemplate(template=template, input_variables=["形容词", "主题"])
llm_chain = LLMChain(prompt=prompt, llm=OpenAI(temperature=0))

llm_chain.predict(形容词="悲伤", 主题="鸭子")

输出结果,

'\n\n一只鸭子在湖边游泳,突然发现自己被困在了一个漩涡里,它拼命地挣扎,但是没有用,它只能眼睁睁地看着自己被淹死。这时,一只鹅飞过来,看到了这一幕,它对鸭子说:“别担心,我会帮你!”于是,鹅用它的嘴巴把鸭子吸出了漩涡,鸭子很感激'

解析输出

默认情况下,即使底层 prompt 对象具有输出解析器, LLMChain 也不解析输出。如果您想在 LLM 输出上应用该输出解析器,请使用 predict_and_parse 而不是 predict 和 apply_and_parse 而不是 apply 。

对于 predict :

from langchain.output_parsers import CommaSeparatedListOutputParser

output_parser = CommaSeparatedListOutputParser()
template = """列出彩虹中的所有颜色"""
prompt = PromptTemplate(template=template, input_variables=[], output_parser=output_parser)
llm_chain = LLMChain(prompt=prompt, llm=llm)

llm_chain.predict()

输出结果,

'\n\n红色、橙色、黄色、绿色、青色、蓝色、紫色'

对于 predict_and_parser :

llm_chain.predict_and_parse()

输出结果,

['红色、橙色、黄色、绿色、青色、蓝色、紫色']
# 英文的输出结果
# ['Red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']

从字符串初始化

您还可以直接从字符串模板构造LLMChain。

template = """告诉我一个关于{主题}的{形容词}笑话。"""
llm_chain = LLMChain.from_string(llm=llm, template=template)
llm_chain.predict(形容词="悲伤", 主题="鸭子")

输出结果,

'\n\n一只鸭子在湖边游泳,突然发现自己被困在了一个漩涡里,它拼命地挣扎,但是没有用,它只能眼睁睁地看着自己被淹死。这时,一只鹅飞过来,看到了这一幕,它对鸭子说:“别担心,我会帮你!”于是,鹅用它的嘴巴把鸭子吸出了漩涡,鸭子很感激'

完结!

猜你喜欢

转载自blog.csdn.net/engchina/article/details/131884919