Skip to content

ClasCat® AI Research

クラスキャット – AgentOS, AI エージェント, MCP, LangChain, AutoGen, AG2, Agno

Menu
  • ホーム
    • ClassCat® AI Research ホーム
    • クラスキャット・ホーム
  • OpenAI API
    • OpenAI Python ライブラリ 1.x : 概要
    • OpenAI ブログ
      • GPT の紹介
      • GPT ストアの紹介
      • ChatGPT Team の紹介
    • OpenAI platform 1.x
      • Get Started : イントロダクション
      • Get Started : クイックスタート (Python)
      • Get Started : クイックスタート (Node.js)
      • Get Started : モデル
      • 機能 : 埋め込み
      • 機能 : 埋め込み (ユースケース)
      • ChatGPT : アクション – イントロダクション
      • ChatGPT : アクション – Getting started
      • ChatGPT : アクション – アクション認証
    • OpenAI ヘルプ : ChatGPT
      • ChatGPTとは何ですか?
      • ChatGPT は真実を語っていますか?
      • GPT の作成
      • GPT FAQ
      • GPT vs アシスタント
      • GPT ビルダー
    • OpenAI ヘルプ : ChatGPT > メモリ
      • FAQ
    • OpenAI ヘルプ : GPT ストア
      • 貴方の GPT をフィーチャーする
    • OpenAI Python ライブラリ 0.27 : 概要
    • OpenAI platform
      • Get Started : イントロダクション
      • Get Started : クイックスタート
      • Get Started : モデル
      • ガイド : GPT モデル
      • ガイド : 画像生成 (DALL·E)
      • ガイド : GPT-3.5 Turbo 対応 微調整
      • ガイド : 微調整 1.イントロダクション
      • ガイド : 微調整 2. データセットの準備 / ケーススタディ
      • ガイド : 埋め込み
      • ガイド : 音声テキスト変換
      • ガイド : モデレーション
      • ChatGPT プラグイン : イントロダクション
    • OpenAI Cookbook
      • 概要
      • API 使用方法 : レート制限の操作
      • API 使用方法 : tiktoken でトークンを数える方法
      • GPT : ChatGPT モデルへの入力をフォーマットする方法
      • GPT : 補完をストリームする方法
      • GPT : 大規模言語モデルを扱う方法
      • 埋め込み : 埋め込みの取得
      • GPT-3 の微調整 : 分類サンプルの微調整
      • DALL-E : DALL·E で 画像を生成して編集する方法
      • DALL·E と Segment Anything で動的マスクを作成する方法
      • Whisper プロンプティング・ガイド
  • Gemini API
    • Tutorials : クイックスタート with Python (1) テキスト-to-テキスト生成
    • (2) マルチモーダル入力 / 日本語チャット
    • (3) 埋め込みの使用
    • (4) 高度なユースケース
    • クイックスタート with Node.js
    • クイックスタート with Dart or Flutter (1) 日本語動作確認
    • Gemma
      • 概要 (README)
      • Tutorials : サンプリング
      • Tutorials : KerasNLP による Getting Started
  • Keras 3
    • 新しいマルチバックエンド Keras
    • Keras 3 について
    • Getting Started : エンジニアのための Keras 入門
    • Google Colab 上のインストールと Stable Diffusion デモ
    • コンピュータビジョン – ゼロからの画像分類
    • コンピュータビジョン – 単純な MNIST convnet
    • コンピュータビジョン – EfficientNet を使用した微調整による画像分類
    • コンピュータビジョン – Vision Transformer による画像分類
    • コンピュータビジョン – 最新の MLPモデルによる画像分類
    • コンピュータビジョン – コンパクトな畳込み Transformer
    • Keras Core
      • Keras Core 0.1
        • 新しいマルチバックエンド Keras (README)
        • Keras for TensorFlow, JAX, & PyTorch
        • 開発者ガイド : Getting started with Keras Core
        • 開発者ガイド : 関数型 API
        • 開発者ガイド : シーケンシャル・モデル
        • 開発者ガイド : サブクラス化で新しい層とモデルを作成する
        • 開発者ガイド : 独自のコールバックを書く
      • Keras Core 0.1.1 & 0.1.2 : リリースノート
      • 開発者ガイド
      • Code examples
      • Keras Stable Diffusion
        • 概要
        • 基本的な使い方 (テキスト-to-画像 / 画像-to-画像変換)
        • 混合精度のパフォーマンス
        • インペインティングの簡易アプリケーション
        • (参考) KerasCV – Stable Diffusion を使用した高性能画像生成
  • TensorFlow
    • TF 2 : 初級チュートリアル
    • TF 2 : 上級チュートリアル
    • TF 2 : ガイド
    • TF 1 : チュートリアル
    • TF 1 : ガイド
  • その他
    • 🦜️🔗 LangChain ドキュメント / ユースケース
    • Stable Diffusion WebUI
      • Google Colab で Stable Diffusion WebUI 入門
      • HuggingFace モデル / VAE の導入
      • LoRA の利用
    • Diffusion Models / 拡散モデル
  • クラスキャット
    • 会社案内
    • お問合せ
    • Facebook
    • ClassCat® Blog
