程序辅助语言模型(PAL)链 Program-aided language model (PAL) chain
实现了程序辅助语言模型,参考论文 https://arxiv.org/pdf/2211.10435.pdf。
from langchain.chains import PALChain
from langchain import OpenAI
llm = OpenAI(temperature=0, max_tokens=512)
数学提示 (Math Prompt)
pal_chain = PALChain.from_math_prompt(llm, verbose=True)
question = "Jan has three times the number of pets as Marcia. Marcia has two more pets than Cindy. If Cindy has four pets, how many total pets do the three have?"
pal_chain.run(question)
> 进入新的PALChain链...
def solution():
"""Jan has three times the number of pets as Marcia. Marcia has two more pets than Cindy. If Cindy has four pets, how many total pets do the three have?"""
cindy_pets = 4
marcia_pets = cindy_pets + 2
jan_pets = marcia_pets * 3
total_pets = cindy_pets + marcia_pets + jan_pets
result = total_pets
return result
> 完成链。
'28'
彩色物体 (Colored Objects)
pal_chain = PALChain.from_colored_object_prompt(llm, verbose=True)
question = "On the desk, you see two blue booklets, two purple booklets, and two yellow pairs of sunglasses. If I remove all the pairs of sunglasses from the desk, how many purple items remain on it?"
pal_chain.run(question)
> 进入新的PALChain链...
# 将物体放入列表以记录顺序
objects = []
objects += [('booklet', 'blue')] * 2
objects += [('booklet', 'purple')] * 2
objects += [('sunglasses', 'yellow')] * 2
# 移除所有的太阳镜
objects = [object for object in objects if object[0] != 'sunglasses']
# 计算紫色物体的数量
num_purple = len([object for object in objects if object[1] == 'purple'])
answer = num_purple
> 完成PALChain链.
'2'
中间步骤 (Intermediate Steps)
您还可以使用中间步骤标志来返回生成答案的执行代码。
pal_chain = PALChain.from_colored_object_prompt(
llm, verbose=True, return_intermediate_steps=True
)
question = "On the desk, you see two blue booklets, two purple booklets, and two yellow pairs of sunglasses. If I remove all the pairs of sunglasses from the desk, how many purple items remain on it?"
result = pal_chain({"question": question})
> 进入新的PALChain链...
# 将物体放入列表以记录顺序
objects = []
objects += [('booklet', 'blue')] * 2
objects += [('booklet', 'purple')] * 2
objects += [('sunglasses', 'yellow')] * 2
# 移除所有的太阳镜
objects = [object for object in objects if object[0] != 'sunglasses']
# 计算紫色物体的数量
num_purple = len([object for object in objects if object[1] == 'purple'])
answer = num_purple
> 完成链.
result["intermediate_steps"]
"# 将物体放入列表以记录顺序\nobjects = []\nobjects += [('booklet', 'blue')] * 2\nobjects += [('booklet', 'purple')] * 2\nobjects += [('sunglasses', 'yellow')] * 2\n\n# 移除所有的太阳镜\nobjects = [object for object in objects if object[0] != 'sunglasses']\n\n# 计算紫色物体的数量\nnum_purple = len([object for object in objects if object[1] == 'purple'])\nanswer = num_purple"