Skip to main content
您可以使用 LangSmith Python 和 TypeScript SDK 以编程方式管理提示。
此功能以前位于 langchainhub 包中,该包现已弃用。所有未来功能都将位于 langsmith 包中。

安装包

在 Python 中,您可以直接使用 LangSmith SDK(推荐,功能完整),或者通过 LangChain 包使用(仅限于推送和拉取提示)。 在 TypeScript 中,您必须使用 LangChain npm 包来拉取提示(它也允许推送)。对于所有其他功能,请使用 LangSmith 包。
pip install -U langsmith # version >= 0.1.99

配置环境变量

如果您已经将 LANGSMITH_API_KEY 设置为当前工作区的 LangSmith API 密钥,则可以跳过此步骤。 否则,请通过导航到 LangSmith 中的 Settings > API Keys > Create API Key 来获取工作区的 API 密钥。 设置您的环境变量。
export LANGSMITH_API_KEY="lsv2_..."
我们所称的“提示”以前被称为“仓库”,因此代码中任何对“仓库”的引用都指的是提示。

推送提示

要创建新提示或更新现有提示,您可以使用 push prompt 方法。
from langsmith import Client
from langchain_core.prompts import ChatPromptTemplate

client = Client()
prompt = ChatPromptTemplate.from_template("tell me a joke about {topic}")
url = client.push_prompt("joke-generator", object=prompt)
# url is a link to the prompt in the UI
print(url)
您也可以将提示作为提示和模型的 RunnableSequence 进行推送。这对于存储您希望与此提示一起使用的模型配置非常有用。提供商必须得到 Playground 的支持,请参阅支持的模型提供商
from langsmith import Client
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI

client = Client()
model = ChatOpenAI(model="gpt-5.4-mini")
prompt = ChatPromptTemplate.from_template("tell me a joke about {topic}")
chain = prompt | model
client.push_prompt("joke-generator-with-model", object=chain)

推送 StructuredPrompt

StructuredPrompt 将提示模板与输出模式相结合,确保模型以定义的结构返回数据。使用 StructuredPrompt.from_messages_and_schema(Python)或 StructuredPrompt.fromMessagesAndSchema(TypeScript)创建一个,然后像任何其他提示一样将其推送到中心。

不带模型

当您希望独立于任何模型配置存储模板和模式时,可以单独推送结构化提示。
from langsmith import Client
from langchain_core.prompts.structured import StructuredPrompt
from pydantic import BaseModel, Field

class ResponseSchema(BaseModel):
    positive_sentiment: bool = Field(description="Was the user sentiment positive?")

prompt = StructuredPrompt.from_messages_and_schema(
    [
        ("system", "Evaluate the sentiment of the following conversation."),
        ("human", "{conversation}"),
    ],
    schema=ResponseSchema.model_json_schema(),
)

client = Client()
url = client.push_prompt("sentiment-evaluator", object=prompt)
print(url)

带模型

将结构化提示作为带有模型的 RunnableSequence 推送,以在中心存储完整的管道,包括模型配置。
from langsmith import Client
from langchain_core.prompts.structured import StructuredPrompt
from langchain_openai import ChatOpenAI
from pydantic import BaseModel, Field

class ResponseSchema(BaseModel):
    positive_sentiment: bool = Field(description="Was the user sentiment positive?")

prompt = StructuredPrompt.from_messages_and_schema(
    [
        ("system", "Evaluate the sentiment of the following conversation."),
        ("human", "{conversation}"),
    ],
    schema=ResponseSchema.model_json_schema(),
)

model = ChatOpenAI(model="gpt-4o-mini")
chain = prompt | model

client = Client()
url = client.push_prompt("sentiment-evaluator-with-model", object=chain)
print(url)

拉取提示

要拉取提示,您可以使用 pull prompt 方法,该方法将提示作为 langchain PromptTemplate 返回。 要拉取私有提示,您不需要指定所有者句柄(但如果您设置了,也可以指定)。 要从 LangChain Hub 拉取公共提示,您需要指定提示作者的句柄。
from langsmith import Client
from langchain_openai import ChatOpenAI

