프롬프트를 프로그래매틱하게 관리하기
프롬프트를 프로그래매틱하게 관리하기
LangSmith Python, TypeScript, Java SDK를 사용해 프롬프트를 프로그래매틱하게 관리하는 방법을 알려드릴게요.
패키지 설치
Python에서는 LangSmith SDK를 직접 사용하거나(권장, 전체 기능), LangChain 패키지를 통해 사용할 수 있습니다(프롬프트 푸시 및 풀링으로 제한됨).
TypeScript에서는 프롬프트를 풀려면 LangChain npm 패키지를 사용해야 합니다(푸시도 허용). 다른 모든 기능에는 LangSmith 패키지를 사용합니다.
uv add langsmith # version >= 0.1.99
```bash
```bash TypeScript
yarn add langsmith langchain # langsmith version >= 0.1.99 and langchain version >= 0.2.14
```bash
```kotlin Java/Kotlin (Gradle)
implementation("com.langchain.smith:langsmith-java:0.1.0-beta.4")
```kotlin
</CodeGroup>
## 환경 변수 구성
현재 워크스페이스의 API 키로 `LANGSMITH_API_KEY`를 이미 설정했다면 이 단계를 건너뛸 수 있습니다.
그렇지 않다면 LangSmith에서 `Settings > API Keys > Create API Key`로 이동해 워크스페이스용 API 키를 가져오세요.
환경 변수를 설정하세요.
```bash
export LANGSMITH_API_KEY="lsv2_..."
프롬프트 푸시하기
새 프롬프트를 만들거나 기존 프롬프트를 업데이트하려면 push prompt 메서드를 사용할 수 있습니다.
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 LangChain (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)
```python
```typescript 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);
```typescript
```java 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()
);
```java
</CodeGroup>
프롬프트와 모델의 RunnableSequence로 프롬프트를 푸시할 수도 있습니다. 이는 이 프롬프트에 사용하려는 모델 구성을 저장하는 데 유용합니다. 제공자는 Playground가 지원해야 합니다. [지원되는 모델 제공자](/langsmith/playground-model-providers)를 참조하세요.
<CodeGroup>
```python 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
```python LangChain (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)
```python
```typescript 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,
});
```typescript
</CodeGroup>
## StructuredPrompt 푸시하기
`StructuredPrompt`는 프롬프트 템플릿과 출력 스키마를 결합해 모델이 정의된 구조로 데이터를 반환하도록 보장합니다. `StructuredPrompt.from_messages_and_schema`(Python) 또는 `StructuredPrompt.fromMessagesAndSchema`(TypeScript)를 사용해 생성한 다음 다른 프롬프트처럼 허브에 푸시합니다.
### 모델 없이
템플릿과 스키마를 모델 구성과 독립적으로 저장하려면 구조화된 프롬프트를 단독으로 푸시합니다.
<CodeGroup>
```python 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)
```python
```typescript 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);
```typescript
</CodeGroup>
### 모델과 함께
모델 구성까지 포함한 전체 파이프라인을 허브에 저장하려면 구조화된 프롬프트를 모델과 함께 RunnableSequence로 푸시합니다.
<CodeGroup>
```python 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)
```python
</CodeGroup>
## 프롬프트 풀기
프롬프트를 풀려면 `pull prompt` 메서드를 사용할 수 있으며, 이 메서드는 프롬프트를 langchain `PromptTemplate`으로 반환합니다.
**비공개 프롬프트**를 풀려면 소유자 핸들을 지정할 필요가 없습니다(설정한 경우에는 지정할 수 있습니다).
LangChain Hub에서 **공개 프롬프트**를 풀려면 프롬프트 작성자의 핸들을 지정해야 합니다.
<CodeGroup>
```python 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
```python LangChain (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"})
```python
```typescript 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"});
```typescript
```java 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.
```java
</CodeGroup>
프롬프트를 푸시하는 것과 유사하게, 프롬프트와 모델의 RunnableSequence로 프롬프트를 풀 수도 있습니다. 프롬프트를 풀 때 include\_model을 지정하면 됩니다. 저장된 프롬프트에 모델이 포함되어 있으면 RunnableSequence로 반환됩니다. 사용 중인 모델에 대한 올바른 환경 변수를 설정했는지 확인하세요.
<CodeGroup>
```python Python
from langsmith import Client
client = Client()
chain = client.pull_prompt("joke-generator-with-model", include_model=True)
chain.invoke({"topic": "cats"})
```python
```python LangChain (Python)
from langchain_classic import hub as prompts
chain = prompts.pull("joke-generator-with-model", include_model=True)
chain.invoke({"topic": "cats"})
```python
```typescript 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"});
```typescript
</CodeGroup>
프롬프트를 풀 때 특정 커밋 해시나 [커밋 태그](/langsmith/manage-prompts#commit-tags)를 지정해 특정 버전의 프롬프트를 풀 수도 있습니다.
<CodeGroup>
```python Python
prompt = client.pull_prompt("joke-generator:12344e88")
```python
```python LangChain (Python)
prompt = prompts.pull("joke-generator:12344e88")
```python
```typescript TypeScript
const prompt = await hub.pull("joke-generator:12344e88")
```typescript
```java Java
String commitHash = "12344e88";
Prompt promptAtCommit = promptClient.pull("joke-generator:" + commitHash);
```java
</CodeGroup>
LangChain Hub에서 공개 프롬프트를 풀려면 프롬프트 작성자의 핸들을 지정해야 합니다.
<CodeGroup>
```python Python
prompt = client.pull_prompt("efriis/my-first-prompt")
```python
```python LangChain (Python)
prompt = prompts.pull("efriis/my-first-prompt")
```python
```typescript TypeScript
const prompt = await hub.pull("efriis/my-first-prompt")
```typescript
```java Java
Prompt publicPrompt = promptClient.pull("efriis/my-first-prompt");
```java
</CodeGroup>
<Note>
프롬프트 풀기에 대해, Node.js 또는 동적 import를 지원하는 환경을 사용한다면 `langchain/hub/node` 엔트리포인트를 사용할 것을 권장합니다. 이 엔트리포인트는 프롬프트 구성과 연관된 모델의 역직렬화를 자동으로 처리합니다.
Node가 아닌 환경이라면 "includeModel"은 비-OpenAI 모델에 대해 지원되지 않으므로 기본 `langchain/hub` 엔트리포인트를 사용해야 합니다.
</Note>
## LangSmith Gateway와 함께 사용하기
워크스페이스가 [LangSmith LLM Gateway](/langsmith/llm-gateway)를 사용한다면 프롬프트를 풀고 호출하기 전에 환경 변수를 설정해 프롬프트 모델 호출을 게이트웨이를 통해 라우팅할 수 있습니다. 다른 코드 변경은 필요하지 않습니다.
```bash
export LANGSMITH_GATEWAY="true"
이것은 인증에 기존 LANGSMITH_API_KEY를 사용합니다. 기본값 대신 지역 게이트웨이 인스턴스를 사용하려면 LANGSMITH_GATEWAY를 전체 게이트웨이 URL로 설정하세요:
export LANGSMITH_GATEWAY="https://eu.gateway.smith.langchain.com"
환경 변수가 설정되면 평소처럼 모델이 있는 프롬프트를 풀고 호출합니다:
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"})
전체 구성 옵션, 제공자 지원, 지역 엔드포인트는 LLM Gateway 퀵스타트를 참조하세요.
프롬프트 캐싱
LangSmith SDK에는 프롬프트용 기본 제공 인메모리 캐싱이 포함되어 있습니다. 활성화하면 LangSmith가 가져온 프롬프트를 메모리에 캐시해 자주 사용하는 프롬프트의 지연 시간과 API 호출을 줄입니다. 캐시는 모든 클라이언트가 공유하고 프로세스 수명 동안 지속되는 전역 싱글톤 인스턴스를 사용합니다. stale-while-revalidate 패턴을 구현해 애플리케이션이 항상 빠른 응답을 얻는 동시에 백그라운드에서 프롬프트를 최신 상태로 유지합니다.
요구사항:
- Python SDK:
langsmith >= 0.7.0 - TypeScript SDK:
langsmith >= 0.5.0
기본 동작
캐싱은 기본적으로 활성화되어 있습니다. 활성화되면 기본 설정은 다음과 같습니다:
| 설정 | 기본값 | 설명 |
|---|---|---|
max_size |
100 | 캐시할 최대 프롬프트 수 |
ttl_seconds |
300 (5분) | 캐시된 프롬프트가 오래된 것으로 간주되기까지의 시간 |
refresh_interval_seconds |
60 | 오래된 프롬프트를 확인하고 백그라운드에서 새로 고치는 빈도 |
새로 고칠 때 전역 캐시는 주어진 프롬프트를 마지막으로 요청한 클라이언트를 사용해 새 데이터를 가져옵니다.
캐시 사용
기본적으로 모든 클라이언트는 전역 프롬프트 캐시를 사용합니다. 구성이 필요하지 않습니다:
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 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)}%`);
```typescript
</CodeGroup>
### 전역 캐시 구성
모든 클라이언트가 기본적으로 사용하는 전역 프롬프트 캐시를 구성할 수 있습니다. 애플리케이션 전체에서 캐싱 동작을 사용자 지정하려는 경우 유용합니다:
<CodeGroup>
```python 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}")
```python
```typescript 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}`);
```typescript
</CodeGroup>
### 캐시 비활성화
특정 클라이언트에 대해 캐싱을 비활성화하려면 `disable_prompt_cache=True`를 전달하세요. 전역적으로 최대 크기를 0으로 구성할 수도 있습니다:
<CodeGroup>
```python 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")
```python
```typescript 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");
```typescript
</CodeGroup>
### 캐시 건너뛰기
개별 요청에 대해 캐시를 우회하고 API에서 새 프롬프트를 가져오려면 `skip_cache` 매개변수를 사용하세요:
<CodeGroup>
```python Python
# Force a fresh fetch, ignoring any cached version
prompt = client.pull_prompt("joke-generator", skip_cache=True)
```python
```typescript TypeScript
import * as hub from "langchain/hub";
// Force a fresh fetch, ignoring any cached version
const prompt = await hub.pull("joke-generator", { skipCache: true });
```typescript
</CodeGroup>
이것은 LangSmith UI에서 변경한 후처럼 프롬프트의 최신 버전을 확인해야 할 때 유용합니다.
### 오프라인 모드
네트워크 연결이 제한되거나 없는 환경에서는 캐시를 미리 채우고 오프라인으로 사용할 수 있습니다. 캐시 항목이 만료되지 않고 백그라운드 새로 고침이 비활성화되도록 `ttl_seconds`를 `None`(Python) 또는 `null`(TypeScript)로 설정하세요.
**1단계: 캐시 파일로 프롬프트 내보내기(온라인 상태에서)**
<CodeGroup>
```python 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")
```python
```typescript 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");
```typescript
</CodeGroup>
**2단계: 오프라인 환경에서 캐시 파일 로드**
<CodeGroup>
```python 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")
```python
```typescript 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");
```typescript
</CodeGroup>
### 캐시 연산
캐시는 캐시된 프롬프트를 관리하기 위한 여러 연산을 지원합니다:
<CodeGroup>
```python 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")
```python
```typescript 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();
```typescript
</CodeGroup>
### 정리
백그라운드 새로 고침 작업을 중지하려면 `stop()`을 수동으로 호출할 수 있습니다:
<CodeGroup>
```python Python
prompt_cache_singleton.stop()
```python
```typescript TypeScript
promptCacheSingleton.stop();
```typescript
</CodeGroup>
<Note>
백그라운드 새로 고침 작업은 캐시에 값을 처음 설정할 때만 시작되며, `ttl_seconds`가 `None`이 아닌 경우에만 시작됩니다. `ttl_seconds`가 `None`(오프라인 모드)이면 백그라운드 작업이 생성되지 않습니다.
</Note>
## LangChain 없이 프롬프트 사용하기
프롬프트를 LangSmith에 저장하되 모델 제공자의 API와 직접 사용하려면 변환 메서드를 사용할 수 있습니다. 이 메서드는 프롬프트를 OpenAI 또는 Anthropic API에 필요한 페이로드로 변환합니다.
이 변환 메서드는 LangChain 통합 패키지 내부의 로직에 의존하므로 선택한 공식 SDK에 추가로 해당 패키지를 종속성으로 설치해야 합니다. 몇 가지 예시가 있습니다:
### OpenAI
<CodeGroup>
```bash Python
pip install -U langchain_openai
```bash
```bash TypeScript
yarn add @langchain/openai @langchain/core # @langchain/openai version >= 0.3.2
```bash
</CodeGroup>
<CodeGroup>
```python 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)
```python
```typescript 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,
});
```typescript
```java 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()
);
```java
</CodeGroup>
### Anthropic
<CodeGroup>
```bash Python
pip install -U langchain_anthropic
```bash
```bash TypeScript
yarn add @langchain/anthropic @langchain/core # @langchain/anthropic version >= 0.3.3
```bash
</CodeGroup>
<CodeGroup>
```python 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)
```python
```typescript 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,
});
```typescript
```java 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()
);
```java
</CodeGroup>
## 프롬프트 나열, 삭제, 좋아요 표시
또한 `list prompts`, `delete prompt`, `like prompt` 및 `unlike prompt` 메서드를 사용해 프롬프트를 나열, 삭제, 좋아요/좋아요 취소할 수 있습니다. 이러한 메서드에 대한 광범위한 문서는 [LangSmith SDK 클라이언트](https://github.com/langchain-ai/langsmith-sdk)를 참조하세요.
<CodeGroup>
```python 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")
```python
```typescript TypeScript
// List all prompts in my workspace
import Client from "langsmith";
const client = new Client({ apiKey: *** });
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");
```typescript
```java 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()
);
```java
</CodeGroup>
***
> 출처: [문서](https://docs.langchain.com/langsmith/manage-prompts-programmatically)
## 더 알아보기 (Learn more)
- [Connect these docs](/use-these-docs) to Claude, VSCode, and more via MCP for real-time answers.
- [Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/langsmith/manage-prompts-programmatically.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).