Skip to content
LangSmith 文档版本 跟随上游 源快照 7a1b17a2 更新于 2026-10-18

以编程方式管理提示

你可以用 LangSmith Python、TypeScript 和 Java SDK 以编程方式管理提示。

NOTE

此前这个功能位于 langchainhub 包中,该包现已弃用。未来的所有功能都将位于 langsmith 包中。

安装软件包

在 Python 中,你可以直接使用 LangSmith SDK(推荐,完整功能),也可以通过 LangChain 包使用(限于推送和拉取提示)。

在 TypeScript 中,你必须用 LangChain npm 包来拉取提示(它也允许推送)。对所有其他功能,使用 LangSmith 包。

bash
pip install -U langsmith # version >= 0.1.99
bash
uv add langsmith  # version >= 0.1.99
bash
yarn add langsmith langchain # langsmith version >= 0.1.99 and langchain version >= 0.2.14
kotlin
implementation("com.langchain.smith:langsmith-java:0.1.0-beta.4")

配置环境变量

如果你已经把 LANGSMITH_API_KEY 设为你当前工作区从 LangSmith 得到的 API 密钥,可以跳过这一步。

否则,通过在 LangSmith 中导航到 Settings > API Keys > Create API Key 获取一个你工作区的 API 密钥。

设置你的环境变量。

bash
export LANGSMITH_API_KEY="lsv2_..."

NOTE

我们所称的"提示"以前叫"repo",因此代码中对"repo"的任何引用都是指一个提示。

推送一个提示

要创建一个新提示或更新一个现有提示,你可以用 push prompt 方法。

python
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)
python
from langchain_classic import hub as prompts
from langchain_core.prompts import ChatPromptTemplate

prompt = ChatPromptTemplate.from_template("tell me a joke about {topic}")
url = prompts.push("joke-generator", prompt)
# url is a link to the prompt in the UI
print(url)
typescript
import * as hub from "langchain/hub";
import { ChatPromptTemplate } from "@langchain/core/prompts";

const prompt = ChatPromptTemplate.fromTemplate("tell me a joke about {topic}");
const url = hub.push("joke-generator", {
  object: prompt,
});
// url is a link to the prompt in the UI
console.log(url);
java
import com.langchain.smith.client.LangsmithClient;
import com.langchain.smith.client.okhttp.LangsmithOkHttpClient;
import com.langchain.smith.core.JsonValue;
import com.langchain.smith.models.commits.CommitCreateParams;
import com.langchain.smith.models.repos.RepoCreateParams;
import java.util.List;
import java.util.Map;

LangsmithClient client = LangsmithOkHttpClient.fromEnv();

client.repos().create(
    RepoCreateParams.builder()
        .repoHandle("joke-generator")
        .isPublic(false)
        .build()
);

Map<String, Object> manifest = Map.of(
    "lc", 1,
    "type", "constructor",
    "id", List.of("langchain_core", "prompts", "prompt", "PromptTemplate"),
    "kwargs", Map.of(
        "template", "tell me a joke about {topic}",
        "input_variables", List.of("topic")
    )
);

client.commits().create(
    CommitCreateParams.builder()
        .owner("-")
        .repo("joke-generator")
        .manifest(JsonValue.from(manifest))
        .build()
);

你也可以把一个提示和模型的 RunnableSequence 作为提示推送。这对存储你想与该提示一起使用的模型配置很有用。提供商必须被 Playground 支持,见受支持的模型提供商。

python
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)
python
from langchain_classic import hub as prompts
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI

model = ChatOpenAI(model="gpt-5.4-mini")
prompt = ChatPromptTemplate.from_template("tell me a joke about {topic}")
chain = prompt | model
url = prompts.push("joke-generator-with-model", chain)
# url is a link to the prompt in the UI
print(url)
typescript
import * as hub from "langchain/hub";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { ChatOpenAI } from "@langchain/openai";

const model = new ChatOpenAI({ model: "gpt-5.4-mini" });
const prompt = ChatPromptTemplate.fromTemplate("tell me a joke about {topic}");
const chain = prompt.pipe(model);
await hub.push("joke-generator-with-model", {
  object: chain,
});