client = Client()
prompt = client.pull_prompt("joke-generator")
model = ChatOpenAI(model="gpt-5.4-mini")
chain = prompt | model
chain.invoke({"topic": "cats"})
与推送提示类似,您也可以将提示作为提示和模型的 RunnableSequence 进行拉取。只需在拉取提示时指定 include_model。如果存储的提示包含模型,它将作为 RunnableSequence 返回。确保您为所使用的模型设置了正确的环境变量。
from langsmith import Client

client = Client()
chain = client.pull_prompt("joke-generator-with-model", include_model=True)
chain.invoke({"topic": "cats"})
拉取提示时,您还可以指定特定的提交哈希或提交标签来拉取特定版本的提示。
prompt = client.pull_prompt("joke-generator:12344e88")
要从 LangChain Hub 拉取公共提示,您需要指定提示作者的句柄。
prompt = client.pull_prompt("efriis/my-first-prompt")
对于拉取提示,如果您使用的是 Node.js 或支持动态导入的环境,我们建议使用 langchain/hub/node 入口点,因为它会自动处理与提示配置关联的模型的反序列化。如果您在非 Node 环境中,对于非 OpenAI 模型不支持 “includeModel”,您应该使用基础 langchain/hub 入口点。

提示缓存

LangSmith SDK 包含内置的内存提示缓存。启用后,LangSmith 会将拉取的提示缓存在内存中,从而减少常用提示的延迟和 API 调用。缓存使用一个全局单例实例,该实例在所有客户端之间共享,并在进程的生命周期内持续存在。它实现了 stale-while-revalidate 模式,确保您的应用程序始终获得快速响应,同时在后台保持提示的最新状态。 要求:
  • Python SDK:langsmith >= 0.7.0
  • TypeScript SDK:langsmith >= 0.5.0

默认行为

缓存默认启用。启用时,默认设置如下:
设置默认值描述
max_size100要缓存的最大提示数
ttl_seconds300(5 分钟)缓存提示被视为过期的时间
refresh_interval_seconds60检查过期提示并在后台刷新它们的频率
刷新时,全局缓存将使用请求给定提示的最后一个客户端来获取新数据。

使用缓存

默认情况下,所有客户端都使用全局提示缓存。无需配置:
from langsmith import Client
# Obtain a reference to the global cache just for logging metrics
from langsmith.prompt_cache import prompt_cache_singleton

# Caching is enabled by default using the global singleton
client = Client()

# First pull - fetches from API and caches
prompt = client.pull_prompt("joke-generator")

# Subsequent pulls - returns cached version instantly
prompt = client.pull_prompt("joke-generator")

# Check cache metrics
print(f"Cache hits: {prompt_cache_singleton.metrics.hits}")
print(f"Cache misses: {prompt_cache_singleton.metrics.misses}")
print(f"Hit rate: {prompt_cache_singleton.metrics.hit_rate:.1%}")

配置全局缓存

您可以配置所有客户端默认使用的全局提示缓存。当您希望在整个应用程序中自定义缓存行为时,这非常有用:
from langsmith import Client
from langsmith.prompt_cache import (
    configure_global_prompt_cache,
    prompt_cache_singleton,
)

# Configure global cache before creating any clients
configure_global_prompt_cache(
    max_size=200,  # Cache up to 200 prompts
    ttl_seconds=7200,  # Consider prompts stale after 2 hours
    refresh_interval_seconds=600,  # Check for stale prompts every 10 minutes
)

# All clients will use these settings
client1 = Client()
client2 = Client()

# Both clients share the same global cache with your custom settings
prompt1 = client1.pull_prompt("prompt-1")
prompt2 = client2.pull_prompt("prompt-2")

# Check global cache metrics
print(f"Global cache hits: {prompt_cache_singleton.metrics.hits}")
print(f"Global cache misses: {prompt_cache_singleton.metrics.misses}")

禁用缓存

要为特定客户端禁用缓存,请传递 disable_prompt_cache=True。您也可以全局配置最大大小为零:
from langsmith import Client

# Disable caching for this client
client = Client(disable_prompt_cache=True)

# Every pull will fetch from the API
prompt = client.pull_prompt("joke-generator")

跳过缓存

要绕过缓存并为单个请求从 API 获取最新提示,请使用 skip_cache 参数:
# Force a fresh fetch, ignoring any cached version
prompt = client.pull_prompt("joke-generator", skip_cache=True)
当您需要确保拥有最新版本的提示时(例如在 LangSmith UI 中进行更改后),这非常有用。