Menu

LangChain 1.0 α : コアコンポーネント – ツール

Posted on 09/24/202509/24/2025 by Masashi Okumura

一部のユースケースではモデルに、構造化入力を使用して API、データベース、ファイルシステムのような外部システムと直接連携することを要求します。
ツールは、エージェントがアクションを実行するために呼び出すコンポーネントです。

LangChain 1.0 alpha : コアコンポーネント – ツール

作成 : クラスキャット・セールスインフォメーション
作成日時 : 09/24/2025
バージョン : 1.0.0a6

* 本記事は docs.langchain.com の以下のページを独自に翻訳した上で、補足説明を加えてまとめ直しています。スニペットはできる限り日本語を使用しています :

  • LangChain OSS (v1-alpha) : Core Components – Tools

* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。

 

クラスキャット 人工知能 研究開発支援サービス ⭐️ リニューアルしました 😉

◆ クラスキャット は人工知能に関する各種サービスを提供しています。お気軽にご相談ください :

  • 人工知能導入個別相談会(無償)実施中! [詳細]

  • 人工知能研究開発支援 [詳細]
    1. 自社特有情報を含むチャットボット構築支援
    2. 画像認識 (医療系含む) / 画像生成

  • PoC(概念実証)を失敗させないための支援 [詳細]

◆ お問合せ : 下記までお願いします。

  • クラスキャット セールス・インフォメーション
  • sales-info@classcat.com
  • ClassCatJP

 

 

LangChain 1.0 alpha : コアコンポーネント – ツール

多くの AI アプリケーションは自然言語を介してユーザとやり取りします。けれども、一部のユースケースではモデルに、構造化入力を使用して API、データベース、ファイルシステムのような外部システムと直接連携することを要求します。

ツールは、エージェント がアクションを実行するために呼び出すコンポーネントです。それらは、うまく定義された入力と出力を通して世界とやり取りすることでモデル機能を拡張させます。ツールは呼び出し可能関数とその入力スキーマをカプセル化します。これらは互換性のある チャットモデル に渡され、モデルがツールを呼び出すかどうか、またどの引数で呼び出すかを決定することを可能にします。これらのシナリオでは、ツール呼び出しは、モデルが指定された入力スキーマに準拠したリクエストを生成することを可能にします。

 

ツールの作成

基本的なツール定義

ツールを作成する最も簡単な方法は @tool デコレータを使用することです。デフォルトでは、関数の docstring がツールの説明になり、モデルがいつそれを使用するか理解するのに役立ちます。
​

from langchain_core.tools import tool

@tool
def search_database(query: str, limit: int = 10) -> str:
    """Search the customer database for records matching the query.

    Args:
        query: Search terms to look for
        limit: Maximum number of results to return
    """
    return f"Found {limit} results for '{query}'"

型ヒントはツールの入力スキーマを定義するために 必須 です。docstring は、モデルがツールの目的を理解するのに役立つように、十分に情報が多く、かつ簡潔である必要があります。

 

