jpskill.com
🛠️ 開発・MCP コミュニティ

langsmith

LangSmithを活用し、LLM(大規模言語モデル)を使ったアプリの実行状況を監視・追跡したり、AIの出力品質を評価したり、プロンプトの実験やモデル比較などを行い、LLMテストの仕組みを構築することで、LLMアプリの改善を支援するSkill。

📜 元の英語説明(参考)

Monitor, trace, debug, and evaluate LLM applications with LangSmith. Use when a user asks to trace LLM calls, debug chain executions, evaluate AI output quality, set up LLM observability, monitor agent performance, run prompt experiments, compare model outputs, create evaluation datasets, track token usage and latency, or build LLM testing pipelines. Covers tracing, datasets, evaluators, annotation queues, prompt hub, and production monitoring.

🇯🇵 日本人クリエイター向け解説

一言でいうと

LangSmithを活用し、LLM(大規模言語モデル)を使ったアプリの実行状況を監視・追跡したり、AIの出力品質を評価したり、プロンプトの実験やモデル比較などを行い、LLMテストの仕組みを構築することで、LLMアプリの改善を支援するSkill。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o langsmith.zip https://jpskill.com/download/15055.zip && unzip -o langsmith.zip && rm langsmith.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/15055.zip -OutFile "$d\langsmith.zip"; Expand-Archive "$d\langsmith.zip" -DestinationPath $d -Force; ri "$d\langsmith.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して langsmith.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → langsmith フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

LangSmith

概要

LangSmith は、LLM アプリケーションのための可観測性と評価プラットフォームです。チェーンとエージェントのあらゆるステップをトレースし、評価データセットの構築、自動品質チェックの実行、および本番環境のパフォーマンスの監視を支援します。LLM アプリをプロトタイプから本番環境に移行するために不可欠です。

手順

ステップ 1: セットアップと構成

smith.langchain.com で LangSmith アカウントを作成し、API キーを取得します。

pip install langsmith

環境変数を設定します。

export LANGCHAIN_TRACING_V2=true
export LANGCHAIN_API_KEY="lsv2_pt_..."
export LANGCHAIN_PROJECT="my-project"  # オプション、デフォルトは "default"

設定すると、すべての LangChain 呼び出しが自動的にトレースされます — コードの変更は不要です。

LangChain 以外のコードについては、SDK を直接使用します。

from langsmith import Client
client = Client()

ステップ 2: トレーシング

自動トレーシング (LangChain)

LANGCHAIN_TRACING_V2=true を設定すると、すべての .invoke().stream().batch() 呼び出しが自動的にトレースされます。各トレースには以下が表示されます。

  • すべてのステップでの入力/出力
  • トークンの使用量とコスト
  • コンポーネントごとのレイテンシ
  • 完全なスタックトレースを含むエラーの詳細

@traceable を使用した手動トレーシング

LangChain 外部のカスタム関数については、以下のようにします。

from langsmith import traceable

@traceable(name="process_order", tags=["production"])
def process_order(order_id: str, items: list) -> dict:
    # ビジネスロジック
    validated = validate_items(items)
    summary = generate_summary(validated)  # LLM 呼び出し
    return {"order_id": order_id, "summary": summary, "status": "processed"}

@traceable
def validate_items(items: list) -> list:
    # ネストされたトレースは自動的に親にリンクされます
    return [item for item in items if item["quantity"] > 0]

コンテキストマネージャーを使用したトレーシング

from langsmith import trace

with trace("data-pipeline", inputs={"source": "csv"}) as run:
    data = load_data("input.csv")
    processed = transform(data)
    run.end(outputs={"rows": len(processed)})

メタデータとタグ

# LangChain の呼び出しにメタデータを追加します
result = chain.invoke(
    {"question": "..."},
    config={
        "metadata": {"user_id": "u-123", "environment": "staging"},
        "tags": ["beta-test", "gpt4"]
    }
)

ステップ 3: データセットとサンプル

