使用 Yi-34B 和 langchain 实现 TOT 的提示词编写

325 阅读2分钟

大家好,我是雨飞。最近在研究 Agent 相关的内容,顺便学习了一些提示词学习的技巧。今天就和大家分享下,如何使用 langchain 实现 Tree of thought (tot) 的提示词编写。

什么是 ToT?

Tree of thought 也就是思维树,是一种提示词编写的技巧,首发于论文

Tree of Thoughts: Deliberate Problem Solving with Large Language Models

ToT 允许 LLM 通过考虑多种不同的推理路径和自我评估选择来进行深思熟虑的决策,以决定下一步行动方案,并在必要时进行前瞻或回溯,以做出全局选择。

从上面的论文和介绍来说,直接使用人工提示词的方式是比较难实现的,反而使用编程的方法会更容易一些,因此,我们使用 langchain 去实现一下这种提示词策略。

SequentialChain

SequentialChain 的形式就是让 LLMChain 的输出输入到下一个 LLMChain 里面,我们可以定义一个 SequentialChain 去接受 tot 的各个提示词,然后组合成最终的提示词。

总代码

Yi 的大模型调用,可以参考下面这篇文章。

雨飞:使用 Yi-34B 和 langchain 去实现 OpenAI 的多工具调用

from langchain import hub
from langchain.chains import LLMChain
from langchain.chains import SequentialChain
cot_step1 = hub.pull("rachnogstyle/nlw_jan24_cot_step1")
cot_step2 = hub.pull("rachnogstyle/nlw_jan24_cot_step2")
cot_step3 = hub.pull("rachnogstyle/nlw_jan24_cot_step3")
cot_step4 = hub.pull("rachnogstyle/nlw_jan24_cot_step4")

chain1 = LLMChain(llm=yi_llm, prompt=cot_step1,output_key="solutions")
chain2 = LLMChain(llm=yi_llm, prompt=cot_step2,output_key="review")
chain3 = LLMChain(llm=yi_llm, prompt=cot_step3,output_key="deepen_thought_process")
chain4 = LLMChain(llm=yi_llm, prompt=cot_step4,output_key="ranked_solutions")

overall_chain = SequentialChain(
    chains=[chain1, chain2, chain3, chain4],
    input_variables=["input","perfect_factors"],
    output_variables=["ranked_solutions"],
    verbose=True)
# 人类如何移民火星
result = overall_chain({
    "input":"请用中文回答下面的问题,人类如何移民火星",
    "perfect_factors":"地球和火星之间的距离很长,使得定期补给变得苦难"
})
print(result)

好了,我写完啦,这篇文章到此结束,如果对你有所感悟,欢迎点赞,评论 ,也欢迎加我微 「1060687688」一起交流学习。