使用 langchain 的 PromptTemplate 处理多变量提示词

使用 langchain 的 PromptTemplate 处理多变量提示词

flyfish

在使用大模型时,我们经常需要构建包含变量的提示词,例如 "给我讲一个关于{topic}的故事"。 LangChain 提供的 PromptTemplate 正好解决这个问题。

一、PromptTemplate 基本概念

PromptTemplate 是 LangChain 中的一个组件,用于创建可重用的提示词模板,支持变量替换。

二、实现

1. 基本用法

使用 PromptTemplate.from_template 方法创建模板是最常见的方式:

python 复制代码
from langchain.prompts import PromptTemplate

# 创建模板
template = PromptTemplate.from_template("请写一段关于{topic}的简短介绍")

# 格式化模板
prompt = template.format(topic="人工智能")
print(prompt)  # 输出:请写一段关于人工智能的简短介绍

2. 多变量处理

PromptTemplate 可以轻松处理多个变量:

python 复制代码
template = PromptTemplate.from_template("写一个{style}风格的小故事,主角是{character},场景在{place}")

prompt = template.format(
    style="温馨",
    character="小猫",
    place="公园"
)
print(prompt)  # 输出:写一个温馨风格的小故事,主角是小猫,场景在公园

三、应用示例

下面是一个完整的示例,展示如何使用 PromptTemplate 处理多变量提示词并发送到 VLLM 服务:

1. 完整代码

python 复制代码
import requests
import json
from langchain.prompts import PromptTemplate
from typing import Optional, Dict, Any

# -------------------------- 核心配置项 --------------------------
VLLM_SERVER_URL = "http://localhost:8000/v1/chat/completions"  # VLLM服务地址
MAX_TOKENS = 1024  # 生成最大token数
TEMPERATURE = 0.7  # 生成温度
MODEL_NAME = "Qwen3-VL-30B-A3B-Instruct-FP8"  # 服务端加载的模型名
# -------------------------------------------------------------

def process_prompt_with_variables(prompt: str, variables: Dict[str, Any]) -> str:
    """
    功能:使用 PromptTemplate 处理包含多变量的提示词
    """
    try:
        # 创建提示词模板并格式化多变量
        template = PromptTemplate.from_template(prompt)
        processed_prompt = template.format(**variables)
        print(f"处理后的完整提示词:\n{processed_prompt}\n")
        return processed_prompt
    except Exception as e:
        print(f"提示词变量处理失败:{str(e)},使用原始提示词")
        return prompt

def send_vllm_request(prompt: str, variables: Optional[Dict[str, Any]] = None) -> Optional[str]:
    """
    功能:向 VLLM 服务发送请求(仅文本+多变量)
    """
    # 第一步:处理提示词中的多变量
    if variables:
        prompt = process_prompt_with_variables(prompt, variables)
    
    # 第二步:构建 VLLM 标准请求体
    payload = {
        "model": MODEL_NAME,
        "messages": [{"role": "user", "content": prompt}],  # 最简对话格式
        "max_tokens": MAX_TOKENS,
        "temperature": TEMPERATURE,
        "stream": False  # 非流式输出
    }

    # 第三步:发送请求并解析响应
    try:
        response = requests.post(
            url=VLLM_SERVER_URL,
            headers={"Content-Type": "application/json"},
            data=json.dumps(payload),
            timeout=120  # 适配大模型推理耗时
        )
        response.raise_for_status()  # 捕获HTTP错误
        
        # 提取模型回复
        result = response.json()
        assistant_reply = result["choices"][0]["message"]["content"]
        return assistant_reply
    except requests.exceptions.ConnectionError:
        print("无法连接到VLLM服务,请检查服务是否启动/地址是否正确")
    except Exception as e:
        print(f"请求失败:{str(e)}")
    return None

def main():
    """
    演示 PromptTemplate 多变量的使用示例
    """
    # 示例1:单个变量
    print("===== 示例1:单个变量 =====")
    single_var_prompt = "请写一段关于{topic}的简短介绍(100字以内)"
    single_variables = {"topic": "人工智能"}
    reply1 = send_vllm_request(single_var_prompt, single_variables)
    print(f"模型回复:\n{reply1}\n")

    # 示例2:多个变量
    print("===== 示例2:多个变量 =====")
    multi_var_prompt = "写一个{style}风格的小故事,主角是{character},场景在{place}"
    multi_variables = {
        "style": "温馨",
        "character": "小猫",
        "place": "公园"
    }
    reply2 = send_vllm_request(multi_var_prompt, multi_variables)
    print(f"模型回复:\n{reply2}\n")

if __name__ == "__main__":
    main()

四、其他例子

python 复制代码
# 生成产品描述
template = "为{product}写一段吸引人的产品描述,突出其{feature}特点"
variables = {"product": "智能手表", "feature": "健康监测"}
python 复制代码
# 个性化邮件回复
template = "亲爱的{name},感谢您对我们{service}的关注,{content}"
variables = {"name": "张先生", "service": "会员服务", "content": "我们将为您提供专属优惠"}
python 复制代码
# 生成练习题
template = "生成一道关于{topic}的{difficulty}难度的练习题,包含答案"
variables = {"topic": "数学", "difficulty": "中等"}
相关推荐
草莓熊Lotso1 小时前
Vibe Coding 时代:LangChain 与 LangGraph 全链路解析
linux·运维·服务器·数据库·人工智能·mysql·langchain
Old Uncle Tom7 小时前
OpenClaw 记忆系统 -- 记忆预加载
java·数据结构·算法·agent
深海鱼在掘金7 小时前
深入浅出 LangChain —— 第三章:模型抽象层
人工智能·langchain·agent
KaneLogger7 小时前
三省六部 Agent 这条路不通
agent·ai编程
深海鱼在掘金8 小时前
深入浅出 LangChain —— 第二章:环境搭建与快速上手
人工智能·typescript·langchain
薛定谔的猫3698 小时前
LLM Agents: 从大语言模型到自主智能体的演进与架构解析
ai·llm·agent·machine learning·architecture
Cder13 小时前
用 React + Ink 在终端里「优雅搜索」:开源 CLI 设计与非交互模式实践
前端·agent
熊猫钓鱼>_>13 小时前
当“虾”遇上“马”:QClaw 融合 Hermes 背后的智能体进化论
人工智能·ai·腾讯云·agent·openclaw·qclaw·hermes
猫头虎14 小时前
如何搭建 24 小时 AI 直播平台:魔珐星云数字人打造无人值守 “AI 销冠” 全流程实战教程
人工智能·langchain·开源·prompt·aigc·embedding·agi
Flittly14 小时前
【LangGraph新手村系列】(1)LangGraph 入门:StateGraph 与带记忆的 ReAct 循环
python·langchain