> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-zh.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# 以编程方式管理提示词

你可以使用 LangSmith 的 Python 和 TypeScript SDK 以编程方式管理提示词。

<Note>
  此功能先前位于现已弃用的 `langchainhub` 包中。未来所有功能都将迁移到 `langsmith` 包中。
</Note>

## 安装包

在 Python 中，你可以直接使用 LangSmith SDK（*推荐，功能完整*），也可以通过 LangChain 包使用（仅限于推送和拉取提示词）。

在 TypeScript 中，你必须使用 LangChain npm 包来拉取提示词（它也支持推送）。对于所有其他功能，请使用 LangSmith 包。

<CodeGroup>
  ```bash pip theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  pip install -U langsmith # 版本 >= 0.1.99
  ```

  ```bash uv theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  uv add langsmith  # 版本 >= 0.1.99
  ```

  ```bash TypeScript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  yarn add langsmith langchain // langsmith 版本 >= 0.1.99 且 langchain 版本 >= 0.2.14
  ```
</CodeGroup>

## 配置环境变量

如果你已经将 `LANGSMITH_API_KEY` 设置为当前 LangSmith 工作空间的 API 密钥，可以跳过此步骤。

否则，请通过导航到 LangSmith 中的 `Settings > API Keys > Create API Key` 获取工作空间的 API 密钥。

设置环境变量。

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
export LANGSMITH_API_KEY="lsv2_..."
```

<Note>
  我们所说的“提示词”过去被称为“仓库”，因此代码中任何对“repo”的引用都指的是提示词。
</Note>

## 推送提示词

要创建新提示词或更新现有提示词，可以使用 `push prompt` 方法。

<CodeGroup>
  ```python Python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  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 是指向 UI 中提示词的链接
  print(url)
  ```

  ```python LangChain (Python) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  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 是指向 UI 中提示词的链接
  print(url)
  ```

  ```typescript TypeScript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  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 是指向 UI 中提示词的链接
  console.log(url);
  ```

  ```java Java theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  import com.langchain.smith.models.prompts.PromptPushParams;
  import com.langchain.smith.models.prompts.Prompt;

  Prompt prompt = Prompt.builder()
      .name("joke-generator")
      .object(prompt)
      .build();
  var url = client.prompts().push(prompt);
  ```
</CodeGroup>

你也可以将提示词作为提示词和模型的 RunnableSequence 推送。这对于存储你希望与此提示词一起使用的模型配置非常有用。提供者必须受 Playground 支持，请参阅[支持的模型提供者](/langsmith/playground-model-providers)。

<CodeGroup>
  ```python Python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langsmith import Client
  from langchain_core.prompts import ChatPromptTemplate
  from langchain_openai import ChatOpenAI

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

  ```python LangChain (Python) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain_classic import hub as prompts
  from langchain_core.prompts import ChatPromptTemplate
  from langchain_openai import ChatOpenAI

  model = ChatOpenAI(model="gpt-4.1-mini")
  prompt = ChatPromptTemplate.from_template("tell me a joke about {topic}")
  chain = prompt | model
  url = prompts.push("joke-generator-with-model", chain)
  # url 是指向 UI 中提示词的链接
  print(url)
  ```

  ```typescript TypeScript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  import * as hub from "langchain/hub";
  import { ChatPromptTemplate } from "@langchain/core/prompts";
  import { ChatOpenAI } from "@langchain/openai";

  const model = new ChatOpenAI({ model: "gpt-4.1-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,
  });
  ```
</CodeGroup>

## 推送 StructuredPrompt

`StructuredPrompt` 将提示词模板与输出模式相结合，确保模型返回的数据符合定义的结构。使用 `StructuredPrompt.from_messages_and_schema`（Python）或 `StructuredPrompt.fromMessagesAndSchema`（TypeScript）创建一个，然后像推送其他提示词一样将其推送到 hub。

### 不包含模型

当你希望独立于任何模型配置存储模板和模式时，可以单独推送结构化提示词。

<CodeGroup>
  ```python Python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  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 TypeScript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  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);
  ```
</CodeGroup>

### 包含模型

将结构化提示词作为 RunnableSequence 与模型一起推送，以在 hub 中存储完整的流水线，包括模型配置。

<CodeGroup>
  ```python Python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  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)
  ```
</CodeGroup>

## 拉取提示词

要拉取提示词，可以使用 `pull prompt` 方法，该方法将提示词作为 langchain 的 `PromptTemplate` 返回。

