自然语言处理从入门到应用——LangChain:模型(Models)-[聊天模型(Chat Models):基础知识]

news/2025/3/19 13:54:10/

分类目录:《自然语言处理从入门到应用》总目录


聊天模型是语言模型的一种变体。虽然聊天模型在内部使用语言模型,但它们公开的接口略有不同。它们不是提供一个“输入文本,输出文本”的API,而是提供一个以“聊天消息”作为输入和输出的接口。 聊天模型的API还比较新,因此我们仍在确定正确的抽象层次。本问将介绍如何开始使用聊天模型,该接口是基于消息而不是原始文本构建的:

from langchain.chat_models import ChatOpenAI
from langchain import PromptTemplate, LLMChain
from langchain.prompts.chat import (ChatPromptTemplate,SystemMessagePromptTemplate,AIMessagePromptTemplate,HumanMessagePromptTemplate,
)
from langchain.schema import (AIMessage,HumanMessage,SystemMessage
)
chat = ChatOpenAI(temperature=0)

通过向聊天模型传递一个或多个消息,可以获取聊天完成的结果。响应将是一个消息。LangChain目前支持的消息类型有AIMessageHumanMessageSystemMessageChatMessage,其中ChatMessage接受一个任意的角色参数。大多数情况下,我们只需要处理HumanMessageAIMessageSystemMessage

chat([HumanMessage(content="Translate this sentence from English to French. I love programming.")])

输出:

AIMessage(content="J'aime programmer.", additional_kwargs={})

OpenAI的聊天模型支持多个消息作为输入。更多信息请参见这里。以下是向聊天模型发送系统消息和用户消息的示例:

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

输出:

AIMessage(content="J'aime programmer.", additional_kwargs={})

您还可以进一步生成多组消息的完成结果,使用generate方法实现。该方法将返回一个带有额外message参数的LLMResult

batch_messages = [[SystemMessage(content="You are a helpful assistant that translates English to French."),HumanMessage(content="I love programming.")],[SystemMessage(content="You are a helpful assistant that translates English to French."),HumanMessage(content="I love artificial intelligence.")],
]
result = chat.generate(batch_messages)
result

输出:

LLMResult(generations=[[ChatGeneration(text="J'aime programmer.", generation_info=None, message=AIMessage(content="J'aime programmer.", additional_kwargs={}))], [ChatGeneration(text="J'aime l'intelligence artificielle.", generation_info=None, message=AIMessage(content="J'aime l'intelligence artificielle.", additional_kwargs={}))]], llm_output={'token_usage': {'prompt_tokens': 57, 'completion_tokens': 20, 'total_tokens': 77}})

我们可以从LLMResult中获取诸如标记使用情况之类的信息:

result.llm_output

输出:

{'token_usage': {'prompt_tokens': 57,'completion_tokens': 20,'total_tokens': 77}}

PromptTemplates

我们可以使用模板来构建MessagePromptTemplate。我们可以从一个或多个MessagePromptTemplate构建一个ChatPromptTemplate。我们还可以使用ChatPromptTemplateformat_prompt方法,它将返回一个PromptValue,我们可以将其转换为字符串或消息对象,具体取决于我们是否希望将格式化后的值作为输入传递给LLM或Chat模型的输入。为了方便起见,模板上公开了一个from_template方法。如果您要使用此模板,代码如下所示:

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(chat_prompt.format_prompt(input_language="English", output_language="French", text="I love programming.").to_messages())

输出:

AIMessage(content="J'adore la programmation.", additional_kwargs={})

如果我们想直接更直接地构建MessagePromptTemplate,我们可以在外部创建一个PromptTemplate,然后将其传递进去,例如:

prompt=PromptTemplate(template="You are a helpful assistant that translates {input_language} to {output_language}.",input_variables=["input_language", "output_language"],
)
system_message_prompt = SystemMessagePromptTemplate(prompt=prompt)

LLMChain

我们可以以与以前非常相似的方式使用现有的LLMChain,即提供一个提示和一个模型:

chain = LLMChain(llm=chat, prompt=chat_prompt)
chain.run(input_language="English", output_language="French", text="I love programming.")

输出:

"J'adore la programmation."

