423 字
2 分钟
LangChain.js学习笔记第三课
结构化提示词
在跟各种聊天模型交互的时候,在构建聊天信息时,不仅仅只包含了上下文中的文本内容,也需要与每条消息关联的角色信息。
为了更方便的构建和处理这种结构化的聊天消息,LangChain提供了专门的结构化提示词模板系统,来帮助我们方便的构造这类信息
| 类名 | 用途 |
|---|---|
ChartPromptTemplate | 构造整个多轮提示词结构 |
SystemMessagePromptTemplate | 设置系统规则/行为模式 |
HumanMassagePromptTemplate | 模拟用户输入 |
AIMessagePromptTemplate | 模拟模型输入(上下文中使用) |
角色概念对LLM理解和构建整个对话流程非常重要,相同的内容由不同的role发送出来的意义是不同的
system角色的消息通常用于设置对话上下文或指定模型采取特定的行为模式。这些消息不会直接显示在对话中,他们对模型有着指导作用。
user角色代表真实用户在对话中的发言。
assistant角色的消息代表AI模型的回复。
快速上手
import { SystemMessagePromptTemplate, HumanMessagePromptTemplate, ChatPromptTemplate } from '@langchain/core/prompts'import { ChatOllama } from "@langchain/ollama"
const chatOllama = new ChatOllama({ model: "llama3.2", stream: true})
// 构建系统提示词const systemPrompt = await SystemMessagePromptTemplate.fromTemplate("你是一位中国的专业导游,请用中文向游客介绍中国某个地区的特产 ")
// 构建用户提示词const userPrompt = await HumanMessagePromptTemplate.fromTemplate("我想问:{question}")
// 组合上面的两个提示词const promptTemplate = await ChatPromptTemplate.fromMessages([systemPrompt, userPrompt])
// 进行格式化const pormpt = await promptTemplate.formatMessages({ question: "广西的特产有哪些"})
const res = await chatOllama.stream(pormpt)
for await (const chunk of res) { process.stdout.write(chunk.content)} LangChain.js学习笔记第三课
https://mizuki.mysqil.com/posts/langchainlession3/ 部分信息可能已经过时