推送一个 StructuredPrompt

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

不带模型

当你想把模板和 schema 独立于任何模型配置存储时,单独推送这个结构化提示。

python
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)
typescript
import * as hub from "langchain/hub";
import { StructuredPrompt } from "@langchain/core/prompts";

const schema = {
  title: "ResponseSchema",
  type: "object",
  properties: {
    positive_sentiment: {
      type: "boolean",
      description: "Was the user sentiment positive?",
    },
  },
  required: ["positive_sentiment"],
};

const prompt = StructuredPrompt.fromMessagesAndSchema(
  [
    ["system", "Evaluate the sentiment of the following conversation."],
    ["human", "{conversation}"],
  ],
  schema
);

const url = await hub.push("sentiment-evaluator", prompt);
console.log(url);

带模型

把结构化提示作为带模型的 RunnableSequence 推送,以把完整流水线(包括模型配置)存储到 hub。

python
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 返回。

要拉取一个私有提示,你不需要指定 owner 句柄(尽管如果你有设置的,可以指定)。

要从 LangChain Hub 拉取一个公共提示,你需要指定该提示作者的句柄。

python
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"})
python
from langchain_classic import hub as prompts
from langchain_openai import ChatOpenAI

prompt = prompts.pull("joke-generator")
model = ChatOpenAI(model="gpt-5.4-mini")
chain = prompt | model
chain.invoke({"topic": "cats"})
typescript
import * as hub from "langchain/hub";
import { ChatOpenAI } from "@langchain/openai";

const prompt = await hub.pull("joke-generator");
const model = new ChatOpenAI({ model: "gpt-5.4-mini" });
const chain = prompt.pipe(model);
await chain.invoke({"topic": "cats"});
java
import com.langchain.smith.client.LangsmithClient;
import com.langchain.smith.client.okhttp.LangsmithOkHttpClient;
import com.langchain.smith.prompts.Prompt;
import com.langchain.smith.prompts.PromptClient;
import com.langchain.smith.prompts.PromptValue;
import java.util.Map;

LangsmithClient client = LangsmithOkHttpClient.fromEnv();
PromptClient promptClient = PromptClient.create(client);

Prompt prompt = promptClient.pull("joke-generator");
PromptValue formattedPrompt = prompt.invoke(Map.of("topic", "cats"));
// Use formattedPrompt with your model provider — see "Use a prompt without LangChain" below.

与推送提示类似,你也可以把一个提示和模型的 RunnableSequence 作为提示拉取。只需在拉取提示时指定 include_model。如果所存储的提示包含一个模型,它会作为 RunnableSequence 被返回。确保你为你使用的模型设好了适当的环境变量。

python
from langsmith import Client

client = Client()
chain = client.pull_prompt("joke-generator-with-model", include_model=True)
chain.invoke({"topic": "cats"})
python
from langchain_classic import hub as prompts

chain = prompts.pull("joke-generator-with-model", include_model=True)
chain.invoke({"topic": "cats"})
typescript
import * as hub from "langchain/hub";
import { Runnable } from "@langchain/core/runnables";

const chain = await hub.pull<Runnable>("joke-generator-with-model", { includeModel: true });
await chain.invoke({"topic": "cats"});

拉取提示时,你还可以指定一个特定的 commit hash 或提交标签,以拉取提示的一个特定版本。

python
prompt = client.pull_prompt("joke-generator:12344e88")
python
prompt = prompts.pull("joke-generator:12344e88")
typescript
const prompt = await hub.pull("joke-generator:12344e88")
java
String commitHash = "12344e88";
Prompt promptAtCommit = promptClient.pull("joke-generator:" + commitHash);

要从 LangChain Hub 拉取一个公共提示,你需要指定该提示作者的句柄。

python
prompt = client.pull_prompt("efriis/my-first-prompt")
python
prompt = prompts.pull("efriis/my-first-prompt")
typescript
const prompt = await hub.pull("efriis/my-first-prompt")
java
Prompt publicPrompt = promptClient.pull("efriis/my-first-prompt");

