深入浅出 langchain 1. Prompt 与 Model

示例

从代码入手来看原理

python 复制代码
from langchain_core.output_parsers import StrOutputParser  
from langchain_core.prompts import ChatPromptTemplate  
from langchain_openai import ChatOpenAI  
  
prompt = ChatPromptTemplate.from_template("tell me a short joke about {topic}")  
model = ChatOpenAI(model="gpt-4")  
output_parser = StrOutputParser()  
  
chain = prompt | model | output_parser  
  
chain.invoke({"topic": "ice cream"})

chain = prompt | model | output_parser

|是 Unix 管道操作符, 将不同的组件链接到一起, 一组组件的输出作为下一组件的输入.

Prompt

prompt 是一个 BasePromptTemplate ,这意味着它接收一个模板变量的字典并生成一个 PromptValue 。一个 PromptValue 是一个完成提示的包装器,可以传递给 LLM (接受字符串作为输入)或 ChatModel (接受消息序列作为输入)。它可以与任何语言模型类型一起工作,因为它定义了生成 BaseMessage 和生成字符串的逻辑。

以下是 PromptValue 的输入

python 复制代码
prompt_value = prompt.invoke({"topic": "ice cream"})

prompt_value
# ChatPromptValue(messages=[HumanMessage(content='tell me a short joke about ice cream')])

prompt_value.to_messages()
# [HumanMessage(content='tell me a short joke about ice cream')]

prompt_value.to_string()
# 'Human: tell me a short joke about ice cream'

Model

然后将 PromptValue 传递给 model 。在这种情况下,我们的 model 是一个 ChatModel ,意味着它将输出一个 BaseMessage 。

python 复制代码
message = model.invoke(prompt_value)  

message
# AIMessage(content="Why don't ice creams ever get invited to parties?\n\nBecause they always bring a melt down!")

如果我们的 model 是一个 LLM ,它会输出一个字符串。

python 复制代码
from langchain_openai.llms import OpenAI  
  
llm = OpenAI(model="gpt-3.5-turbo-instruct")  
llm.invoke(prompt_value)

# '\n\nRobot: Why did the ice cream truck break down? Because it had a meltdown!'

Output parser

最后,我们将我们的 model 输出传递给 output_parser ,这是一个 BaseOutputParser ,它接受字符串或 BaseMessage 作为输入。这个 StrOutputParser 特别简单地将任何输入转换为字符串

python 复制代码
output_parser.invoke(message)

# "Why did the ice cream go to therapy? \n\nBecause it had too many toppings and couldn't find its cone-fidence!"

Summary

运行流程图如下:

我们将用户输入变成字典后, 传递给 PromptTemplate 包装成 PromptValue, 传递给 ChatModel 后, Model 给我们返回 ChatMessage, 再将其传递给 StrOutputParser, 最终解析成 String 类型

相关推荐
酒旅Agent开发实战几秒前
10000个MCP Server之后:生态繁荣还是碎片化?
人工智能·大模型·酒店预订·ai agent·mcp
javaDocker2 分钟前
授权、协议与提示注入:Personal Agent 的安全基线该抄哪几份作业
人工智能·安全·金融·架构
梦想出海-Phoebe3 分钟前
ChatGPT 支持人民币付款了吗?详解 OpenAI 多币种计费与支付限制
人工智能·chatgpt
启雀AI7 分钟前
演讲式 AI 陪练引擎设计:PPT 内容解析、翻页节奏感知与多模态评分的工程实现
人工智能·powerpoint·培训saas平台·企业lms·ai陪练
天空属于哈夫克313 分钟前
企业微信二次开发:外部群接 AI 客服,如何避免抢答和双回?
人工智能
FBI HackerHarry浩15 分钟前
Pytorch中 CPU tensor vs GPU tensor
人工智能·pytorch·python·深度学习
死磕音视频15 分钟前
ChatGPT Deep Research 入门:把复杂问题做成带出处的调研报告
人工智能·chatgpt·信息检索·deep research·调研方法
小草cys17 分钟前
图片一键转全矢量可编辑PPT——纯Python实现,零依赖,离线可用
人工智能·python·powerpoint
weixin_4166600721 分钟前
AI 生成的 Mermaid 流程图和 LaTeX 公式,怎么一起导出到 Word?
人工智能·word·流程图·豆包
xsd2024111823 分钟前
Compositor:8MB 开源 Photoshop 平替
人工智能