ツール・プロパティのカスタマイズ

​

ツール名のカスタマイズ

​

デフォルトでは、ツール名は関数名に由来します。より説明的な名前が必要な場合にはオーバーライドできます :

@tool("web_search")  # Custom name
def search(query: str) -> str:
    """Search the web for information."""
    return f"Results for: {query}"

print(search.name)  # web_search

 

ツール説明のカスタマイズ

より明確なモデルガイダンスのために自動生成されたツール説明をオーバーライドできます :

@tool("calculator", description="Performs arithmetic calculations. Use this for any math problems.")
def calc(expression: str) -> str:
    """Evaluate mathematical expressions."""
    return str(eval(expression))

 

高度なスキーマ定義

Pydantic モデルや JSON スキーマを使用して複雑な入力を定義できます :

Pydantic model

from pydantic import BaseModel, Field
from typing import Literal

class WeatherInput(BaseModel):
    """Input for weather queries."""
    location: str = Field(description="City name or coordinates")
    units: Literal["celsius", "fahrenheit"] = Field(
        default="celsius",
        description="Temperature unit preference"
    )
    include_forecast: bool = Field(
        default=False,
        description="Include 5-day forecast"
    )

@tool(args_schema=WeatherInput)
def get_weather(location: str, units: str = "celsius", include_forecast: bool = False) -> str:
    """Get current weather and optional forecast."""
    temp = 22 if units == "celsius" else 72
    result = f"Current weather in {location}: {temp} degrees {units[0].upper()}"
    if include_forecast:
        result += "\nNext 5 days: Sunny"
    return result

JSON Schema

weather_schema = {
    "type": "object",
    "properties": {
        "location": {"type": "string"},
        "units": {"type": "string"},
        "include_forecast": {"type": "boolean"}
    },
    "required": ["location", "units", "include_forecast"]
}

@tool(args_schema=weather_schema)
def get_weather(location: str, units: str = "celsius", include_forecast: bool = False) -> str:
    """Get current weather and optional forecast."""
    temp = 22 if units == "celsius" else 72
    result = f"Current weather in {location}: {temp} degrees {units[0].upper()}"
    if include_forecast:
        result += "\nNext 5 days: Sunny"
    return result

 

エージェントでツールを使用する

エージェントは、推論ループ、状態管理、多段階実行を追加することで、単純なツールバインディングを超えた機能を提供できます。

Note : To see examples of how to use tools with agents, see Agents.

 

高度なツールパターン

​

ToolNode

ToolNode は事前構築済みの LangGraph コンポーネントで、エージェントのワークフロー内でツール呼び出しを処理します。create_agent() とシームレスに連携し、高度なツール実行制御、組み込みの並列処理、エラー処理を提供します。

 

構成設定オプション

ToolNode は以下のパラメータを受け取ります :
​

from langchain.agents import ToolNode

tool_node = ToolNode(
    tools=[...],              # List of tools or callables
    handle_tool_errors=True,  # Error handling configuration
    ...
)

tools – required

このノードが実行できるツールのリスト。以下を含めることができます :

  • LangChain @tool でデコレートされた関数

  • 適切な型ヒントと docstring を持つ呼び出し可能オブジェクト (e.g. 関数)

 
handle_tool_errors

ツール実行の失敗の処理方法を制御します。Can be :

  • bool
  • str
  • Callable[…, str]
  • type[Exception]
  • tuple[type[Exception], …]

Default: internal _default_handle_tool_errors

 

エラー処理ストラテジー

ToolNode は、handle_tool_errors プロパティを通してツール実行の組み込みエラー処理を提供します。

さまざまなエラー処理ストラテジーの使用方法の例 :

# Retry on all exception types with the default error message template string
tool_node = ToolNode(tools=[my_tool], handle_tool_errors=True)

# Retry on all exception types with a custom message string
tool_node = ToolNode(
    tools=[my_tool],
    handle_tool_errors="I encountered an issue. Please try rephrasing your request."
)

# Retry on ValueError with a custom message, otherwise raise
def handle_errors(e: ValueError) -> str:
    return "Invalid input provided"

