新闻  |   论坛  |   博客  |   在线研讨会
独家 | 开始使用LangChain:帮助你构建LLM驱动应用的新手教程(2)
数据派THU | 2023-07-16 18:14:07    阅读:1142   发布文章

提示: 管理LLM输入


LLM有怪异的api。尽管用自然语言向LLM输入提示应该感觉很直观,但在从LLM获得所需的输出之前,需要对提示进行大量调整。这个过程称为提示工程。一旦有了好的提示,您可能希望将其用作其他目的的模板。因此,LangChain为您提供了所谓的提示模板,可帮助您从多个组件构建提示。

from langchain import PromptTemplate
template = "What is a good name for a company that makes {product}?"
prompt = PromptTemplate(    input_variables=["product"],    template=template,)
prompt.format(product="colorful socks")


上面的提示可以看作是Zero-shot Learning(零射击学习是一种设置,模型可以学习识别以前在训练中没有明确看到的事物),您希望LLM在足够的相关数据上进行了训练,以提供令人满意的结果。改善LLM输出的另一个技巧是在提示中添加一些示例,并使其成为一些问题设置。

from langchain import PromptTemplate, FewShotPromptTemplate
examples = [    {"word": "happy", "antonym": "sad"},    {"word": "tall", "antonym": "short"},]
example_template = """Word: {word}Antonym: {antonym}\n"""
example_prompt = PromptTemplate(    input_variables=["word", "antonym"],    template=example_template,)
few_shot_prompt = FewShotPromptTemplate(    examples=examples,    example_prompt=example_prompt,    prefix="Give the antonym of every input",    suffix="Word: {input}\nAntonym:",    input_variables=["input"],    example_separator="\n",)
few_shot_prompt.format(input="big")


上面的代码将生成一个提示模板,并根据提供的示例和输入组成以下提示:

Give the antonym of every input
Word: happyAntonym: sad


Word: tallAntonym: short

Word: bigAntonym:


Chain: 将LLMs与其他组件组合
在LangChain中Chain简单地描述了将LLMs与其他组件组合以创建应用程序的过程。一些示例是: 将LLM与提示模板组合 (请参阅本节),通过将第一个LLM的输出作为第二个LLM的输入来顺序组合多个LLM (请参阅本节),将LLM与外部数据组合,例如,对于问题回答 (请参阅索引),将LLM与长期记忆相结合,例如,对于上一节中的聊天记录 (请参阅内存),我们创建了一个提示模板。当我们想将其与我们的LLM一起使用时,我们可以使用LLMChain,如下所示:

from langchain.chains import LLMChain
chain = LLMChain(llm = llm,                  prompt = prompt)
# Run the chain only specifying the input variable.chain.run("colorful socks")

如果我们想使用这个第一个LLM的输出作为第二个LLM的输入,我们可以使用一个SimpleSequentialChain:
from langchain.chains import LLMChain, SimpleSequentialChain
# Define the first chain as in the previous code example# ...
# Create a second chain with a prompt template and an LLMsecond_prompt = PromptTemplate(    input_variables=["company_name"],    template="Write a catchphrase for the following company: {company_name}",)
chain_two = LLMChain(llm=llm, prompt=second_prompt)
# Combine the first and the second chain overall_chain = SimpleSequentialChain(chains=[chain, chain_two], verbose=True)
# Run the chain specifying only the input variable for the first chain.catchphrase = overall_chain.run("colorful socks")

图片

结果示例


索引:访问外部数据
LLM的一个限制是它们缺乏上下文信息 (例如,访问某些特定文档或电子邮件)。您可以通过允许LLMs访问特定的外部数据来解决此问题。为此,您首先需要使用文档加载器加载外部数据。LangChain为不同类型的文档提供了各种加载程序,从pdf和电子邮件到网站和YouTube视频。让我们从YouTube视频中加载一些外部数据。如果你想加载一个大的文本文档并用文本拆分器拆分它,你可以参考官方文档。

# pip install youtube-transcript-api# pip install pytube
from langchain.document_loaders import YoutubeLoader
loader = YoutubeLoader.from_youtube_url("https://www.youtube.com/watch?v=dQw4w9WgXcQ")
documents = loader.load()


现在,您已经准备好外部数据作为文档,您可以使用矢量数据库 (VectorStore) 中的文本嵌入模型 (请参阅模型) 对其进行索引。流行的矢量数据库包括Pinecone,weavviate和Milvus。在本文中,我们使用的是Faiss,因为它不需要API密钥。