要拉取**私有提示词**，你不需要指定所有者句柄（但如果你设置了句柄，也可以指定）。

要从 LangChain Hub 拉取**公共提示词**，你需要指定提示词作者的句柄。

<CodeGroup>
  ```python Python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langsmith import Client
  from langchain_openai import ChatOpenAI

  client = Client()
  prompt = client.pull_prompt("joke-generator")
  model = ChatOpenAI(model="gpt-4.1-mini")
  chain = prompt | model
  chain.invoke({"topic": "cats"})
  ```

  ```python LangChain (Python) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain_classic import hub as prompts
  from langchain_openai import ChatOpenAI

  prompt = prompts.pull("joke-generator")
  model = ChatOpenAI(model="gpt-4.1-mini")
  chain = prompt | model
  chain.invoke({"topic": "cats"})
  ```

  ```typescript TypeScript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  import * as hub from "langchain/hub";
  import { ChatOpenAI } from "@langchain/openai";

  const prompt = await hub.pull("joke-generator");
  const model = new ChatOpenAI({ model: "gpt-4.1-mini" });
  const chain = prompt.pipe(model);
  await chain.invoke({"topic": "cats"});
  ```

  ```java Java theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  RepoListPage jokePrompts = client.repos().list(
      RepoListParams.builder()
          .query("joke")
          .isPublic(RepoListParams.IsPublic.FALSE)
          .build()
  );
  ```
</CodeGroup>

与推送提示词类似，你也可以将提示词作为提示词和模型的 RunnableSequence 拉取。只需在拉取提示词时指定 include\_model。如果存储的提示词包含模型，它将作为 RunnableSequence 返回。确保为你使用的模型设置了正确的环境变量。

<CodeGroup>
  ```python Python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langsmith import Client

  client = Client()
  chain = client.pull_prompt("joke-generator-with-model", include_model=True)
  chain.invoke({"topic": "cats"})
  ```

  ```python LangChain (Python) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain_classic import hub as prompts

  chain = prompts.pull("joke-generator-with-model", include_model=True)
  chain.invoke({"topic": "cats"})
  ```

  ```typescript TypeScript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  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"});
  ```
</CodeGroup>

