> This is a page from the ElevenLabs documentation. For an index of the documentation, fetch https://elevenlabs.io/docs/llms.txt.

# コードで管理するツール

## 概要

[ツール](/docs/ja/eleven-agents/customization/tools)は、パラメータ用のJSONスキーマをネストした設定として保存されます。この設定を手動で記述する場合、パスパラメータとURL、`required` リストとそのプロパティをそれぞれ一致させ、すべてのパラメータに値の取得元を1つだけ指定する必要があります。PythonおよびJavaScript SDKのツールビルダーを使うと、同じツールをメソッドチェーンで記述できます。その後、`tools.create()` と `tools.update()` がそのまま受け取れるリクエストが生成されます。

次の用途に使用できます。

* Webhook、クライアント、システムツールをコードで定義し、ほかのコード変更と同じようにレビューする。
* ツールを読み込み、ほかの設定を変えずにパラメータを1つ変更して反映する。
* ツールをJSONとしてバージョン管理に保存し、CIで検証する。

> **Note**
>
> ビルダーはSDK内だけで動作します。新しいAPIエンドポイントは呼び出しません。また、ビルダーで作成したものはすべて
> ダッシュボードで開いて編集できます。

## 要件

* Python：`elevenlabs` パッケージ。ビルダーは `elevenlabs.agent_tools` からインポートします。
* JavaScript：`@elevenlabs/elevenlabs-js` パッケージ。ビルダーはパッケージルートからエクスポートされます。

## Webhookツールを構築する

`Tool.webhook(name, description)` で[Webhookツール](/docs/ja/eleven-agents/customization/tools/webhook-tools)の作成を開始します。名前と説明は、ツールを呼び出すかどうかを判断するときにLLMが参照します。この例では、発信者が伝えた番号から注文を検索し、ワークスペースのシークレットからAPIキーを送信して、注文ステータスを動的変数に保存します。

```python
from elevenlabs import ElevenLabs
from elevenlabs.agent_tools import Header, Schema, Tool

elevenlabs = ElevenLabs()

get_order = (
    Tool.webhook("get_order", "Look up an order by the number the caller gives")
    .get("https://api.example.com/orders/{order_id}")
    .path_param("order_id", Schema.string().describe("The order number, e.g. A-1042"))
    .query_param("include", Schema.string().constant("items"))
    .header("Authorization", Header.secret("sec_orders_api"))
    .assign("order_status", "order.status")
    .options(response_timeout_secs=10)
)

tool = elevenlabs.conversational_ai.tools.create(request=get_order.build())
```

```typescript
import { ElevenLabsClient, Header, Schema, Tool } from "@elevenlabs/elevenlabs-js";

const elevenlabs = new ElevenLabsClient();

const getOrder = Tool.webhook("get_order", "Look up an order by the number the caller gives")
  .get("https://api.example.com/orders/{order_id}")
  .pathParam("order_id", Schema.string().describe("The order number, e.g. A-1042"))
  .queryParam("include", Schema.string().constant("items"))
  .header("Authorization", Header.secret("sec_orders_api"))
  .assign("order_status", "order.status")
  .options({ responseTimeoutSecs: 10 });

const tool = await elevenlabs.conversationalAi.tools.create(getOrder.build());
```

リクエストメソッドでは、HTTPメソッドとURLを設定します。URL内の `{name}` プレースホルダーには、パスパラメータの値が入ります。

