Langchain知识分享及使用指南

释放双眼,带上耳机,听听看~!
本文分享了关于Langchain的知识,并提供了使用指南。介绍了Langchain的基本语法格式和如何使用prompt模板。还讲解了如何修改Open AI的LLM的参数以及如何使用记忆库来实现上下文记忆。最后介绍了Langchain的Chain功能及其重要性。

关于Langchain的知识,之前我已经根据官方文档结合了我的经验和理解写了中文版的Langhain文档,这次吴恩达老师的课程我也再次复习了一下(纯英文无中文翻译真的挺难受的),以下是我的笔记分享:

Model_prompt_parser

一上来就是Langchain的基本语法格式:

import os
import openai

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

def get_completion(prompt, model="gpt-3.5-turbo"):
    messages = [{"role": "user", "content": prompt}]
    response = openai.ChatCompletion.create(
        model=model,
        messages=messages,
        temperature=0, 
    )
    return response.choices[0].message["content"]
## 提问

get_completion("What is 1+1?")

然后介绍了Prompt模板

prompt = f"""Translate the text 
that is delimited by triple backticks 
into a style that is {style}.
text: ```{customer_email}```
"""

print(prompt)

为什么我们需要prompt模板:
因为prompt普遍都是很长而且有很多细节的,我们应该尽可能重复使用这些好的框架,只需要修改部分必要的细节即可

接着介绍了一下如何修改Open AI的LLM的几个影响回答的参数:

messages = prompt_template.format_messages(text=customer_review)
chat = ChatOpenAI(temperature=0.0)#这里的括号里面还可以添加其他修改参数的值
response = chat(messages)
print(response.content)

以及如何将得到的结果修改为python 的字典结构

Memory

众所不周知,OPEN AI 的API是不具备和chatgpt一样的上下文能力的,也就是我们通俗意义上理解的“记忆”能力。
Langchain知识分享及使用指南
但是我们可以通过Langchain来解决这个问题。

llm = ChatOpenAI(temperature=0.0)
memory = ConversationBufferMemory()#用了一个记忆库来记忆上下文
conversation = ConversationChain(
    llm=llm, 
    memory = memory,
    verbose=True
)

当然,不只是一个记忆库可以使用,课程中还介绍了好几种,用法大差不差,不多介绍了。

Chain

很明显,Langchain的chain是故事的主角,这节课主要介绍的就是Chain(链)。
Lanchain的主要思路就是通过链式调用各种API各种库实现为LLM赋能,实现更多的定制化功能。

先看一个简单的例子:

llm = ChatOpenAI(temperature=0.9)
prompt = ChatPromptTemplate.from_template(
    "What is the best name to describe 
    a company that makes {product}?"
)

chain = LLMChain(llm=llm, prompt=prompt)#这里就是将LLM和prompt链接起来了

product = "Queen Size Sheet Set"
chain.run(product)

接下来展示多次链式调用

from langchain.chains import SimpleSequentialChain
llm = ChatOpenAI(temperature=0.9)

# prompt template 1
first_prompt = ChatPromptTemplate.from_template(
    "What is the best name to describe 
    a company that makes {product}?"
)

# Chain 1
chain_one = LLMChain(llm=llm, prompt=first_prompt)

# prompt template 2
second_prompt = ChatPromptTemplate.from_template(
    "Write a 20 words description for the following 
    company:{company_name}"
)
# chain 2
chain_two = LLMChain(llm=llm, prompt=second_prompt)

# 将两个chain链接在一起
overall_simple_chain = SimpleSequentialChain(chains=[chain_one, chain_two],
                                             verbose=True
                                            )
overall_simple_chain.run(product)

接下来就是顺序调用链子
顾名思义,就是每条chain之间是有先后顺序的
Langchain知识分享及使用指南
下面是例子和代码(这里这个例子用来4条chain,先将文本翻译成英文——》将这段英文文本总结成一句话——》判断接下来的文本的特定语言——》将上面的总结翻译成第三步得到的特定的语言):

from langchain.chains import SequentialChain
llm = ChatOpenAI(temperature=0.9)

# prompt template 1: translate to english
first_prompt = ChatPromptTemplate.from_template(
    "Translate the following review to english:"
    "nn{Review}"
)
# chain 1: input= Review and output= English_Review
chain_one = LLMChain(llm=llm, prompt=first_prompt, 
                     output_key="English_Review"
                    )
                    