NOTE

对于拉取提示,如果你使用 Node.js 或支持动态导入的环境,我们推荐使用 langchain/hub/node 入口点,它会自动处理与你提示配置关联的模型的反序列化。

如果你在非 Node 环境中,对非 OpenAI 模型不支持 "includeModel",你应该用基础的 langchain/hub 入口点。

与 LangSmith Gateway 配合使用

如果你的工作区使用 LangSmith LLM Gateway,你可以在拉取并调用你的提示之前设置一个环境变量,把提示的模型调用路由通过它。无需其他代码更改。

bash
export LANGSMITH_GATEWAY="true"

这用你现有的 LANGSMITH_API_KEY 进行身份验证。要用一个区域网关实例而非默认的,把 LANGSMITH_GATEWAY 设为完整的网关 URL:

bash
export LANGSMITH_GATEWAY="https://eu.gateway.smith.langchain.com"

NOTE

如果你需要为网关调用用一个不同于默认 LANGSMITH_API_KEY 的 API 密钥,把 LANGSMITH_GATEWAY_API_KEY 设为一个覆盖。它必须是一个带 gateway:invoke 权限的工作区作用域密钥。

环境变量设置好后,像平常一样用一个模型拉取并调用一个提示:

python
from langsmith import Client

client = Client()

# Pull a prompt that includes a stored model configuration
prompt_with_model = client.pull_prompt("my-prompt", include_model=True)

# The model call is routed through the gateway automatically
result = prompt_with_model.invoke({"topic": "cats"})

NOTE

LangChain 聊天模型的网关路由需要 Python 和一个受支持的 langchain-* 集成包,最低版本见网关快速开始。如果集成包低于最低版本,调用会绕过网关,直接去提供商。

完整的配置选项、提供商支持和区域端点,见 LLM Gateway 快速开始。

提示缓存

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多久检查一次陈旧提示并在后台刷新它们

刷新时,全局缓存会用最后请求某个给定提示的那个客户端来拉取新数据。

使用缓存

默认情况下,所有客户端都用全局提示缓存。无需配置:

python
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%}")
typescript
import * as hub from "langchain/hub";
// Obtain a reference to the global cache just for logging metrics
import { promptCacheSingleton } from "langsmith";

// Caching is enabled by default
// First pull - fetches from API and caches
const prompt = await hub.pull("joke-generator");

// Subsequent pulls - returns cached version instantly
const prompt2 = await hub.pull("joke-generator");

// Check cache metrics
console.log(`Cache hits: ${promptCacheSingleton.metrics.hits}`);
console.log(`Cache misses: ${promptCacheSingleton.metrics.misses}`);
console.log(`Hit rate: ${(promptCacheSingleton.hitRate * 100).toFixed(1)}%`);

配置全局缓存

你可以配置所有客户端默认使用的全局提示缓存。当你想跨整个应用定制缓存行为时这很有用:

python
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}")
typescript
import * as hub from "langchain/hub";
import {
  configureGlobalPromptCache,
  promptCacheSingleton,
} from "langsmith";

// Configure global cache before pulling prompts
configureGlobalPromptCache({
  maxSize: 200,  // Cache up to 200 prompts
  ttlSeconds: 7200,  // Consider prompts stale after 2 hours
  refreshIntervalSeconds: 600,  // Check for stale prompts every 10 minutes
});

// All hub.pull calls will use these settings
const prompt1 = await hub.pull("prompt-1");
const prompt2 = await hub.pull("prompt-2");

// Check global cache metrics
console.log(`Global cache hits: ${promptCacheSingleton.metrics.hits}`);
console.log(`Global cache misses: ${promptCacheSingleton.metrics.misses}`);

禁用缓存

要为某个特定客户端禁用缓存,传 disable_prompt_cache=True。你也可以全局配置一个为零的最大值:

python
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")
typescript
import * as hub from "langchain/hub";
import { configureGlobalPromptCache } from "langsmith";

// Disable caching globally
configureGlobalPromptCache({ maxSize: 0 });

// Every pull will fetch from the API
const prompt = await hub.pull("joke-generator");

