一、LangChain基本概念
LangChain 是一个专为大型语言模型(LLM)设计的应用程序开发框架,提供了一套工具和接口,使开发者能够轻松将 LLM 集成到各种应用程序中,利用其强大的语言理解和生成能力。它优化了提示管理、内存保持和索引等关键功能,并能够轻松管理与语言模型的交互,链接多个组件,同时集成额外的资源,如 API 和数据库。
1.LangChain基本板块
模型(Models) 提示(Prompts) 内存(Memory)
索引(Indexes) 链(Chains) 代理(Agents) 评估
注:本周以模型及提示实验为主
2.LangChain的分类
1.LLM(大型语言模型):这些模型将文本字符串作为输入并返回文本字符串作为输出。它们是许多语言模型应用程序的支柱。
2.聊天模型( Chat Model):聊天模型由语言模型支持,但具有更结构化的 API。他们将聊天消息列表作为输入并返回聊天消息。这使得管理对话历史记录和维护上下文变得容易。
3.文本嵌入模型(Text Embedding Models):这些模型将文本作为输入并返回表示文本嵌入的浮点列表。这些嵌入可用于文档检索、聚类和相似性比较等任务。
二、使用API调用模型
1.采用阿里云百炼获取API
灵积已停止开通,直接使用百炼
开通百炼后,申请API,并将API放到环境配置中(直接使用模型的测试代码可能会失败)
from openai import OpenAI
import os
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", # 填写DashScope服务的base_url
)
2.实现单次问答
(1)多个模型可免费使用一个月,部分模型限时免费,这里选择了通义千问2.5-1.5B,进行测试
def get_completion(prompt, model="qwen2.5-1.5b-instruct"):
messages =[{"role":"user","content":prompt}]
response = client.chat.completions.create(
model=model,
messages=messages,
temperature=0
)
return response.choices[0].message.content
得到下面结果
(2)改变文段风格
给出原文段以及想要改变的风格
test_text="在郁郁葱葱的森林中,各种动物和谐共生。松鼠在树枝间灵巧地跳跃,寻找坚果,\
而红狐狸则悄悄地穿行在灌木丛中,捕捉猎物。鸟儿在高空中歌唱,奏响大自然的乐章,溪\
水轻轻流淌,仿佛在为这片宁静的乐园伴奏。每一种生命都在这里扮演着独特的角色,构成\
了这个生态系统的终极和谐美。"
style="""简单易懂,口语化的"""
使用"f"字符串指定和说明提示,形成一个提示。大概意思是将文本翻译为style的样式
prompt =f"""Translate the text that is delimited \
by triple backticksinto a style that is {style}.text:'''{test_text}'''"""
调用上面的函数,得到改变风格的文段
response = get_completion(prompt)
得到返回的结果,可以看到文段已经改变了风格,更加的口语化。
3.导入LangChain,使用提示模版
(1)为什么要使用提示模版
当我们构建复杂应用程序时,提示可能会很长且详细。提示模版是一种较好的抽象,可以在需要时进行重用提示。使用LangChain的内置提示可以快速使应用程序运行,而无需设计自己的提示。
(2)简单实践
仍然使用前面的qwen2.5-1.5b-instruct模型
from langchain.chat_models import ChatOpenAI
chat = ChatOpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", # 填写DashScope服务的base_url
model="qwen2.5-1.5b-instruct",
temperature=0.0
)
ChatPromptTemplate
是一个提示模板类,用于构建对话模型的输入结构。我们可以用它来定义对话中不同角色的对话模式。使用提示模版(区别于前面的f字符串)生成提示,查看可以发现,它已经发现提示有两个待输入项
创建test_message生成完整提示,传递给大语言模型得到返回结果。查看了test_message类型可以发现是一个列表
test_message = prompt_template.format_messages(
style=style,
text=test_text
)
test_message列表的第一个元素就是我们所设置的完整的提示
调用chat,得到改变风格的文段。
(3)使用LangChain输出解析器
但当使用LLM构建一个复制应用程序时,一般会指示它以某种特定格式输出,比如特定关键词。比如“Thought”,“Action”,“Observe”等,那么这个提示可以与一个解析器结合提取出用这些特定关键词标记的文本。这样一来,就可以很好地描象地指定LLM的输入。然后让解析器正确地解释LLM给出的输出。
给出一个案例,客户对于吹风机的售后评价,已经我们尝试获取JSON的模版。将客户的评价作为输入,提取是三个字段如下,将输出格式化为JSON
customer_review="""This leaf blower is pretty amazing.\
It has four settings:candle blower,gentle breeze, windy city, \
and tornado.It arrived in two days, \
just in time for my wife's anniversary present.\
I think my wife liked it so much she was speechless.\
So far I've been the only one using it, \
and I've been using it every other morning to clear the leaves on our lawn.\
It's slightly more expensive than the other leaf blowers outthere, \
but I think it's worth it for the extra features."""
review_template = """For the following text,\
extract the following information:
gift: Was the item purchased as a gift for someone else? Answer True, False or unknown.
delivery days: How many days did it take for the product to arrive?If this imformation is not available, answer unknown.
price_value: Extract any sentences about the value or price, and output them as a comma separated string.
Format the output as JSON with the following keys:
gift
delivery_days
price_value
text:{text}"""
from langchain.prompts import ChatPromptTemplate
prompt_template = ChatPromptTemplate.from_template(review_template)
print(prompt_template)
查看输出,这个就是提示模版
调用API,打印出相应
messages=prompt_template.format_messages(text = customer_review)
chat = ChatOpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
model="qwen2.5-1.5b-instruct",
temperature=0.0
)
response=chat(messages)
print(response.content)
输出一个我们定义好的特殊格式,需要注意的是这个返回虽然看起来像JSON,但其实是一个字符串,而不是一个Python字典。
这样子是没有办法从某个键中获取内容的,所以修改如下
from langchain.output_parsers import ResponseSchema
from langchain.output_parsers import StructuredOutputParser
#然后我将通过指定这些返口的JSON的格式规范告诉LangChain希望它解析什么
gift_schema = ResponseSchema(name="gift",description="Was the item purchased as a gift for someone else? Answer True, False or unknown.")
delivery_days_schema = ResponseSchema(name="delivery_days",description="How many days did it take for the product to arrive?If this imformation is not available, answer unknown.")
price_value_schema = ResponseSchema(name="price_value",description="Extract any sentences about the value or price, and output them as a comma separated string.")
#将这些格式放到一个列表中
response_schemas=[gift_schema,delivery_days_schema,price_value_schema]
#初始化一个输出解析器并获取关于如何使用它的格式,在后续处理数据时遵循相应的格式规范。
output_parser = StructuredOutputParser(response_schemas=response_schemas)
format_instructions = output_parser.get_format_instructions()
#形成新的review_template
review_template2 = """For the following text,extract the following information:
gift: Was the item purchased as a gift for someone else? Answer True, False or unknown.
delivery days: How many days did it take for the product to arrive?If this imformation is not available,answer unknown.
price_value: Extract any sentences about the value or price, and output them as a comma separated string.
text:{text}
{format_instructions}
"""
#从review_template创建新的提示并传递给模型
prompt = ChatPromptTemplate.from_template(template=review_template2)
messages = prompt.format_messages(
text = customer_review,
format_instructions = format_instructions
)
#使用之前创建的output_parser就可以解析出一个output_dist
response = chat(messages)
output_dist = output_parser.parse(response.content)
output_dist
得到这样子的输出,这个时候它的类型已经改变成为一个字典了(可以通过代码type查看)
也可以直接根据字典来获取信息,比如获取天数。
学习及案例来源:【(超爽中英!) 2024公认最好的【吴恩达LangChain+RAG】教程!更适合中国宝宝体质,全程干货无废话,学完成为AGI大佬!(附课件+代码)】https://www.bilibili.com/video/BV1TJ4zemETf?p=2&vd_source=700d6f5d63bc66b4cbe7ea5a66d2a824