second_prompt = ChatPromptTemplate.from_template(
    "Can you summarize the following review in 1 sentence:"
    "nn{English_Review}"
)
# chain 2: input= English_Review and output= summary
chain_two = LLMChain(llm=llm, prompt=second_prompt, 
                     output_key="summary"
                    )
# prompt template 3: translate to english
third_prompt = ChatPromptTemplate.from_template(
    "What language is the following review:nn{Review}"
)
# chain 3: input= Review and output= language
chain_three = LLMChain(llm=llm, prompt=third_prompt,
                       output_key="language"
                      )

# prompt template 4: follow up message
fourth_prompt = ChatPromptTemplate.from_template(
    "Write a follow up response to the following "
    "summary in the specified language:"
    "nnSummary: {summary}nnLanguage: {language}"
)
# chain 4: input= summary, language and output= followup_message
chain_four = LLMChain(llm=llm, prompt=fourth_prompt,
                      output_key="followup_message"
                     )
# overall_chain: input= Review 
# and output= English_Review,summary, followup_message
overall_chain = SequentialChain(
    chains=[chain_one, chain_two, chain_three, chain_four],
    input_variables=["Review"],
    output_variables=["English_Review", "summary","followup_message"],
    verbose=True
)

之后还介绍了Router Chain,类似用多个prompt,然后根据input来选择prompt来回答。
代码太多就不展示了。

提问与回答

这节课主要展示的就是如何通过Langchain让LLM根据特定的内容回答问题。
其实也是chatpdf,chatdoc之类网站的实现原理。
来看下面的例子和代码:

file = 'OutdoorClothingCatalog_1000.csv'
loader = CSVLoader(file_path=file)
# 调用向量索引库来存储文件内容
from langchain.indexes import VectorstoreIndexCreator

index = VectorstoreIndexCreator(
    vectorstore_cls=DocArrayInMemorySearch
).from_loaders([loader])

query ="Please list all your shirts with sun protection 
in a table in markdown and summarize each one."

response = index.query(query)

display(Markdown(response))

这里解释一下我们如何存储内容:
因为LLM模型只能存储很少的信息,所以对于大文件我们需要用到一个向量索引库来存贮这些文件的内容,然后通过向量相关匹配来找到和提问对应的内容,LLM根据这特定的内容进行回答。
Langchain知识分享及使用指南

Evaluation

Evaluation是用来检测和评估我们的chain和agent质量的,
一般来说是比较难以评估的,两个原因:缺乏数据;缺乏指标
不过通过Langchain我们就能够解决上面的问题。

通过LangChainDataset寻找开源数据或者让LLM根据文件生成相关的数据

不用指标判断而通过人根据感觉分析或者通过LLM本身评估输出质量

本文的代码量大就不放上来了,有需要到课程网站上查阅。

Agent

我对于Agent的理解就是能够调用其他的API来加强LLM的能力,并且Agents 使用 LLMs 来确定采取哪些行动以及以何种顺序采取行动。
比如使用谷歌的API实现LLM的上网查阅信息的能力,通过使用计算机API来实现精准的计算。
下面是例子和代码:

llm = ChatOpenAI(temperature=0)
tools = load_tools(["llm-math","wikipedia"], llm=llm)
agent= initialize_agent(
    tools, 
    llm, 
    agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,
    handle_parsing_errors=True,
    verbose = True)

这是运行代码后内部发生的过程: Langchain知识分享及使用指南

我的学习后思考

吴恩达老师课程里面其实是不如Langchain官方文档全面的,包括很多例子也是照搬的。不过好的是提供了一个视频方式,能够让更多人参与进来,而且能够使用在线的notebook编辑也是方便了很多。不过还是希望下次能尽快把抄本放出来,不然英文听力很累的www
感谢吴恩达老师的无私付出和

本网站的内容主要来自互联网上的各种资源,仅供参考和信息分享之用,不代表本网站拥有相关版权或知识产权。如您认为内容侵犯您的权益,请联系我们,我们将尽快采取行动,包括删除或更正。
AI教程

百度发布大语言模型“文心一言”,助力企业创造最佳客户体验

2023-12-22 20:48:14

AI教程

大连海事大学自然语言处理NLTK使用实验

2023-12-22 20:59:14

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索