データセットは、評価に使用される入力/出力ペアのコレクションです。

from langsmith import Client

client = Client()

# データセットを作成します
dataset = client.create_dataset("customer-support-qa", description="Real support questions with expected answers")

# サンプルを追加します
client.create_examples(
    inputs=[
        {"question": "How do I reset my password?"},
        {"question": "What's your refund policy?"},
    ],
    outputs=[
        {"answer": "Go to Settings > Security > Reset Password"},
        {"answer": "Full refund within 30 days, no questions asked"},
    ],
    dataset_id=dataset.id,
)
# 既存のトレースから作成することもできます: UI でトレースを選択 → "Add to Dataset"

ステップ 4: 評価

データセットに対してチェーンを実行し、結果をスコアリングします。

from langsmith import evaluate

# ターゲット関数 (チェーン、エージェント、または任意の呼び出し可能オブジェクト)
def my_app(inputs: dict) -> dict:
    result = chain.invoke(inputs)
    return {"answer": result}

# カスタム評価器
def correctness(run, example) -> dict:
    """Check if the answer matches expected output."""
    predicted = run.outputs["answer"]
    expected = example.outputs["answer"]
    score = 1.0 if expected.lower() in predicted.lower() else 0.0
    return {"key": "correctness", "score": score}

def conciseness(run, example) -> dict:
    """Penalize overly long answers."""
    answer = run.outputs["answer"]
    word_count = len(answer.split())
    score = 1.0 if word_count < 100 else max(0, 1.0 - (word_count - 100) / 200)
    return {"key": "conciseness", "score": score}

# 評価を実行します
results = evaluate(
    my_app,
    data="customer-support-qa",  # データセット名
    evaluators=[correctness, conciseness],
    experiment_prefix="gpt4o-v2",
    max_concurrency=4,
)

# 結果は、スコア、比較、およびドリルダウンとともに LangSmith UI に表示されます

LLM をジャッジとして使用する評価器の場合は、0〜1 のスケールで品質を評価するために LLM を呼び出す関数を作成します。一貫性を保つために temperature=0 を使用します。ペアごとの比較の場合は、evaluate_comparative を使用して、2 つの実験実行を並べて比較します。

ステップ 5: プロンプトハブとアノテーションキュー

hub.pull("rlm/rag-prompt") を使用して共有プロンプトを取得し、hub.push("my-org/support-prompt", my_prompt) を使用して独自のプロンプトをバージョン管理します。アノテーションキューを使用すると、ヒューマンレビューワークフローを設定できます — client.create_annotation_queue() でキューを作成し、UI でトレースをフィルタリングして、スコアの低いものをレビューに送信します。

ステップ 6: 本番環境のモニタリング

# トレースをフィルタリングして分析します
runs = client.list_runs(
    project_name="production",
    filter='and(eq(status, "error"), gt(latency, 5))',
    limit=50,
)

for run in runs:
    print(f"Run {run.id}: {run.error} | Latency: {run.total_time}s | Tokens: {run.total_tokens}")

LangSmith ダッシュボードで、自動化ルールを設定して、実行速度の遅いものを自動的にフラグ付けし、スコアの低い応答をアノテーションキューに送信し、エラー率の急上昇時にアラートを送信します。

ステップ 7: CI/CD でのテスト

CI で評価を実行し、最小品質スコアをアサートします。

def test_qa_quality():
    results = evaluate(my_app, data="regression-test-set", evaluators=[correctness])
    avg_score = sum(r["evaluation_results"]["results"][0].score for r in results) / len(results)
    assert avg_score >= 0.85, f"Quality dropped to {avg_score:.2f}"

例 1: 既存の RAG チャットボットにトレーシングと評価を追加する

ユーザープロンプト: 「当社の HR ポリシーに関する質問に答える LangChain RAG チャットボットがあります。LangSmith トレーシングを追加し、回答が正しく簡潔であるかどうかをチェックする評価パイプラインを作成してください。」

