使用 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": "中等"}
相关推荐
DreamLife☼43 分钟前
复杂Agent系统架构设计
系统架构·wpf·agent·组件·设计·构架·说明
镜舟科技1 小时前
从 DBA 经验到 Agent:镜舟如何构建生产级智能排障体系
数据库·agent·dba·skill·devops agent·mirrorship
武子康2 小时前
Seedream 5.0 Pro 进入 Vercel AI Gateway:图像生成开始网关化
人工智能·ai·chatgpt·gateway·agent·claude·harness
Boop_wu3 小时前
[LangGraph] 案例 2 : 支持搜索的智能代理系统
服务器·windows·python·langchain
JouYY3 小时前
大模型底层学习(四)- 混合精度训练与分布式训练
架构·llm·agent
测试开发Kevin4 小时前
DeepEval + Eval‑Harness 完整讲解(结合 Playwright UI 自动化例子)
人工智能·ai·langchain
智码看视界4 小时前
Apodex-1.1-mini 部署实测:Int4 量化 18GB 单卡跑通 Agent Team,35B 开源逼近 1T Kimi
开源·agent·模型量化·智能体·开源大模型·大模型本地部署·apodex
夏文强4 小时前
DeepSeek Harness 底层探秘:Cordis 元框架与「一切皆插件」的实现
人工智能·开源·大模型·agent·deepseek
岁月宁静5 小时前
四、《从零手撸 Agent》 — 流式输出:接住 AI “一个字一个字” 想出来的过程
python·agent