离线模式

对于网络连接有限或没有网络连接的环境,您可以预填充缓存并离线使用它。将 ttl_seconds 设置为 None(Python)或 null(TypeScript)以防止缓存条目过期并禁用后台刷新。 步骤 1:将提示导出到缓存文件(在线时)
from langsmith import Client
from langsmith.prompt_cache import prompt_cache_singleton

# Create client (caching is enabled by default)
client = Client()

# Pull the prompts you need
client.pull_prompt("prompt-1")
client.pull_prompt("prompt-2")
client.pull_prompt("prompt-3")

# Export cache to a file
prompt_cache_singleton.dump("prompts_cache.json")
步骤 2:在离线环境中加载缓存文件
from langsmith import Client
from langsmith.prompt_cache import (
    configure_global_prompt_cache,
    prompt_cache_singleton,
)

# Configure cache with infinite TTL (never expire, no background refresh)
configure_global_prompt_cache(ttl_seconds=None)

# Load the cache file
prompt_cache_singleton.load("prompts_cache.json")

# Create client (uses the loaded cache)
client = Client()

# Uses cached version without any API calls
prompt = client.pull_prompt("prompt-1")

缓存操作

缓存支持多种操作来管理缓存提示:
from langsmith import Client
from langsmith.prompt_cache import prompt_cache_singleton

client = Client()

# Invalidate a specific prompt from cache
prompt_cache_singleton.invalidate("joke-generator:latest")

# Clear all cached prompts
prompt_cache_singleton.clear()

# Reset metrics
prompt_cache_singleton.reset_metrics()

# Check if cache is running background refresh
# (only runs if ttl_seconds is not None)
if prompt_cache_singleton._refresh_thread is not None:
    print("Background refresh is active")

清理

您可以手动调用 stop() 来停止后台刷新任务:
prompt_cache_singleton.stop()
后台刷新任务仅在您首次在缓存中设置值时启动,并且仅在 ttl_seconds 不为 None 时启动。如果 ttl_secondsNone(离线模式),则不会创建后台任务。

不使用 LangChain 使用提示

如果您想将提示存储在 LangSmith 中,但直接使用模型提供商的 API,可以使用我们的转换方法。这些方法将您的提示转换为 OpenAI 或 Anthropic API 所需的有效负载。 这些转换方法依赖于 LangChain 集成包内部的逻辑,除了您选择的官方 SDK 之外,您还需要安装相应的包作为依赖项。以下是一些示例:

OpenAI

pip install -U langchain_openai
from openai import OpenAI
from langsmith.client import Client, convert_prompt_to_openai_format

# langsmith client
client = Client()
# openai client
oai_client = OpenAI()

# pull prompt and invoke to populate the variables
prompt = client.pull_prompt("joke-generator")
prompt_value = prompt.invoke({"topic": "cats"})
openai_payload = convert_prompt_to_openai_format(prompt_value)
openai_response = oai_client.chat.completions.create(**openai_payload)

Anthropic

pip install -U langchain_anthropic
from anthropic import Anthropic
from langsmith.client import Client, convert_prompt_to_anthropic_format

# langsmith client
client = Client()
# anthropic client
anthropic_client = Anthropic()

# pull prompt and invoke to populate the variables
prompt = client.pull_prompt("joke-generator")
prompt_value = prompt.invoke({"topic": "cats"})
anthropic_payload = convert_prompt_to_anthropic_format(prompt_value)
anthropic_response = anthropic_client.messages.create(**anthropic_payload)

列出、删除和点赞提示

您还可以使用 list promptsdelete promptlike promptunlike prompt 方法来列出、删除和点赞/取消点赞提示。有关这些方法的详细文档,请参阅 LangSmith SDK 客户端
# List all prompts in my workspace
prompts = client.list_prompts()

# List my private prompts that include "joke"
prompts = client.list_prompts(query="joke", is_public=False)

# Delete a prompt
client.delete_prompt("joke-generator")

# Like a prompt
client.like_prompt("efriis/my-first-prompt")

# Unlike a prompt
client.unlike_prompt("efriis/my-first-prompt")