绕过缓存

要对单个请求绕过缓存并从 API 拉取一个新鲜的提示,用 skip_cache 参数:

python
# Force a fresh fetch, ignoring any cached version
prompt = client.pull_prompt("joke-generator", skip_cache=True)
typescript
import * as hub from "langchain/hub";

// Force a fresh fetch, ignoring any cached version
const prompt = await hub.pull("joke-generator", { skipCache: true });

当你需要确保拥有提示的最新版本时(例如在 LangSmith UI 中做了更改之后),这很有用。

离线模式

对于网络连通性有限或无网络的环境,你可以预填充缓存并离线使用它。把 ttl_seconds 设为 None(Python)或 null(TypeScript)以防止缓存条目过期并禁用后台刷新。

步骤 1:把你的提示导出到一个缓存文件(在线时)

python
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")
typescript
import * as hub from "langchain/hub";
import { promptCacheSingleton } from "langsmith";

// Caching is enabled by default

// Pull the prompts you need
await hub.pull("prompt-1");
await hub.pull("prompt-2");
await hub.pull("prompt-3");

// Export cache to a file
promptCacheSingleton.dump("prompts_cache.json");

步骤 2:在你的离线环境加载该缓存文件

python
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")
typescript
import * as hub from "langchain/hub";
import {
  configureGlobalPromptCache,
  promptCacheSingleton,
} from "langsmith";

// Configure cache with infinite TTL (never expire, no background refresh)
configureGlobalPromptCache({ ttlSeconds: null });

// Load the cache file
promptCacheSingleton.load("prompts_cache.json");

// Uses cached version without any API calls
const prompt = await hub.pull("prompt-1");

缓存操作

缓存支持若干操作来管理已缓存的提示:

python
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")
typescript
import { promptCacheSingleton } from "langsmith";

// Invalidate a specific prompt from cache
promptCacheSingleton.invalidate("joke-generator:latest");

// Clear all cached prompts
promptCacheSingleton.clear();

// Reset metrics
promptCacheSingleton.resetMetrics();

清理

你可以手动调用 stop() 来停止后台刷新任务:

python
prompt_cache_singleton.stop()
typescript
promptCacheSingleton.stop();

NOTE

后台刷新任务只在你首次往缓存设一个值时启动,且仅当 ttl_seconds 不为 None。如果 ttl_seconds 为 None(离线模式),不创建后台任务。

不使用 LangChain 使用提示

如果你想把提示存在 LangSmith 中,但直接用某个模型提供商的 API 使用它们,你可以用我们的转换方法。这些方法把你的提示转换为 OpenAI 或 Anthropic API 所需的载荷。

这些转换方法依赖 LangChain 集成包内的逻辑,你需要把相应的包作为依赖安装,除了你选定的官方 SDK。这里有一些例子:

OpenAI

bash
pip install -U langchain_openai
bash
yarn add @langchain/openai @langchain/core # @langchain/openai version >= 0.3.2
python
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)
typescript
import * as hub from "langchain/hub";
import { convertPromptToOpenAI } from "@langchain/openai";
import OpenAI from "openai";

const prompt = await hub.pull("jacob/joke-generator");
const formattedPrompt = await prompt.invoke({
  topic: "cats",
});
const { messages } = convertPromptToOpenAI(formattedPrompt);

const openAIClient = new OpenAI();
const openAIResponse = await openAIClient.chat.completions.create({
  model: "gpt-5.4-mini",
  messages,
});
java
import static com.langchain.smith.prompts.PromptConverters.convertToOpenAIParams;
import com.langchain.smith.client.LangsmithClient;
import com.langchain.smith.client.okhttp.LangsmithOkHttpClient;
import com.langchain.smith.prompts.Prompt;
import com.langchain.smith.prompts.PromptClient;
import com.langchain.smith.prompts.PromptValue;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.ChatModel;
import com.openai.models.chat.completions.ChatCompletion;
import java.util.Map;

LangsmithClient client = LangsmithOkHttpClient.fromEnv();
PromptClient promptClient = PromptClient.create(client);
OpenAIClient openai = OpenAIOkHttpClient.fromEnv();

