Partial Prompt Templates in LangChain

https://python.langchain.com.cn/docs/modules/model_io/prompts/prompt_templates/partial

Partial Prompt Templates in LangChain

Partial prompt templates (called "partial" for short) are a useful feature in LangChain. Their core purpose is: fill in a subset of the required values first, then create a new prompt template that only needs the remaining values.

LangChain supports two main ways to use partial prompt templates. Below, we'll explain each method with simple language and the exact code/examples from the original source (no changes or omissions).

Method 1: Partial Formatting with String Values

When to use this?

This is for cases where you get some variables early (e.g., at the start of your code) and other variables later (e.g., from user input). Instead of waiting to pass all variables at once, you can fill in the early variables first.

Example 1: Use the .partial() method

Suppose we have a prompt template that needs two variables: foo and bar. We get foo first, then bar later.

Step 1: Import and create the original prompt template
python 复制代码
from langchain.prompts import PromptTemplate

# The template needs two variables: {foo} and {bar}
prompt = PromptTemplate(template="{foo}{bar}", input_variables=["foo", "bar"])
Step 2: Fill in the "early" variable (foo) with .partial()

This creates a new partial prompt template that only needs bar now.

python 复制代码
partial_prompt = prompt.partial(foo="foo")  # Fill in {foo} with the string "foo"
Step 3: Fill in the remaining variable (bar)

Use .format() to pass the remaining variable (bar):

python 复制代码
print(partial_prompt.format(bar="baz"))  # Pass {bar} with "baz"
Output
复制代码
foobaz

Example 2: Initialize with partial_variables

You can also fill in the "early" variable when creating the prompt template (instead of using .partial() later).

Code
python 复制代码
# input_variables only lists the remaining variable: {bar}
# partial_variables fills in {foo} upfront
prompt = PromptTemplate(
    template="{foo}{bar}", 
    input_variables=["bar"],  # Only need {bar} later
    partial_variables={"foo": "foo"}  # Fill {foo} with "foo" now
)

# Only pass {bar} to format()
print(prompt.format(bar="baz"))
Output
复制代码
foobaz

Method 2: Partial Formatting with Functions

When to use this?

This is for cases where a variable needs to be automatically fetched in the same way every time (e.g., current date/time). You don't want to hardcode it, and you don't want to pass it manually every time---so you use a function to get its value.

Example: Get current date automatically

Suppose we have a prompt template that needs two variables: adjective (from user input) and date (current date, fetched automatically).

Step 1: Define a function to get the value

First, create a function that returns the current date as a string:

python 复制代码
from datetime import datetime

def _get_datetime():
    now = datetime.now()  # Get current time
    return now.strftime("%m/%d/%Y, %H:%M:%S")  # Format as "month/day/year, hour:minute:second"
Example 1: Use the .partial() method
Step 1: Create the original prompt template
python 复制代码
prompt = PromptTemplate(
    template="Tell me a {adjective} joke about the day {date}", 
    input_variables=["adjective", "date"]  # Needs {adjective} and {date}
)

Use .partial() to set date to the result of _get_datetime() (note: we pass the function itself , not its result---no parentheses () after the function name):

python 复制代码
partial_prompt = prompt.partial(date=_get_datetime)
Step 3: Fill in the remaining variable (adjective)
python 复制代码
print(partial_prompt.format(adjective="funny"))
Output
复制代码
Tell me a funny joke about the day 02/27/2023, 22:15:16  # Date matches when you run the code
Example 2: Initialize with partial_variables

This is more common for function-based partialing (since the function runs automatically when needed).

Code
python 复制代码
prompt = PromptTemplate(
    template="Tell me a {adjective} joke about the day {date}", 
    input_variables=["adjective"],  # Only need {adjective} later
    partial_variables={"date": _get_datetime}  # Link {date} to the function
)

# Only pass {adjective} to format()
print(prompt.format(adjective="funny"))
Output
复制代码
Tell me a funny joke about the day 02/27/2023, 22:15:16  # Date matches when you run the code
相关推荐
UIUV2 小时前
RAG技术学习笔记(含实操解析)
javascript·langchain·llm
神秘的猪头8 小时前
🚀 拒绝“一本正经胡说八道”!手把手带你用 LangChain 实现 RAG,打造你的专属 AI 知识库
langchain·llm·openai
栀秋6668 小时前
重塑 AI 交互边界:基于 LangChain 与 MCP 协议的全栈实践
langchain·llm·mcp
YuMiao8 小时前
gstatic连接问题导致Google Gemini / Studio页面乱码或图标缺失问题
服务器·网络协议
大模型真好玩9 小时前
LangChain DeepAgents 速通指南(三)—— 让Agent告别混乱:Tool Selector与Todo List中间件解析
人工智能·langchain·trae
是一碗螺丝粉1 天前
LangChain 链(Chains)完全指南:从线性流程到智能路由
前端·langchain·aigc
前端付豪1 天前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
神秘的猪头1 天前
🔌 给 AI 装上“三头六臂”!实战大模型接入第三方 MCP 全攻略
langchain·llm·mcp
前端付豪2 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
神秘的猪头2 天前
🔌 把 MCP 装进大脑!手把手带你构建能“热插拔”工具的 AI Agent
langchain·llm·mcp