| Python                                                           | JavaScript                 | 設定内容                                                                                                   |
| ---------------------------------------------------------------- | -------------------------- | ------------------------------------------------------------------------------------------------------ |
| `get(url)`, `post(url)`, `put(url)`, `patch(url)`, `delete(url)` | 同じ                         | メソッドとURL。`POST`、`PUT`、`PATCH` にはボディが必要です。`GET` にはボディを指定できません。                                          |
| `path_param(name, schema)`                                       | `pathParam(name, schema)`  | URL内の `{name}` プレースホルダーに対応するパスパラメータ。                                                                   |
| `query_param(name, schema)`                                      | `queryParam(name, schema)` | クエリパラメータ。                                                                                              |
| `body(schema)`                                                   | `body(schema)`             | リクエストボディ。オブジェクトスキーマである必要があります。                                                                         |
| `response(schema)`                                               | `response(schema)`         | レスポンスボディのスキーマ。オブジェクトスキーマである必要があります。                                                                    |
| `header(name, value)`                                            | `header(name, value)`      | リクエストヘッダー。[ヘッダーと認証](#headers-and-authentication)を参照してください。                                             |
| `auth(connection)`                                               | `auth(connection)`         | 使用する[認証接続](/docs/ja/eleven-agents/customization/tools/webhook-tools#supported-authentication-methods)。 |
| `assign(variable, path)`                                         | `assign(variable, path)`   | レスポンス内の `path`（ドット記法）にある値を動的変数に保存します。                                                                  |

すでに存在する名前のパラメータやヘッダーを設定すると、位置を維持したまま置き換えられます。`remove_path_param()`、`remove_query_param()`、`remove_header()`、`remove_assignment()`（JavaScriptでは `removePathParam()` など）を使うと削除できます。パラメータ名は、パス、クエリ、ボディ全体で一意である必要があります。

ボディは、プロパティを1つずつ追加して構築するオブジェクトスキーマです。

```python
refund = (
    Tool.webhook("issue_refund", "Refund an order the caller asked to return")
    .post("https://api.example.com/refunds")
    .body(
        Schema.object()
        .property("order_id", Schema.string().from_variable("order_id"))
        .property(
            "reason",
            Schema.string().describe("Why the caller wants a refund").choices(["damaged", "late", "other"]),
        )
        .property("note", Schema.string().describe("Anything else the caller said").optional())
    )
)
```

```typescript
const refund = Tool.webhook("issue_refund", "Refund an order the caller asked to return")
  .post("https://api.example.com/refunds")
  .body(
    Schema.object()
      .property("order_id", Schema.string().fromVariable("order_id"))
      .property(
        "reason",
        Schema.string()
          .describe("Why the caller wants a refund")
          .choices(["damaged", "late", "other"])
      )
      .property("note", Schema.string().describe("Anything else the caller said").optional())
  );
```

## パラメータスキーマ

`Schema` は、Webhookツールとクライアントツールで使用するパラメータスキーマを構築します。各メソッドは新しいスキーマを返し、呼び出し元のスキーマは変更しません。そのため、一度定義したスキーマを複数のツールで使用できます。

| コンストラクター                                                                  | 構築するもの                            |
| ------------------------------------------------------------------------- | --------------------------------- |
| `Schema.string()`, `Schema.integer()`, `Schema.number()`, `Schema.bool()` | リテラル値                             |
| `Schema.object()`                                                         | オブジェクト。`property()` でプロパティを追加します。 |
| `Schema.array(items)`                                                     | 要素が `items` スキーマに一致する配列           |

### 値の取得元

パラメータ、ボディ、レスポンススキーマ、オブジェクトや配列の内部など、どこに現れる場合でも、各リテラルには値の取得元を1つだけ指定する必要があります。オブジェクトや配列にも取得元を指定でき、その場合は値全体が提供されます。

| Python                | JavaScript           | 値                                                                                               |
| --------------------- | -------------------- | ----------------------------------------------------------------------------------------------- |
| `describe(text)`      | `describe(text)`     | `text` の指示に従ってLLMが提供します。                                                                        |
| `from_variable(name)` | `fromVariable(name)` | ツールの実行時に[動的変数](/docs/ja/eleven-agents/customization/personalization/dynamic-variables)から読み取ります。 |
| `constant(value)`     | `constant(value)`    | 常に `value` です。                                                                                  |
| `system_provided()`   | `systemProvided()`   | ツールの実行時にシステムが設定します。リテラルにのみ使用できます。                                                               |
| `omit()`              | `omit()`             | リクエストから除外します。任意プロパティにのみ使用できます。                                                                  |

オブジェクトまたは配列で `describe()` を使うと、LLM向けにコンテナを説明できます。各プロパティまたは要素には、引き続き個別の取得元が必要です。

### その他のスキーマメソッド

| Python                                            | JavaScript                                    | 動作                                                  |
| ------------------------------------------------- | --------------------------------------------- | --------------------------------------------------- |
| `optional()`                                      | `optional()`                                  | プロパティを任意にします。任意と指定しない限り、プロパティは必須です。                 |
| `choices(values)`                                 | `choices(values)`                             | 文字列を、LLMが選択する固定の値セットに制限します。                         |
| `allowed_from(variable)`                          | `allowedFrom(variable)`                       | LLMの値が動的変数に保持されたリスト内にない場合に拒否します。`describe()` が必要です。 |
| `property(name, schema)` / `without(name)`        | `property(name, schema)` / `without(name)`    | オブジェクトプロパティを追加、置換、削除します。置換したプロパティの位置は維持されます。        |
| `require_any_of(names)` / `require_all_of(names)` | `requireAnyOf(names)` / `requireAllOf(names)` | 任意プロパティのグループのうち、少なくとも1つまたはすべてを必須にします。               |

## ヘッダーと認証

ヘッダー値の取得元は4種類あります。機密情報にはシークレットまたは環境変数を使用し、ツール設定に値が表示されないようにしてください。

| コンストラクター                                         | ヘッダー値                                                                                  |
| ------------------------------------------------ | -------------------------------------------------------------------------------------- |
| `Header.value(text)`                             | 固定テキスト。                                                                                |
| `Header.secret(id)`                              | ワークスペースのシークレットストアにあるシークレット。                                                            |
| `Header.variable(name)`                          | ツールの実行時に読み取られる動的変数。                                                                    |
| `Header.env_var(label)` / `Header.envVar(label)` | 現在の環境に応じて解決される、ワークスペースの[環境変数](/docs/ja/eleven-agents/integrate/environment-variables)。 |

`AuthConnection.id(id)` は、IDを指定してワークスペースの認証接続を使用します。`AuthConnection.env_var(label)` / `AuthConnection.envVar(label)` は環境変数から認証接続を選択するため、同じツール設定で環境ごとに異なる接続を使用できます。

```python
from elevenlabs.agent_tools import AuthConnection, Header

update_profile = (
    Tool.webhook("update_profile", "Update the caller's email address")
    .put("https://api.example.com/profiles/{profile_id}")
    .path_param("profile_id", Schema.string().from_variable("profile_id"))
    .body(Schema.object().property("email", Schema.string().describe("The new email address")))
    .header("X-Api-Key", Header.env_var("profiles_api_key"))
    .auth(AuthConnection.env_var("profiles_oauth"))
)
```

```typescript
import { AuthConnection, Header } from "@elevenlabs/elevenlabs-js";

const updateProfile = Tool.webhook("update_profile", "Update the caller's email address")
  .put("https://api.example.com/profiles/{profile_id}")
  .pathParam("profile_id", Schema.string().fromVariable("profile_id"))
  .body(Schema.object().property("email", Schema.string().describe("The new email address")))
  .header("X-Api-Key", Header.envVar("profiles_api_key"))
  .auth(AuthConnection.envVar("profiles_oauth"));
```

## クライアントツールを構築する

`Tool.client(name, description)` で、サーバーではなくアプリケーション内で実行される[クライアントツール](/docs/ja/eleven-agents/customization/tools/client-tools)の作成を開始します。`param(name, schema)` でパラメータを追加します。エージェントがアプリケーションからの結果を待つ必要がある場合は、`expects_response` / `expectsResponse` を設定します。

```python
show_map = (
    Tool.client("show_store_map", "Show the caller a map of the nearest store")
    .param("store_id", Schema.string().describe("The store to show"))
    .options(expects_response=False)
)
```

```typescript
const showMap = Tool.client("show_store_map", "Show the caller a map of the nearest store")
  .param("store_id", Schema.string().describe("The store to show"))
  .options({ expectsResponse: false });
```

## システムツールを構築する

[システムツール](/docs/ja/eleven-agents/customization/tools/system-tools)はプラットフォームに組み込まれています。それぞれに `SystemTool` 上の専用コンストラクターがあり、各ツールの設定を受け取ります。

| Python                                                  | JavaScript                                            |
| ------------------------------------------------------- | ----------------------------------------------------- |
| `SystemTool.end_call()`                                 | `SystemTool.endCall()`                                |
| `SystemTool.skip_turn(wait_timeout_secs=...)`           | `SystemTool.skipTurn({ waitTimeoutSecs })`            |
| `SystemTool.language_detection(...)`                    | `SystemTool.languageDetection(options?)`              |
| `SystemTool.play_keypad_touch_tone(...)`                | `SystemTool.playKeypadTouchTone(options?)`            |
| `SystemTool.voicemail_detection(voicemail_message=...)` | `SystemTool.voicemailDetection({ voicemailMessage })` |
| `SystemTool.knowledge_base(enabled_strategies=...)`     | `SystemTool.knowledgeBase({ enabledStrategies })`     |
| `SystemTool.transfer_to_number(...)`                    | `SystemTool.transferToNumber(options?)`               |
| `SystemTool.transfer_to_agent()`                        | `SystemTool.transferToAgent()`                        |

2つの転送ツールでは、`transfer(condition, destination, options)` で転送先を指定します。条件はLLMに転送のタイミングを伝え、転送先には[コードで管理するワークフロー](/docs/ja/eleven-agents/customization/agents-as-code/workflows#transfer-destinations)と同じ `Destination` を使用します。SIP URIへの転送にはSIP REFER転送が必要です。

```python
from elevenlabs.agent_tools import SystemTool
from elevenlabs.agent_workflows import Destination

transfer = (
    SystemTool.transfer_to_number()
    .transfer("Caller asks for billing", Destination.phone("+15551234567"))
    .transfer("Caller is a reseller partner", Destination.sip("sip:partners@pbx.example.com"), transfer_type="sip_refer")
)

to_sales = SystemTool.transfer_to_agent().transfer(
    "Caller wants to buy something", Destination.agent("agent_sales"), transfer_message="Connecting you to sales"
)
```

```typescript
import { Destination, SystemTool } from "@elevenlabs/elevenlabs-js";

const transfer = SystemTool.transferToNumber()
  .transfer("Caller asks for billing", Destination.phone("+15551234567"))
  .transfer("Caller is a reseller partner", Destination.sip("sip:partners@pbx.example.com"), {
    transferType: "sip_refer",
  });

const toSales = SystemTool.transferToAgent().transfer(
  "Caller wants to buy something",
  Destination.agent("agent_sales"),
  { transferMessage: "Connecting you to sales" }
);
```

## ツールオプション

すべての種類のツールで共通する設定は `options()` に指定します。Pythonではキーワード引数、JavaScriptではオブジェクトを使用します。名前はAPIのツール設定フィールドと一致します。

| 適用対象       | Python                                                                                                                                       | JavaScript                                                                                                                          |
| ---------- | -------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| すべてのツール    | `name`, `description`, `response_timeout_secs`, `interruption_mode`, `pre_tool_speech`, `tool_call_sound`, `tool_error_handling_mode`, ...   | `name`, `description`, `responseTimeoutSecs`, `interruptionMode`, `preToolSpeech`, `toolCallSound`, `toolErrorHandlingMode`, ...    |
| Webhookツール | `execution_mode`, `content_type`, `response_filter`, `follow_redirects`, `follow_redirects_allowed_domains`, `dynamic_variable_placeholders` | `executionMode`, `contentType`, `responseFilter`, `followRedirects`, `followRedirectsAllowedDomains`, `dynamicVariablePlaceholders` |
| クライアントツール  | `execution_mode`, `expects_response`, `dynamic_variable_placeholders`                                                                        | `executionMode`, `expectsResponse`, `dynamicVariablePlaceholders`                                                                   |

Webhookツールのレスポンスタイムアウトは5～300秒です。クライアントツールでは1～120秒、または完了まで無期限に待機する場合は-1です。-1を指定するには `expects_response` / `expectsResponse` が必要です。`follow_redirects` / `followRedirects` には、許可するドメインのリストが必要です。

## ツールをエージェントに接続する

Webhookツールとクライアントツールは `tools.create()` で個別に作成し、IDでエージェントに接続します。そのため、1つのツールを複数のエージェントで共有できます。システムツールはエージェント設定の一部です。`build_config()` / `buildConfig()` は、エージェントの組み込みツール用エントリを返します。

```python
from elevenlabs import AgentConfig, BuiltInToolsOutput, ConversationalConfig, PromptAgentApiModelOutput

order_tool = elevenlabs.conversational_ai.tools.create(request=get_order.build())

agent = elevenlabs.conversational_ai.agents.create(
    name="Support line",
    conversation_config=ConversationalConfig(
        agent=AgentConfig(
            prompt=PromptAgentApiModelOutput(
                prompt="You are a support agent for Acme.",
                tool_ids=[order_tool.id],
                built_in_tools=BuiltInToolsOutput(
                    end_call=SystemTool.end_call().build_config(),
                    transfer_to_number=transfer.build_config(),
                ),
            )
        )
    ),
)
```

```typescript
const orderTool = await elevenlabs.conversationalAi.tools.create(getOrder.build());

const agent = await elevenlabs.conversationalAi.agents.create({
  name: "Support line",
  conversationConfig: {
    agent: {
      prompt: {
        prompt: "You are a support agent for Acme.",
        toolIds: [orderTool.id],
        builtInTools: {
          endCall: SystemTool.endCall().buildConfig(),
          transferToNumber: transfer.buildConfig(),
        },
      },
    },
  },
});
```

> **Warning**
>
> ツール設定をインラインで保持するエージェントの `prompt.tools` フィールドは非推奨です。`tool_ids` とは
> 併用できません。また、リクエストにこのフィールドを含めると、エージェントの組み込みツールが、そこに含まれる
> システムツールに置き換えられます。代わりに `tools.create()` でツールを作成し、IDで接続してください。

## 既存のツールを編集する

`Tool.from_response()` / `Tool.fromResponse()` は、`tools.get()` が返したツールを読み込みます。ビルダーがモデル化していないフィールドやAPIによって補完されるデフォルト値も保持されるため、再度反映したときに変更されるのは編集した部分だけです。`as_webhook()`、`as_client()`、`as_system()`（JavaScriptでは `asWebhook()` など）を使うと、編集用の型付きツールを取得できます。別の種類の場合は `None` / `undefined` が返されます。

ボディのプロパティを変更するには、ボディスキーマを読み取り、プロパティを再設定してからボディを設定します。

```python
from elevenlabs.agent_tools import ObjectSchema

loaded = Tool.from_response(elevenlabs.conversational_ai.tools.get("tool_id")).as_webhook()
if loaded is None:
    raise ValueError("Not a webhook tool")

body = loaded.body_schema
assert isinstance(body, ObjectSchema)
loaded.body(body.property("reason", Schema.string().describe("Why the caller wants a refund")))
loaded.query_param("locale", Schema.string().describe("The caller's language").optional())

elevenlabs.conversational_ai.tools.update("tool_id", request=loaded.build())
```

```typescript
import { type ObjectSchema, Schema, Tool } from "@elevenlabs/elevenlabs-js";

const loaded = Tool.fromResponse(
  await elevenlabs.conversationalAi.tools.get("tool_id")
).asWebhook();
if (!loaded) throw new Error("Not a webhook tool");

const body = loaded.bodySchema as ObjectSchema;
loaded.body(body.property("reason", Schema.string().describe("Why the caller wants a refund")));
loaded.queryParam("locale", Schema.string().describe("The caller's language").optional());

await elevenlabs.conversationalAi.tools.update("tool_id", loaded.build());
```

## ツールをバージョン管理に保存する

`to_json_string()` / `toJSONString()` は、APIの通信形式でツールを書き出します。キーはsnake_caseで、すべての階層で並べ替えられ、2スペースでインデントされます。これは[CLI](/docs/ja/eleven-agents/operate/cli)が `tool_configs/` ディレクトリに保持する形式と同じです。また、同じツールであれば両方のSDKがバイト単位で同一のファイルを書き出すため、差分を小さく保てます。`Tool.from_json()` / `Tool.fromJSON()` で再度読み込めます。

```python
from pathlib import Path

from elevenlabs.agent_tools import Tool

Path("tool_configs/get_order.json").write_text(get_order.to_json_string())

stored = Tool.from_json(Path("tool_configs/get_order.json").read_text())
elevenlabs.conversational_ai.tools.update("tool_id", request=stored.build())
```

```typescript
import { Tool } from "@elevenlabs/elevenlabs-js";
import { readFile, writeFile } from "node:fs/promises";

await writeFile("tool_configs/get_order.json", getOrder.toJSONString());

const stored = Tool.fromJSON(await readFile("tool_configs/get_order.json", "utf8"));
await elevenlabs.conversationalAi.tools.update("tool_id", stored.build());
```

一般的な構成は[ワークフロー](/docs/ja/eleven-agents/customization/agents-as-code/workflows#store-workflows-in-version-control)と同じです。`elevenlabs tools pull` でファイルを作成し、直接またはビルダーで編集します。すべてのプルリクエストに対してCIで `Tool.from_json(file).build()` / `Tool.fromJSON(file).build()` を実行し、マージ時に `tools.update()` または `elevenlabs tools push` で反映します。

## 検証

メソッドチェーンの呼び出し自体が失敗することはありません。`build()`、`build_config()` / `buildConfig()`、`to_json()` / `toJSON()`、`to_json_string()` / `toJSONString()` はツール全体をチェックし、単一の `ToolValidationError` を発生させます。その `issues` にはすべての問題が一覧表示され、各問題には `code`、`message`、および対象部分の `path`（`body.reason` など）が含まれます。

```python
from elevenlabs.agent_tools import ToolValidationError

try:
    request = refund.build()
except ToolValidationError as err:
    for issue in err.issues:
        print(issue.code, issue.path, issue.message)
```

```typescript
import { ToolValidationError } from "@elevenlabs/elevenlabs-js";

try {
  const request = refund.build();
} catch (err) {
  if (err instanceof ToolValidationError) {
    for (const issue of err.issues) console.error(issue.code, issue.path, issue.message);
  } else {
    throw err;
  }
}
```

エラーには次のものがあります。

* 対応するパスパラメータがないURLプレースホルダー、または対応するプレースホルダーがないパスパラメータ。`{{system__env_api_host}}` などの環境変数テンプレートはプレースホルダーではありません。
* 値の取得元がない、または複数あるリテラル。
* `GET` にボディがある、または `POST`、`PUT`、`PATCH` にボディがない。
* パス、クエリ、ボディのうち複数の場所で同じパラメータ名が使われている。
* 必須プロパティに `omit()` を使用している、文字列以外のスキーマに `choices()` を使用している、または定数がスキーマの型と一致しない。
* 転送先がない転送ツール、種類が正しくない転送先、またはSIP REFER転送を指定していないSIP URI転送先。
* ツールの種類に適用できないオプション、または範囲外のタイムアウト。

## SDKより新しいツールタイプ

APIまたはファイルから読み込んだツールが、MCPツールなど、ビルダーで編集できないタイプである場合があります。その場合、種類は `"other"` として読み込まれ、`from_json()` / `fromJSON()` と `to_json_string()` / `toJSONString()` を経由しても変更されません。また、`build()` は `on_warning` / `onWarning` を通じて警告として報告します。