Prompt prompt = promptClient.pull("jacob/joke-generator");
PromptValue formattedPrompt = prompt.invoke(Map.of("topic", "cats"));

ChatCompletion completion = openai.chat().completions().create(
    convertToOpenAIParams(formattedPrompt)
        .model(ChatModel.GPT_4_1_MINI)
        .build()
);

Anthropic

bash
pip install -U langchain_anthropic
bash
yarn add @langchain/anthropic @langchain/core # @langchain/anthropic version >= 0.3.3
python
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)
typescript
import * as hub from "langchain/hub";
import { convertPromptToAnthropic } from "@langchain/anthropic";
import Anthropic from "@anthropic-ai/sdk";

const prompt = await hub.pull("jacob/joke-generator");
const formattedPrompt = await prompt.invoke({
  topic: "cats",
});
const { messages, system } = convertPromptToAnthropic(formattedPrompt);

const anthropicClient = new Anthropic();
const anthropicResponse = await anthropicClient.messages.create({
  model: "claude-haiku-4-5-20251001",
  system,
  messages,
  max_tokens: 1024,
  stream: false,
});
java
import static com.langchain.smith.prompts.PromptConverters.convertToAnthropicParams;
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.models.messages.Message;
import com.anthropic.models.messages.Model;
import com.langchain.smith.client.LangsmithClient;
import com.langchain.smith.client.okhttp.LangsmithOkHttpClient;
import com.langchain.smith.prompts.Prompt;
import com.langchain.smith.prompts.PromptClient;
import com.langchain.smith.prompts.PromptValue;
import java.util.Map;

LangsmithClient client = LangsmithOkHttpClient.fromEnv();
PromptClient promptClient = PromptClient.create(client);
AnthropicClient anthropic = AnthropicOkHttpClient.fromEnv();

Prompt prompt = promptClient.pull("jacob/joke-generator");
PromptValue formattedPrompt = prompt.invoke(Map.of("topic", "cats"));

Message message = anthropic.messages().create(
    convertToAnthropicParams(formattedPrompt)
        .model(Model.CLAUDE_SONNET_4_5)
        .maxTokens(1024)
        .build()
);

列出、删除和点赞提示

你也可以用 list prompts、delete prompt、like prompt 和 unlike prompt 方法来列出、删除和点赞/取消点赞提示。这些方法的详尽文档见 LangSmith SDK client。

python
# 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")
typescript
// List all prompts in my workspace
import Client from "langsmith";

const client = new Client({ apiKey: "lsv2_..." });
const prompts = client.listPrompts();

for await (const prompt of prompts) {
  console.log(prompt);
}

// List my private prompts that include "joke"
const private_joke_prompts = client.listPrompts({ query: "joke", isPublic: false});

// Delete a prompt
client.deletePrompt("joke-generator");

// Like a prompt
client.likePrompt("efriis/my-first-prompt");

// Unlike a prompt
client.unlikePrompt("efriis/my-first-prompt");
java
import com.langchain.smith.client.LangsmithClient;
import com.langchain.smith.client.okhttp.LangsmithOkHttpClient;
import com.langchain.smith.models.repos.RepoDeleteParams;
import com.langchain.smith.models.repos.RepoListPage;
import com.langchain.smith.models.repos.RepoListParams;
import com.langchain.smith.models.repos.RepoWithLookups;

LangsmithClient client = LangsmithOkHttpClient.fromEnv();

// List all prompts in my workspace
RepoListPage prompts = client.repos().list();
for (RepoWithLookups prompt : prompts.repos()) {
    System.out.println(prompt.repoHandle());
}

// List my private prompts that include "joke"
RepoListPage jokePrompts = client.repos().list(
    RepoListParams.builder()
        .query("joke")
        .isPublic(RepoListParams.IsPublic.FALSE)
        .build()
);

// Delete a prompt
client.repos().delete(
    RepoDeleteParams.builder()
        .owner("-")
        .repo("joke-generator")
        .build()
);

BytesRouter 是社区翻译站点,所有译文仅供参考,一切以官方英文原文为准。