LangChain框架(二)---- 提示词模板

提示词模板

FewShotPromptTemplate/PromptTemplate
复制代码
FewShotPromptTemplate(
    examples=None,example_prompt=None,
    prefix=None,
    suffix=None,
    input_variables=None
)

参数:

  • examples:示例数据,list,内套字典
  • example_prompt:示例数据的提示词模板
  • prefix:组装提示词,示例数据前内容
  • suffix:组装提示词,示例数据后内容
  • input_variables:列表,注入的变量列表

实例

复制代码
from langchain_core.prompts import PromptTemplate,FewShotPromptTemplate
from langchain_community.llms.tongyi import Tongyi

# 示例的模板
example_template = PromptTemplate.from_template("单词:{word}, 反义词: {antonym}")

# 示例的动态数据注入 要求是list内部套字典
examples_data = [
    {"word": "大", "antonym": "小"},
    {"word": "高", "antonym": "低"},
]

FewShot_Prompt = FewShotPromptTemplate(
    example_prompt = example_template,      #示例数据模板
    examples = examples_data,               #示例数据(用于动态注入)
    prefix = "告诉我单词的反义词,我提供如下示例", #示例前缀
    suffix = "基于前面的内容回答我,{input}的反义词",  #示例后缀
    input_variables=['input']
)

prompt_value = FewShot_Prompt.invoke(input={"input": "左"}).to_string()
print(prompt_value)

model = Tongyi(model="qwen-max")
print(model.invoke(input=prompt_value))

程序运行结果

复制代码
D:\Programs\Python\Python314\python.exe E:\Python\LLM实例\LangChain简单使用\FewShot提示词模板.py 
D:\Programs\Python\Python314\Lib\site-packages\langchain_core\_api\deprecation.py:25: UserWarning: Core Pydantic V1 functionality isn't compatible with Python 3.14 or greater.
  from pydantic.v1.fields import FieldInfo as FieldInfoV1
告诉我单词的反义词,我提供如下示例

单词:大, 反义词: 小

单词:高, 反义词: 低

基于前面的内容回答我,左的反义词
左的反义词是右。

进程已结束,退出代码为 0
ChatPromptTemplate

支持注入任意数量的历史会话信息

历史会话信息并非静态的,而是随着对话的进行不断的积攒的,动态的

实例如下

复制代码
from langchain_core.prompts import ChatPromptTemplate,MessagesPlaceholder
from langchain_community.chat_models.tongyi import ChatTongyi

chat_prompt_template = ChatPromptTemplate.from_messages(
    [
        ("system","你是一个诗人,你可以作诗"),
        MessagesPlaceholder("history_message"),
        ("human","很好,再来一首吧"),
    ]
)

history_date = [
    ("human", "你来写一个唐诗"),
    ("ai", "白日依山尽,黄河入海流。欲穷千里目,更上一层楼"),
    ("human" , "做的不错,再来一首吧"),
    ("ai", "千山鸟飞绝,万径人踪灭。孤舟蓑笠翁,独钓寒江雪")
]

# StringPromptValue 类对象
prompt_text_value = chat_prompt_template.invoke({"history_message": history_date}).to_string()
print(prompt_text_value)

model = ChatTongyi(model="qwen2.5-vl-3b-instruct")
res = model.invoke(prompt_text_value)
print(res.content)

实例运行效果

相关推荐
右耳朵猫AI21 分钟前
Python周刊2026W38 | 标准流编码修复、PEP 845/846 草案、解析器提速 10%、集合字典二次复杂度
python·ai·数据科学
微软技术分享24 分钟前
大模型网络结构:模型接口测试用例参考
python
Bruce_Liuxiaowei2 小时前
Python 实例赋值遮蔽类属性:一个从不报错的静默陷阱
开发语言·python·语法糖
做运维的阿瑞2 小时前
Python 标准库汇总:分类速览与常用模块清单
linux·运维·python
why-geo2 小时前
Hermes Agent 与 Python 的会产生什么样的碰撞
人工智能·python·ai编程
正经教主2 小时前
【FDE系列】阶段2:Day 29:FastAPI 进阶 — Pydantic 模型与完整 CRUD 实战
人工智能·python·fde
gCode Teacher 格码致知2 小时前
Pandas教学-6:coerce详解
python·pandas
梦在远山后2 小时前
Electron 与 FastAPI 如何完成流式 Agent 对话
python·langchain·agent
大衛說2 小时前
12 · 文件 I/O 与序列化
python
小静AI工程实验室2 小时前
Python 爬虫中文乱码排查:严格解码、UTF-8 BOM 与 JSON 转义的 12 项实验
字符编码·爬虫·python