エージェントは、すべてのチェーン呼び出しのために LANGCHAIN_TRACING_V2=true および LANGCHAIN_API_KEY 環境変数を設定します。

(原文はここで切り詰められています)

📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

LangSmith

Overview

LangSmith is the observability and evaluation platform for LLM applications. It traces every step of your chains and agents, helps you build evaluation datasets, run automated quality checks, and monitor production performance. Essential for moving LLM apps from prototype to production.

Instructions

Step 1: Setup and Configuration

Create a LangSmith account at smith.langchain.com and get an API key.

pip install langsmith

Set environment variables:

export LANGCHAIN_TRACING_V2=true
export LANGCHAIN_API_KEY="lsv2_pt_..."
export LANGCHAIN_PROJECT="my-project"  # Optional, defaults to "default"

Once set, all LangChain calls are automatically traced — no code changes needed.

For non-LangChain code, use the SDK directly:

from langsmith import Client
client = Client()

Step 2: Tracing

Automatic Tracing (LangChain)

With LANGCHAIN_TRACING_V2=true, every .invoke(), .stream(), .batch() call is traced automatically. Each trace shows:

  • Input/output at every step
  • Token usage and cost
  • Latency per component
  • Error details with full stack traces

Manual Tracing with @traceable

For custom functions outside LangChain:

from langsmith import traceable

@traceable(name="process_order", tags=["production"])
def process_order(order_id: str, items: list) -> dict:
    # Your business logic
    validated = validate_items(items)
    summary = generate_summary(validated)  # LLM call
    return {"order_id": order_id, "summary": summary, "status": "processed"}

@traceable
def validate_items(items: list) -> list:
    # Nested traces automatically link to parent
    return [item for item in items if item["quantity"] > 0]

Tracing with Context Manager

from langsmith import trace

with trace("data-pipeline", inputs={"source": "csv"}) as run:
    data = load_data("input.csv")
    processed = transform(data)
    run.end(outputs={"rows": len(processed)})

Metadata and Tags

# Add metadata to any LangChain call
result = chain.invoke(
    {"question": "..."},
    config={
        "metadata": {"user_id": "u-123", "environment": "staging"},
        "tags": ["beta-test", "gpt4"]
    }
)

Step 3: Datasets and Examples

Datasets are collections of input/output pairs used for evaluation:

from langsmith import Client

client = Client()

# Create a dataset
dataset = client.create_dataset("customer-support-qa", description="Real support questions with expected answers")

# Add examples
client.create_examples(
    inputs=[
        {"question": "How do I reset my password?"},
        {"question": "What's your refund policy?"},
    ],
    outputs=[
        {"answer": "Go to Settings > Security > Reset Password"},
        {"answer": "Full refund within 30 days, no questions asked"},
    ],
    dataset_id=dataset.id,
)
# Also create from existing traces: in the UI, select traces → "Add to Dataset"

Step 4: Evaluation

Run your chain against a dataset and score the results:

from langsmith import evaluate

# Your target function (chain, agent, or any callable)
def my_app(inputs: dict) -> dict:
    result = chain.invoke(inputs)
    return {"answer": result}

# Custom evaluator
def correctness(run, example) -> dict:
    """Check if the answer matches expected output."""
    predicted = run.outputs["answer"]
    expected = example.outputs["answer"]
    score = 1.0 if expected.lower() in predicted.lower() else 0.0
    return {"key": "correctness", "score": score}

def conciseness(run, example) -> dict:
    """Penalize overly long answers."""
    answer = run.outputs["answer"]
    word_count = len(answer.split())
    score = 1.0 if word_count < 100 else max(0, 1.0 - (word_count - 100) / 200)
    return {"key": "conciseness", "score": score}

# Run evaluation
results = evaluate(
    my_app,
    data="customer-support-qa",  # dataset name
    evaluators=[correctness, conciseness],
    experiment_prefix="gpt4o-v2",
    max_concurrency=4,
)

