使用 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": "中等"}
相关推荐
夫唯不争,故无尤也2 小时前
PostgreSQL + SQLAlchemy 快速搭一个能跑的 Agent 后端数据层
数据库·人工智能·postgresql·agent
Monly212 小时前
大模型:LangChain调用大语言模型
人工智能·语言模型·langchain
七牛云行业应用2 小时前
别瞎折腾了!4 步排查法,手把手教你搞定 OpenClaw Skills 各种安装报错
后端·openai·agent
软件聚导航2 小时前
OpenClaw实战应用场景-之有道龙虾
ai·agent·openclaw
Joy T2 小时前
【AI Agent入门】从RAG知识库到智能体架构:实质区分Coze、Dify与OpenClaw
人工智能·agent·dify·rag·coze·openclaw
Olafur_zbj2 小时前
【AI】深度解析OpenClaw智能体循环(Agentic Loop):底层运行机制、ReAct演进与多智能体协同架构
人工智能·react.js·架构·agent·openclaw
chaors3 小时前
Langchain入门到精通0x05:预制链
人工智能·langchain·ai编程
诚实可靠小郎君_dpc3 小时前
如何把特斯拉接入OpenClaw,让🦞做你的行车小助理
后端·agent
chaors3 小时前
Langchain入门到精通0x04:大模型怎么记忆?
人工智能·langchain·ai编程