# pip install faiss-cpufrom langchain.vectorstores import FAISS
# create the vectorestore to use as the indexdb = FAISS.from_documents(documents, embeddings)

您的文档 (在本例中为视频) 现在作为嵌入存储在矢量存储中。现在你可以用这个外部数据做各种各样的事情。让我们将其用于带有信息寻回器的问答任务:

from langchain.chains import RetrievalQA
retriever = db.as_retriever()
qa = RetrievalQA.from_chain_type(    llm=llm,    chain_type="stuff",    retriever=retriever,    return_source_documents=True)
query = "What am I never going to do?"result = qa({"query": query})
print(result['result'])


图片

结果示例


存储器: 记住先前的对话
对于像聊天机器人这样的应用程序来说,他们能够记住以前的对话是至关重要的。但是默认情况下,LLMs没有任何长期记忆,除非您输入聊天记录。


图片有无记忆的聊天机器人的对比


LangChain通过提供处理聊天记录的几种不同选项来解决此问题:

  • 保留所有对话
  • 保留最新的k对话
  • 总结对话


在这个例子中,我们将使用ConversationChain作为这个应用程序会话内存。

from langchain import ConversationChain
conversation = ConversationChain(llm=llm, verbose=True)
conversation.predict(input="Alice has a parrot.")
conversation.predict(input="Bob has two cats.")
conversation.predict(input="How many pets do Alice and Bob have?")


这将生成上图中的右手对话。如果没有ConversationChain来保持对话记忆,对话将看起来像上图中左侧的对话。
代理: 访问其他工具
尽管LLMs非常强大,但仍有一些局限性: 它们缺乏上下文信息 (例如,访问训练数据中未包含的特定知识),它们可能很快就会过时 (例如,GPT-4在2021年9月之前就接受了数据培训),并且他们不擅长数学。
因为LLM可能会对自己无法完成的任务产生幻觉,所以我们需要让他们访问补充工具,例如搜索 (例如Google搜索),计算器 (例如Python REPL或Wolfram Alpha) 和查找 (例如,维基百科)。此外,我们需要代理根据LLM的输出来决定使用哪些工具来完成任务。
请注意,某些LLM(例如google/flan-t5-xl) 不适用于以下示例,因为它们不遵循会话-反应-描述模板。对我来说,这是我在OpenAI上设置付费帐户并切换到OpenAI API的原因。
下面是一个例子,代理人首先用维基百科查找奥巴马的出生日期,然后用计算器计算他2022年的年龄。

# pip install wikipediafrom langchain.agents import load_toolsfrom langchain.agents import initialize_agentfrom langchain.agents import AgentType
tools = load_tools(["wikipedia", "llm-math"], llm=llm)agent = initialize_agent(tools,                         llm,                         agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,                         verbose=True)

agent.run("When was Barack Obama born? How old was he in 2022?")


图片

结果图片
总结
就在几个月前,我们所有人 (或至少我们大多数人) 都对ChatGPT的功能印象深刻。现在,像LangChain这样的新开发人员工具使我们能够在几个小时内在笔记本电脑上构建同样令人印象深刻的原型--这是一些真正令人兴奋的时刻!
LangChain是一个开源的Python库,它使任何可以编写代码的人都可以构建以LLM为动力的应用程序。该软件包为许多基础模型提供了通用接口,可以进行提示管理,并在撰写本文时通过代理充当其他组件 (如提示模板,其他LLM,外部数据和其他工具) 的中央接口。该库提供了比本文中提到的更多的功能。以目前的发展速度,这篇文章也可能在一个月内过时。
在撰写本文时,我注意到库和文档围绕OpenAI的API展开。尽管许多示例与开源基础模型google/flan-t5-xl一起使用,但我在两者之间选择了OpenAI API。尽管不是免费的,但在本文中尝试OpenAI API只花了我大约1美元。


原文标题:Getting Started with LangChain: A Beginner’s Guide to Building LLM-Powered Applications原文链接:https://towardsdatascience.com/getting-started-with-langchain-a-beginners-guide-to-building-llm-powered-applications-95fc8898732c


*博客内容为网友个人发布,仅代表博主个人观点,如有侵权请联系工作人员删除。

参与讨论
登录后参与讨论
推荐文章
最近访客
站长统计
×

Digikey let's do
· 2025年第1期限时报名开启,5月8日截止
· Digikey助力,提供一站式免费器件支持
· 跟大佬一起 【DIY 功率监测与控制系统】