# Results visible in LangSmith UI with scores, comparisons, and drill-down

For LLM-as-judge evaluators, create a function that calls an LLM to rate quality on a 0-1 scale. Use temperature=0 for consistency. For pairwise comparisons, use evaluate_comparative to compare two experiment runs side by side.

Step 5: Prompt Hub and Annotation Queues

Use hub.pull("rlm/rag-prompt") to fetch shared prompts and hub.push("my-org/support-prompt", my_prompt) to version your own. Annotation queues let you set up human review workflows — create a queue with client.create_annotation_queue(), then filter traces in the UI and send low-scoring ones for review.

Step 7: Production Monitoring

# Filter and analyze traces
runs = client.list_runs(
    project_name="production",
    filter='and(eq(status, "error"), gt(latency, 5))',
    limit=50,
)

for run in runs:
    print(f"Run {run.id}: {run.error} | Latency: {run.total_time}s | Tokens: {run.total_tokens}")

In the LangSmith dashboard, set up automation rules to auto-flag slow runs, send low-score responses to annotation queues, and alert on error rate spikes.

Step 8: Testing in CI/CD

Run evaluations in CI and assert minimum quality scores:

def test_qa_quality():
    results = evaluate(my_app, data="regression-test-set", evaluators=[correctness])
    avg_score = sum(r["evaluation_results"]["results"][0].score for r in results) / len(results)
    assert avg_score >= 0.85, f"Quality dropped to {avg_score:.2f}"

Examples

Example 1: Add tracing and evaluation to an existing RAG chatbot

User prompt: "I have a LangChain RAG chatbot answering questions about our HR policies. Add LangSmith tracing and create an evaluation pipeline that checks if answers are correct and concise."

The agent will set the LANGCHAIN_TRACING_V2=true and LANGCHAIN_API_KEY environment variables so all chain invocations are automatically traced. It will then create a LangSmith dataset called hr-policy-qa with 10-15 real question/answer pairs drawn from common employee queries. Next, it will write two evaluators — a correctness evaluator that checks whether the expected answer appears in the predicted output, and a conciseness evaluator that penalizes answers over 100 words. Finally, it will wire up evaluate() to run the chatbot against the dataset with both evaluators and print a summary of scores.

Example 2: Monitor production agent and alert on regressions

User prompt: "Our customer support agent is in production. Set up LangSmith monitoring to track error rates and latency, and add a CI test that fails if answer quality drops below 90%."

The agent will configure the production project in LangSmith with metadata tags for environment: production and service: support-agent. It will write a monitoring script using client.list_runs() with filters for error status and high latency (over 5 seconds), outputting a summary of total tokens, average latency, and error count. Then it will create a regression-test-set dataset from recent production traces and write a pytest test that runs evaluate() against it, asserting the average correctness score stays at or above 0.90.

Guidelines

  1. Always enable tracing in dev — set LANGCHAIN_TRACING_V2=true from day one
  2. Use projects to organize — separate dev, staging, production traces
  3. Build datasets from production — real data makes the best test sets
  4. Start with simple evaluators — exact match and contains before LLM judges
  5. Run evals on every PR — catch regressions before they ship
  6. Use annotation queues — human review builds trust and better datasets
  7. Tag everything — metadata makes filtering and analysis possible
  8. Monitor cost — track token usage per user/feature to control spend
  9. Compare experiments — A/B test prompts and models systematically
  10. Version prompts in Hub — never lose a prompt that worked well

Common Pitfalls

  • Forgetting to set env vars: No tracing without LANGCHAIN_TRACING_V2=true
  • Huge traces: Logging full documents in metadata slows the UI — summarize or truncate
  • Evaluator flakiness: LLM judges are non-deterministic — use temperature=0 and run multiple times
  • Not separating projects: Dev traces mixed with production makes analysis impossible
  • Ignoring latency data: Tracing overhead is minimal (<5ms) — the latency insights are worth it