tool_node = ToolNode([my_tool], handle_tool_errors=handle_errors)

# Retry on ValueError and KeyError with the default error message template string, otherwise raise
tool_node = ToolNode(
    tools=[my_tool],
    handle_tool_errors=(ValueError, KeyError)
)

 

create_agent() で使用する

Note : We recommend that you familiarize yourself with create_agent() before covering this section. Read more about agents.

構成設定済みの ToolNode を create_agent() に直接渡します :

from langchain_openai import ChatOpenAI
from langchain.agents import ToolNode, create_agent
import random

@tool
def fetch_user_data(user_id: str) -> str:
    """Fetch user data from database."""
    if random.random() > 0.7:
        raise ConnectionError("Database connection timeout")
    return f"User {user_id}: John Doe, john@example.com, Active"

@tool
def process_transaction(amount: float, user_id: str) -> str:
    """Process a financial transaction."""
    if amount > 10000:
        raise ValueError(f"Amount {amount} exceeds maximum limit of 10000")
    return f"Processed ${amount} for user {user_id}"

def handle_errors(e: Exception) -> str:
    if isinstance(e, ConnectionError):
        return "The database is currently overloaded, but it is safe to retry. Please try again with the same parameters."
    elif isinstance(e, ValueError):
        return f"Error: {e}. Try to process the transaction in smaller amounts."
    return f"Error: {e}. Please try again."

tool_node = ToolNode(
    tools=[fetch_user_data, process_transaction],
    handle_tool_errors=handle_errors
)

agent = create_agent(
    model=ChatOpenAI(model="gpt-4o"),
    tools=tool_node,
    prompt="You are a financial assistant."
)

agent.invoke({
    "messages": [{"role": "user", "content": "Process a payment of 15000 dollars for user123. Generate a receipt email and address it to the user."}]
})

 

以上



クラスキャット

最近の投稿

  • LangChain 1.0 α : コアコンポーネント – 短期メモリ
  • LangChain 1.0 α : コアコンポーネント – ツール
  • LangChain 1.0 α : コアコンポーネント – メッセージ
  • LangChain 1.0 α : コアコンポーネント – モデル
  • LangChain 1.0 α : コアコンポーネント – エージェント

タグ

AG2 (14) Agno (46) AutoGen (13) ClassCat Press Release (20) ClassCat TF/ONNX Hub (11) DGL 0.5 (14) Eager Execution (7) Edward (17) FLUX.1 (16) Gemini (20) HuggingFace Transformers 4.5 (10) HuggingFace Transformers 4.29 (9) Keras 2 Examples (98) Keras 2 Guide (16) Keras 3 (10) Keras Release Note (17) Kubeflow 1.0 (10) LangChain (45) LangGraph (24) LangGraph 0.5 (9) MediaPipe 0.8 (11) Model Context Protocol (16) NNI 1.5 (16) OpenAI Agents SDK (8) OpenAI Cookbook (13) OpenAI platform (10) OpenAI platform 1.x (10) OpenAI ヘルプ (8) TensorFlow 2.0 Advanced Tutorials (33) TensorFlow 2.0 Advanced Tutorials (Alpha) (15) TensorFlow 2.0 Advanced Tutorials (Beta) (16) TensorFlow 2.0 Guide (10) TensorFlow 2.0 Guide (Alpha) (16) TensorFlow 2.0 Guide (Beta) (9) TensorFlow 2.0 Release Note (12) TensorFlow 2.0 Tutorials (20) TensorFlow 2.0 Tutorials (Alpha) (14) TensorFlow 2.0 Tutorials (Beta) (12) TensorFlow 2.4 Guide (24) TensorFlow Deploy (8) TensorFlow Probability (9) TensorFlow Programmer's Guide (22) TensorFlow Release Note (18) TensorFlow Tutorials (33) TF-Agents 0.4 (11)
2025年9月
月 火 水 木 金 土 日
1234567
891011121314
15161718192021
22232425262728
2930  
« 8月    
© 2025 ClasCat® AI Research | Powered by Minimalist Blog WordPress Theme