Streaming

通过回调处理,ChatOpenAI支持流式处理。

from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
chat = ChatOpenAI(streaming=True, callbacks=[StreamingStdOutCallbackHandler()], temperature=0)
resp = chat([HumanMessage(content="Write me a song about sparkling water.")])

输出:

Verse 1:
Bubbles rising to the top
A refreshing drink that never stops
Clear and crisp, it's pure delight
A taste that's sure to exciteChorus:
Sparkling water, oh so fine
A drink that's always on my mind
With every sip, I feel alive
Sparkling water, you're my vibeVerse 2:
No sugar, no calories, just pure bliss
A drink that's hard to resist
It's the perfect way to quench my thirst
A drink that always comes firstChorus:
Sparkling water, oh so fine
A drink that's always on my mind
With every sip, I feel alive
Sparkling water, you're my vibeBridge:
From the mountains to the sea
Sparkling water, you're the key
To a healthy life, a happy soul
A drink that makes me feel wholeChorus:
Sparkling water, oh so fine
A drink that's always on my mind
With every sip, I feel alive
Sparkling water, you're my vibeOutro:
Sparkling water, you're the one
A drink that's always so much fun
I'll never let you go, my friend
Sparkling

参考文献:
[1] LangChain 🦜️🔗 中文网,跟着LangChain一起学LLM/GPT开发:https://www.langchain.com.cn/
[2] LangChain中文网 - LangChain 是一个用于开发由语言模型驱动的应用程序的框架:http://www.cnlangchain.com/


http://www.ppmy.cn/news/981018.html

相关文章

LLM 基础-transformers 库快速入门

一,Transformers 术语 1.1,token、tokenization 和 tokenizer1.2,input IDs1.3,attention mask1.4,bos_token、eop_token、pad_token、eos_token1.5,decoder models1.6,架构与参数二,Transformers 功能 API 概述三,快速上手 3.1,transformer 模型类别3.2,Pipeline&l…

强化学习价值函数方法笔记

在强化学习中,价值函数(Value Function)是一个核心概念,它用于衡量在不同状态或状态-动作对下,一个智能体(agent)可以获得的预期累积奖励。价值函数对于智能体做出决策和学习行为策略非常重要。…

8-js高级-7(理解js的事件循环)

一、前言 JS是单线程语言,但是又可以做到异步处理高并发请求,这时就用到了JavaScript的事件循环机制 理解事件循环,可以帮助我们准确分析和运用各种异步形式,减少代码的不确定性,在一些执行效率优化上也能有明确的思路…

Oralce数据库 手工重新创建控制文件

控制文件对于Oralce数据库的作用,就好像微软操作系统中注册表的作用一样。控制文件是一个比较小的二进制文件,记录着数据库的结构信息。如果数据库控制文件发生孙华的话,则Oracle将无法正常启动。通常情况下,在创建数据库时会自动…

没有编程基础,学习风变编程有困难吗?

许多初学者担心学习编程语言太难了。但是,大多数人可以通过时间、决心和正确的资源掌握编码。 许多因素决定了学习者找到编码的难度。一些语言优先考虑简单的命令,而另一些语言则使用密集的语法。有些语言比其他语言有更多的学习资源。在选择第一种编程…

UE4/5C++多线程插件制作(十、接口类和代理容器类的制作)

目录 封装 准备 MTPThreadInterface制作 作用域锁 然后我们开始重载操作符 operator<<:

怎么给图片去底色?这几个方法一定要知道

如果你是一位设计师或者是需要制作图片的人&#xff0c;那么你一定知道去除图片底色的重要性。无论是制作海报、广告、产品图片还是网站页面&#xff0c;去除图片底色可以让你的设计更加精细、美观、专业。在本文中&#xff0c;我们将介绍三种常见的图片去底色方法&#xff0c;…

数学学习总结

最近在准备一场考试&#xff0c;通过这几个月的学习发现数学思维还是有待建立&#xff0c;逻辑性、熟练度、思维想象力还是不足&#xff0c;本身数学基础不扎实&#xff0c;要通过这场考试&#xff0c;需要更进一步努力&#xff0c;复习一轮后&#xff0c;看视频、看老师讲解都…