【LangChain系列 1】 LangChain初探

原文链接:【LangChain系列 1】LangChain初探https://mp.weixin.qq.com/s/9UpbM84LlsHOaMS7cbRfeQ

本文速读:

  • LangChain是什么

  • LangChain初探

    • 环境准备

    • LLMs

    • Prompt Templates

    • Output Parser

    • 第一个LLMChain应用

01 LangChain是什么


LangChain是一个大语言模型的应用开发框架,在LangChain在基础上,我们可以快速开发AI应用。

02 LangChain初探


环境准备

  • openai api key

注册一个openai开发者帐号,然后可以生成key,获取key来调用open ai的接口,调用接口会消耗费用,帐号中有免费的5美金可以使用。

  • python开发环境

可以使用conda,也可以直接使用python 3,我使用的是python 3.8.9版本。

  • 安装openai和langchain

pip install openaipip install langchain

LLMs

LangChain中有LLMs和ChatModels两种语言模型:

  • LLMs:输入一个字符串,然后返回一个字符串。

  • ChatModels:输入一连串Message,比如说一连串对话,以此为上下评文,然后输入一条Message。

两者的区别是:LLMs偏向于问与答,ChatModel更偏向于对话的场景。

Message包含content和role两个部分,LangChain根据role在不同分为四种Message:

  • HumanMessage:代表人类/用户的message。

  • AIMessage:代表AI的message。

  • SystemMessage:代表系统的message。

  • FunctionMessage:代表函数调用的message。

下面我们看一个简单的例子怎么使用LLMs和ChatModels。

1. 输入一个字符串

from langchain.llms import OpenAIfrom langchain.chat_models import ChatOpenAI

text = "What would be a good company name for a company that makes colorful socks?"

llm = OpenAI()chat_model = ChatOpenAI()
llm.predict(text)
chat_model.predict(text)

2. 输入一个Message

from langchain.llms import OpenAIfrom langchain.chat_models import ChatOpenAI

text = "What would be a good company name for a company that makes colorful socks?"
messages = [HumanMessage(content=text)]

llm = OpenAI()
chat_model = ChatOpenAI()

llm.predict_messages(messages)
chat_model.predict_messages(messages)

Prompt Templates

一般来讲,我们不会将用户的输入或者问题直接传递给LLM应用,而是将它放到一个固定的上下文中,方便LLM应用理解提出的问题,从而给出更准确的回答,这段上下文就是我们所说在prompt templates。

例如:

from langchain.prompts import PromptTemplate

prompt = PromptTemplate.from_template("What is a good name for a company that makes {product}?")
prompt.format(product="colorful socks")

prompt templates的作用就是把product这个变量抽离出来,我们可以根据需要赋予它不同的值,这样就更加灵活。

prompt templates除了可以用于字符串,它还可以用于Message,例如:

from langchain.prompts.chat import (
    ChatPromptTemplate,
    SystemMessagePromptTemplate,
    HumanMessagePromptTemplate)

template = "You are a helpful assistant that translates {input_language} to {output_language}."
system_message_prompt = SystemMessagePromptTemplate.from_template(template)human_template = "{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])

chat_prompt.format_messages(input_language="English", output_language="French", text="I love programming.")

上述chat_prompt相当于:

[    
    SystemMessage(content="You are a helpful assistant that translates English to French.", additional_kwargs={}),
    HumanMessage(content="I love programming.")
]

Output Parser

output parser的作用就是将LLMs的输出进行解析处理,最终返回给我们需要的格式,例如:

  • 将文本转换为json

  • 将Message转换为字符串

  • 将其它信息转换为字符串

下面这个例子就是将LLM返回的一个字符串转换为以逗号为分隔的列表。

from langchain.schema import BaseOutputParser

class CommaSeparatedListOutputParser(BaseOutputParser):
    """Parse the output of an LLM call to a comma-separated list."""


    def parse(self, text: str):
        """Parse the output of an LLM call."""
        return text.strip().split(", ")

CommaSeparatedListOutputParser().parse("hi, bye")

第一个LangChain应用

介绍完LangChain应用所需要的最基础的组件后,我们可以开启Hello World之旅了,开始写第一个最简单的LangChain应用。

from langchain.chat_models import ChatOpenAI
from langchain.prompts.chat import (
    ChatPromptTemplate,
    SystemMessagePromptTemplate,
    HumanMessagePromptTemplate,
)
from langchain.chains import LLMChain
from langchain.schema import BaseOutputParser

class CommaSeparatedListOutputParser(BaseOutputParser):
    """Parse the output of an LLM call to a comma-separated list."""


    def parse(self, text: str):
        """Parse the output of an LLM call."""
        return text.strip().split(", ")

template = """You are a helpful assistant who generates comma separated lists.
A user will pass in a category, and you should generate 5 objects in that category in a comma separated list.
ONLY return a comma separated list, and nothing more."""
system_message_prompt = SystemMessagePromptTemplate.from_template(template)
human_template = "{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)

chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])
chain = LLMChain(
    llm=ChatOpenAI(),
    prompt=chat_prompt,
    output_parser=CommaSeparatedListOutputParser()
)
chain.run("fruits")

以上就是本篇的全部内容,我们下一篇再见。

 更多最新文章,请关注公众号:大白爱爬山

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值