拉取提示词时，你还可以指定特定的提交哈希或[提交标签](/langsmith/manage-prompts#commit-tags)来拉取提示词的特定版本。

<CodeGroup>
  ```python Python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  prompt = client.pull_prompt("joke-generator:12344e88")
  ```

  ```python LangChain (Python) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  prompt = prompts.pull("joke-generator:12344e88")
  ```

  ```typescript TypeScript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  const prompt = await hub.pull("joke-generator:12344e88")
  ```
</CodeGroup>

要从 LangChain Hub 拉取公共提示词，你需要指定提示词作者的句柄。

<CodeGroup>
  ```python Python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  prompt = client.pull_prompt("efriis/my-first-prompt")
  ```

  ```python LangChain (Python) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  prompt = prompts.pull("efriis/my-first-prompt")
  ```

  ```typescript TypeScript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  const prompt = await hub.pull("efriis/my-first-prompt")
  ```
</CodeGroup>

<Note>
  对于拉取提示词，如果你使用的是 Node.js 或支持动态导入的环境，我们建议使用 `langchain/hub/node` 入口点，因为它会自动处理与提示词配置关联的模型的反序列化。

  如果你在非 Node 环境中，对于非 OpenAI 模型不支持“includeModel”，你应该使用基础的 `langchain/hub` 入口点。
</Note>

## 提示词缓存

LangSmith SDK 包含内置的内存中提示词缓存。启用后，LangSmith 会将拉取的提示词缓存在内存中，减少频繁使用提示词的延迟和 API 调用。缓存使用全局单例实例，该实例在所有客户端之间共享，并在进程的整个生命周期内持续存在。它实现了陈旧-重新验证模式，确保你的应用程序始终获得快速响应，同时在后台保持提示词的最新状态。

**要求：**

* Python SDK：`langsmith >= 0.7.0`
* TypeScript SDK：`langsmith >= 0.5.0`

### 默认行为

缓存**默认启用**。启用后，默认设置如下：

| 设置                         | 默认值       | 描述               |
| -------------------------- | --------- | ---------------- |
| `max_size`                 | 100       | 缓存的最大提示词数量       |
| `ttl_seconds`              | 300（5 分钟） | 缓存提示词被视为陈旧前的时间   |
| `refresh_interval_seconds` | 60        | 检查陈旧提示词并在后台刷新的频率 |

刷新时，全局缓存将使用最后请求给定提示词的客户端来获取新数据。

### 使用缓存

默认情况下，所有客户端都使用全局提示词缓存。无需配置：

<CodeGroup>
  ```python Python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langsmith import Client
  # 仅为记录指标获取全局缓存的引用
  from langsmith.prompt_cache import prompt_cache_singleton

  # 默认启用缓存，使用全局单例
  client = Client()

  # 第一次拉取 - 从 API 获取并缓存
  prompt = client.pull_prompt("joke-generator")

  # 后续拉取 - 立即返回缓存版本
  prompt = client.pull_prompt("joke-generator")

  # 检查缓存指标
  print(f"缓存命中: {prompt_cache_singleton.metrics.hits}")
  print(f"缓存未命中: {prompt_cache_singleton.metrics.misses}")
  print(f"命中率: {prompt_cache_singleton.metrics.hit_rate:.1%}")
  ```

  ```typescript TypeScript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  import * as hub from "langchain/hub";
  // 仅为记录指标获取全局缓存的引用
  import { promptCacheSingleton } from "langsmith";

  // 默认启用缓存
  // 第一次拉取 - 从 API 获取并缓存
  const prompt = await hub.pull("joke-generator");

  // 后续拉取 - 立即返回缓存版本
  const prompt2 = await hub.pull("joke-generator");

  // 检查缓存指标
  console.log(`缓存命中: ${promptCacheSingleton.metrics.hits}`);
  console.log(`缓存未命中: ${promptCacheSingleton.metrics.misses}`);
  console.log(`命中率: ${(promptCacheSingleton.hitRate * 100).toFixed(1)}%`);
  ```
</CodeGroup>

### 配置全局缓存

你可以配置所有客户端默认使用的全局提示词缓存。这在你想在整个应用程序中自定义缓存行为时非常有用：

<CodeGroup>
  ```python Python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langsmith import Client
  from langsmith.prompt_cache import (
      configure_global_prompt_cache,
      prompt_cache_singleton,
  )

  # 在创建任何客户端之前配置全局缓存
  configure_global_prompt_cache(
      max_size=200,  # 最多缓存 200 个提示词
      ttl_seconds=7200,  # 2 小时后认为提示词陈旧
      refresh_interval_seconds=600,  # 每 10 分钟检查一次陈旧提示词
  )

  # 所有客户端都将使用这些设置
  client1 = Client()
  client2 = Client()

  # 两个客户端共享具有你自定义设置的同一全局缓存
  prompt1 = client1.pull_prompt("prompt-1")
  prompt2 = client2.pull_prompt("prompt-2")

  # 检查全局缓存指标
  print(f"全局缓存命中: {prompt_cache_singleton.metrics.hits}")
  print(f"全局缓存未命中: {prompt_cache_singleton.metrics.misses}")
  ```

  ```typescript TypeScript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  import * as hub from "langchain/hub";
  import {
    configureGlobalPromptCache,
    promptCacheSingleton,
  } from "langsmith";

  // 在拉取提示词之前配置全局缓存
  configureGlobalPromptCache({
    maxSize: 200,  // 最多缓存 200 个提示词
    ttlSeconds: 7200,  // 2 小时后认为提示词陈旧
    refreshIntervalSeconds: 600,  // 每 10 分钟检查一次陈旧提示词
  });

  // 所有 hub.pull 调用都将使用这些设置
  const prompt1 = await hub.pull("prompt-1");
  const prompt2 = await hub.pull("prompt-2");

  // 检查全局缓存指标
  console.log(`全局缓存命中: ${promptCacheSingleton.metrics.hits}`);
  console.log(`全局缓存未命中: ${promptCacheSingleton.metrics.misses}`);
  ```
</CodeGroup>

### 禁用缓存

要为特定客户端禁用缓存，请传递 `disable_prompt_cache=True`。你也可以全局配置最大大小为零：

<CodeGroup>
  ```python Python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langsmith import Client

  # 为此客户端禁用缓存
  client = Client(disable_prompt_cache=True)

  # 每次拉取都将从 API 获取
  prompt = client.pull_prompt("joke-generator")
  ```

  ```typescript TypeScript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  import * as hub from "langchain/hub";
  import { configureGlobalPromptCache } from "langsmith";

  // 全局禁用缓存
  configureGlobalPromptCache({ maxSize: 0 });

  // 每次拉取都将从 API 获取
  const prompt = await hub.pull("joke-generator");
  ```
</CodeGroup>

### 跳过缓存

要为单个请求绕过缓存并从 API 获取新的提示词，请使用 `skip_cache` 参数：

<CodeGroup>
  ```python Python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  # 强制获取新版本，忽略任何缓存版本
  prompt = client.pull_prompt("joke-generator", skip_cache=True)
  ```

  ```typescript TypeScript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  import * as hub from "langchain/hub";

  # 强制获取新版本，忽略任何缓存版本
  const prompt = await hub.pull("joke-generator", { skipCache: true });
  ```
</CodeGroup>

这在需要确保拥有提示词的最新版本时非常有用，例如在 LangSmith UI 中进行更改后。

### 离线模式

对于网络连接有限或没有网络连接的环境，你可以预先填充缓存并离线使用。将 `ttl_seconds` 设置为 `None`（Python）或 `null`（TypeScript）以防止缓存条目过期并禁用后台刷新。

**步骤 1：将提示词导出到缓存文件（在线时）**

<CodeGroup>
  ```python Python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langsmith import Client
  from langsmith.prompt_cache import prompt_cache_singleton

  # 创建客户端（默认启用缓存）
  client = Client()

  # 拉取你需要的提示词
  client.pull_prompt("prompt-1")
  client.pull_prompt("prompt-2")
  client.pull_prompt("prompt-3")

  # 将缓存导出到文件
  prompt_cache_singleton.dump("prompts_cache.json")
  ```

  ```typescript TypeScript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  import * as hub from "langchain/hub";
  import { promptCacheSingleton } from "langsmith";

  // 默认启用缓存

  // 拉取你需要的提示词
  await hub.pull("prompt-1");
  await hub.pull("prompt-2");
  await hub.pull("prompt-3");

  // 将缓存导出到文件
  promptCacheSingleton.dump("prompts_cache.json");
  ```
</CodeGroup>

**步骤 2：在离线环境中加载缓存文件**

<CodeGroup>
  ```python Python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langsmith import Client
  from langsmith.prompt_cache import (
      configure_global_prompt_cache,
      prompt_cache_singleton,
  )

  # 配置具有无限 TTL 的缓存（永不过期，无后台刷新）
  configure_global_prompt_cache(ttl_seconds=None)

  # 加载缓存文件
  prompt_cache_singleton.load("prompts_cache.json")

  # 创建客户端（使用已加载的缓存）
  client = Client()

  # 使用缓存版本，无需任何 API 调用
  prompt = client.pull_prompt("prompt-1")
  ```

  ```typescript TypeScript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  import * as hub from "langchain/hub";
  import {
    configureGlobalPromptCache,
    promptCacheSingleton,
  } from "langsmith";

  // 配置具有无限 TTL 的缓存（永不过期，无后台刷新）
  configureGlobalPromptCache({ ttlSeconds: null });

  // 加载缓存文件
  promptCacheSingleton.load("prompts_cache.json");

  // 使用缓存版本，无需任何 API 调用
  const prompt = await hub.pull("prompt-1");
  ```
</CodeGroup>

### 缓存操作

缓存支持多种管理缓存提示词的操作：

<CodeGroup>
  ```python Python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langsmith import Client
  from langsmith.prompt_cache import prompt_cache_singleton

  client = Client()

  # 使特定提示词从缓存中失效
  prompt_cache_singleton.invalidate("joke-generator:latest")

  # 清除所有缓存的提示词
  prompt_cache_singleton.clear()

  # 重置指标
  prompt_cache_singleton.reset_metrics()

  # 检查缓存是否正在运行后台刷新
  # （仅当 ttl_seconds 不为 None 时运行）
  if prompt_cache_singleton._refresh_thread is not None:
      print("后台刷新处于活动状态")
  ```

  ```typescript TypeScript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  import { promptCacheSingleton } from "langsmith";

  // 使特定提示词从缓存中失效
  promptCacheSingleton.invalidate("joke-generator:latest");

  // 清除所有缓存的提示词
  promptCacheSingleton.clear();

  // 重置指标
  promptCacheSingleton.resetMetrics();
  ```
</CodeGroup>

### 清理

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

<CodeGroup>
  ```python Python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  prompt_cache_singleton.stop()
  ```

  ```typescript TypeScript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  promptCacheSingleton.stop();
  ```
</CodeGroup>

<Note>
  后台刷新任务仅在首次在缓存中设置值时启动，并且仅当 `ttl_seconds` 不为 `None` 时。如果 `ttl_seconds` 为 `None`（离线模式），则不会创建后台任务。
</Note>

## 不使用 LangChain 使用提示词

如果你希望将提示词存储在 LangSmith 中，但直接与模型提供者的 API 一起使用，可以使用我们的转换方法。这些方法将你的提示词转换为 OpenAI 或 Anthropic API 所需的负载。

这些转换方法依赖于 LangChain 集成包内的逻辑，除了你选择的官方 SDK 外，你还需要安装相应的包作为依赖项。以下是一些示例：

### OpenAI

<CodeGroup>
  ```bash Python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  pip install -U langchain_openai
  ```

  ```bash TypeScript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  yarn add @langchain/openai @langchain/core // @langchain/openai 版本 >= 0.3.2
  ```
</CodeGroup>

<CodeGroup>
  ```python Python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from openai import OpenAI
  from langsmith.client import Client, convert_prompt_to_openai_format

  # langsmith 客户端
  client = Client()
  # openai 客户端
  oai_client = OpenAI()

  # 拉取提示词并调用以填充变量
  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 TypeScript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  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-4.1-mini",
    messages,
  });
  ```
</CodeGroup>

### Anthropic

<CodeGroup>
  ```bash Python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  pip install -U langchain_anthropic
  ```

  ```bash TypeScript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  yarn add @langchain/anthropic @langchain/core // @langchain/anthropic 版本 >= 0.3.3
  ```
</CodeGroup>

<CodeGroup>
  ```python Python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from anthropic import Anthropic
  from langsmith.client import Client, convert_prompt_to_anthropic_format

  # langsmith 客户端
  client = Client()
  # anthropic 客户端
  anthropic_client = Anthropic()

  # 拉取提示词并调用以填充变量
  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 TypeScript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  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,
  });
  ```
</CodeGroup>

## 列出、删除和点赞提示词

你也可以使用 `list prompts`、`delete prompt`、`like prompt` 和 `unlike prompt` 方法来列出、删除和点赞/取消点赞提示词。有关这些方法的详细文档，请参阅 [LangSmith SDK 客户端](https://github.com/langchain-ai/langsmith-sdk)。

<CodeGroup>
  ```python Python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  # 列出我工作空间中的所有提示词
  prompts = client.list_prompts()

  # 列出我包含“joke”的私有提示词
  prompts = client.list_prompts(query="joke", is_public=False)

  # 删除提示词
  client.delete_prompt("joke-generator")

  # 点赞提示词
  client.like_prompt("efriis/my-first-prompt")

  # 取消点赞提示词
  client.unlike_prompt("efriis/my-first-prompt")
  ```

  ```typescript TypeScript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  // 列出我工作空间中的所有提示词
  import Client from "langsmith";

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

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

  // 列出我包含“joke”的私有提示词
  const private_joke_prompts = client.listPrompts({ query: "joke", isPublic: false});

  // 删除提示词
  client.deletePrompt("joke-generator");

  // 点赞提示词
  client.likePrompt("efriis/my-first-prompt");

  // 取消点赞提示词
  client.unlikePrompt("efriis/my-first-prompt");
  ```

  ```java Java theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  // 列出我工作空间中的所有提示词
  RepoListPage prompts = client.repos().list();
  for (RepoWithLookups prompt : prompts.repos()) {
      System.out.println(prompt.repoHandle());
  }

  // 列出我包含“joke”的私有提示词
  RepoListPage jokePrompts = client.repos().list(
      RepoListParams.builder()
          .query("joke")
          .isPublic(RepoListParams.IsPublic.FALSE)
          .build()
  );

  // 删除提示词
  String promptId = "joke-generator";
  String[] parts = promptId.split("/", 2);
  String owner = parts.length > 1 ? parts[0] : "-";
  String repo = parts.length > 1 ? parts[1] : promptId;

  client.repos().delete(
      RepoDeleteParams.builder()
          .owner(owner)
          .repo(repo)
          .build()
  );
  ```
</CodeGroup>

***

<div className="source-links">
  <Callout icon="edit">
    [Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/i18n\zh-CN\langsmith\manage-prompts-programmatically.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).
  </Callout>

  <Callout icon="terminal-2">
    [Connect these docs](/use-these-docs) to Claude, VSCode, and more via MCP for real-time answers.
  </Callout>
</div>
