---
title: Tools definieren
url: https://platform.claude.com/docs/de/agents-and-tools/tool-use/define-tools
description: Lege Tool-Schemas fest, schreibe effektive Beschreibungen und steuere, wann Claude deine Tools aufruft.
---

## Voraussetzungen

* Vertrautheit mit der [Übersicht zur Tool-Nutzung](https://platform.claude.com/docs/de/agents-and-tools/tool-use/overview)
* Ein Claude API-Key und ein funktionierendes SDK- oder cURL-Setup

<Tip>
  Wenn du Claude mit „tool use“ (Tool-Nutzung) und Thinking verwendest, findest du unter [Thinking](https://platform.claude.com/docs/de/build-with-claude/thinking) weitere Informationen.
</Tip>

## Client-Tools festlegen

Client-Tools werden im Top-Level-Parameter `tools` der API-Anfrage angegeben. Client-Tools mit Anthropic-Schema, wie das Bash- und das Texteditor-Tool, werden über einen datumsversionierten `type` deklariert; die jeweils akzeptierten Felder findest du auf der Seite des jeweiligen Tools, die in der [Tool-Referenz](https://platform.claude.com/docs/de/agents-and-tools/tool-use/tool-reference) verlinkt ist. Die Tools für Computer Use und Browser Use sind [Client-Toolsets](https://platform.claude.com/docs/de/agents-and-tools/tool-use/tool-reference#client-toolsets): ein einzelner Eintrag ohne `name`, der einen festen Satz von Mitglieds-Tools deklariert. Eine benutzerdefinierte Tool-Definition umfasst:

| Parameter        | Beschreibung                                                                                                                                                                                                                                                                    |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name`           | Der Name des Tools. Muss dem regulären Ausdruck `^[a-zA-Z0-9_-]{1,128}$` entsprechen.                                                                                                                                                                                           |
| `description`    | Eine detaillierte Klartextbeschreibung dessen, was das Tool tut, wann es verwendet werden sollte und wie es sich verhält.                                                                                                                                                       |
| `input_schema`   | Ein [JSON Schema](https://json-schema.org/)-Objekt, das die erwarteten Parameter für das Tool definiert.                                                                                                                                                                        |
| `input_examples` | (Optional) Ein Array von Beispiel-Eingabeobjekten, die Claude helfen zu verstehen, wie das Tool zu verwenden ist. Siehe [Beispiele für die Tool-Nutzung bereitstellen](https://platform.claude.com/docs/de/agents-and-tools/tool-use/define-tools#providing-tool-use-examples). |

Den vollständigen Satz optionaler Eigenschaften, die für jede einzelne Tool-Definition verfügbar sind, einschließlich `cache_control`, `strict`, `defer_loading` und `allowed_callers`, findest du in der [Tool-Referenz](https://platform.claude.com/docs/de/agents-and-tools/tool-use/tool-reference#tool-definition-properties). Ein Client-Toolset-Eintrag akzeptiert `cache_control` und `allowed_callers` auf dem Eintrag und setzt `defer_loading` pro Mitglied; siehe [Client-Toolsets](https://platform.claude.com/docs/de/agents-and-tools/tool-use/tool-reference#client-toolsets).

<Accordion title="Beispiel einer einfachen Tool-Definition">
  ```json JSON
  {
    "name": "get_weather",
    "description": "Get the current weather in a given location",
    "input_schema": {
      "type": "object",
      "properties": {
        "location": {
          "type": "string",
          "description": "The city and state, e.g. San Francisco, CA"
        },
        "unit": {
          "type": "string",
          "enum": ["celsius", "fahrenheit"],
          "description": "The unit of temperature, either 'celsius' or 'fahrenheit'"
        }
      },
      "required": ["location"]
    }
  }
  ```

  Dieses Tool mit dem Namen `get_weather` erwartet ein Eingabeobjekt mit einem erforderlichen String `location` und einem optionalen String `unit`, der entweder "celsius" oder "fahrenheit" sein muss.
</Accordion>

### System-Prompt für die Tool-Nutzung

Wenn du die Claude API mit dem Parameter `tools` aufrufst, erstellt die API einen speziellen „system prompt“ (System-Prompt) aus den Tool-Definitionen, der Tool-Konfiguration und einem etwaigen vom Benutzer angegebenen System-Prompt. Der erstellte Prompt ist darauf ausgelegt, das Modell anzuweisen, das bzw. die angegebenen Tools zu verwenden, und den notwendigen Kontext bereitzustellen, damit das Tool ordnungsgemäß funktioniert:

```text wrap
In this environment you have access to a set of tools you can use to answer the user's question.
{{ FORMATTING INSTRUCTIONS }}
String and scalar parameters should be specified as is, while lists and objects should use JSON format. Note that spaces for string values are not stripped. The output is not expected to be valid XML and is parsed with regular expressions.
Here are the functions available in JSONSchema format:
{{ TOOL DEFINITIONS IN JSON SCHEMA }}
{{ USER SYSTEM PROMPT }}
{{ TOOL CONFIGURATION }}
```

### Best Practices für Tool-Definitionen

Um bei der Verwendung von Tools die beste Leistung aus Claude herauszuholen, befolge diese Richtlinien:

* **Stelle äußerst detaillierte Beschreibungen bereit.** Dies ist mit Abstand der wichtigste Faktor für die Tool-Leistung. Deine Beschreibungen sollten jedes Detail des Tools erklären, einschließlich:

  * Was das Tool tut
  * Wann es verwendet werden sollte (und wann nicht)
  * Was jeder Parameter bedeutet und wie er das Verhalten des Tools beeinflusst
  * Alle wichtigen Einschränkungen oder Grenzen, etwa welche Informationen das Tool nicht zurückgibt, wenn der Tool-Name unklar ist. Je mehr Kontext du Claude über deine Tools gibst, desto besser kann es bestimmen, wann und wie sie zu verwenden sind. Strebe mindestens 3–4 Sätze pro Tool-Beschreibung an, bei komplexen Tools mehr.

* **Priorisiere Beschreibungen, ziehe aber für komplexe Tools `input_examples` in Betracht.** Klare Beschreibungen sind am wichtigsten, aber für Tools mit komplexen Eingaben, verschachtelten Objekten oder formatsensiblen Parametern kannst du das Feld `input_examples` verwenden, um schemavalidierte Beispiele bereitzustellen. Details findest du unter [Beispiele für die Tool-Nutzung bereitstellen](https://platform.claude.com/docs/de/agents-and-tools/tool-use/define-tools#providing-tool-use-examples).

* **Fasse verwandte Operationen in weniger Tools zusammen.** Anstatt für jede Aktion ein separates Tool zu erstellen (`create_pr`, `review_pr`, `merge_pr`), gruppiere sie in einem einzigen Tool mit einem `action`-Parameter. Weniger, dafür leistungsfähigere Tools verringern die Mehrdeutigkeit bei der Auswahl und machen deine Tool-Oberfläche für Claude leichter navigierbar.

* **Verwende aussagekräftige Namensräume in Tool-Namen.** Wenn deine Tools mehrere Dienste oder Ressourcen umfassen, stelle den Namen den Dienst voran (zum Beispiel `github_list_prs`, `slack_send_message`). Das macht die Tool-Auswahl eindeutig, wenn deine Bibliothek wächst, und ist besonders wichtig bei der Verwendung der [Tool-Suche](https://platform.claude.com/docs/de/agents-and-tools/tool-use/tool-search-tool).

* **Gestalte Tool-Antworten so, dass sie nur Informationen mit hohem Signalgehalt zurückgeben.** Gib semantische, stabile Bezeichner (zum Beispiel Slugs oder UUIDs) statt undurchsichtiger interner Referenzen zurück und schließe nur die Felder ein, die Claude benötigt, um über seinen nächsten Schritt nachzudenken. Aufgeblähte Antworten verschwenden Kontext und erschweren es Claude, das Wesentliche herauszufiltern.

* **Bitte um eine Erklärung, nicht um eine Begründungskette.** Wenn ein Parameter Claude fragt, warum es den Aufruf tätigt, bitte um eine kurze Erklärung oder die stützenden Belege. Ein Parameter, der nach dem Nachdenken des Modells oder einer schrittweisen Begründung fragt, kann zu einer `reasoning_extraction`-Ablehnung führen. Siehe [Reasoning in Thinking-Blöcken belassen](https://platform.claude.com/docs/de/build-with-claude/refusals-and-fallback#keep-reasoning-in-thinking-blocks).

<AccordionGroup>
  <Accordion title="Beispiel einer guten Tool-Beschreibung">
    ```json JSON
    {
      "name": "get_stock_price",
      "description": "Retrieves the current stock price for a given ticker symbol. The ticker symbol must be a valid symbol for a publicly traded company on a major US stock exchange like NYSE or NASDAQ. The tool will return the latest trade price in USD. It should be used when the user asks about the current or most recent price of a specific stock. It will not provide any other information about the stock or company.",
      "input_schema": {
        "type": "object",
        "properties": {
          "ticker": {
            "type": "string",
            "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
          }
        },
        "required": ["ticker"]
      }
    }
    ```
  </Accordion>

  <Accordion title="Beispiel einer schlechten Tool-Beschreibung">
    ```json JSON
    {
      "name": "get_stock_price",
      "description": "Gets the stock price for a ticker.",
      "input_schema": {
        "type": "object",
        "properties": {
          "ticker": {
            "type": "string"
          }
        },
        "required": ["ticker"]
      }
    }
    ```
  </Accordion>
</AccordionGroup>

Die gute Beschreibung erklärt klar, was das Tool tut, wann es verwendet werden soll, welche Daten es zurückgibt und was der Parameter `ticker` bedeutet. Die schlechte Beschreibung ist zu kurz und lässt für Claude viele offene Fragen zum Verhalten und zur Verwendung des Tools.

<Tip>
  Ausführlichere Hinweise zum Tool-Design (Zusammenfassung, Benennung und Gestaltung von Antworten) findest du unter [Writing tools for agents](https://www.anthropic.com/engineering/writing-tools-for-agents).
</Tip>

## Beispiele für die Tool-Nutzung bereitstellen

Du kannst konkrete Beispiele gültiger Tool-Eingaben bereitstellen, um Claude zu helfen, deine Tools effektiver zu verwenden. Dies ist besonders nützlich für komplexe Tools mit verschachtelten Objekten, optionalen Parametern oder formatsensiblen Eingaben.

### Grundlegende Verwendung

Füge deiner Tool-Definition ein optionales Feld `input_examples` mit einem Array von Beispiel-Eingabeobjekten hinzu. Jedes Beispiel muss gemäß dem `input_schema` des Tools gültig sein:

<CodeGroup>
  ```bash cURL
  curl -sS https://api.anthropic.com/v1/messages \
    -H "content-type: application/json" \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 1024,
      "tools": [
        {
          "name": "get_weather",
          "description": "Get the current weather in a given location",
          "input_schema": {
            "type": "object",
            "properties": {
              "location": {
                "type": "string",
                "description": "The city and state, e.g. San Francisco, CA"
              },
              "unit": {
                "type": "string",
                "enum": ["celsius", "fahrenheit"],
                "description": "The unit of temperature"
              }
            },
            "required": ["location"]
          },
          "input_examples": [
            {"location": "San Francisco, CA", "unit": "fahrenheit"},
            {"location": "Tokyo, Japan", "unit": "celsius"},
            {"location": "New York, NY"}
          ]
        }
      ],
      "messages": [
        {"role": "user", "content": "What is the weather like in San Francisco?"}
      ]
    }'
  ```

  ```bash CLI
  ant messages create <<'YAML'
  model: claude-opus-5-5
  max_tokens: 1024
  tools:
    - name: get_weather
      description: Get the current weather in a given location
      input_schema:
        type: object
        properties:
          location:
            type: string
            description: The city and state, e.g. San Francisco, CA
          unit:
            type: string
            enum: [celsius, fahrenheit]
            description: The unit of temperature
        required: [location]
      input_examples:
        - location: San Francisco, CA
          unit: fahrenheit
        - location: Tokyo, Japan
          unit: celsius
        - location: New York, NY  # 'unit' is optional
  messages:
    - role: user
      content: What's the weather like in San Francisco?
  YAML
  ```

  ```python Python
  client = anthropic.Anthropic()

  response = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=1024,
      tools=[
          {
              "name": "get_weather",
              "description": "Get the current weather in a given location",
              "input_schema": {
                  "type": "object",
                  "properties": {
                      "location": {
                          "type": "string",
                          "description": "The city and state, e.g. San Francisco, CA",
                      },
                      "unit": {
                          "type": "string",
                          "enum": ["celsius", "fahrenheit"],
                          "description": "The unit of temperature",
                      },
                  },
                  "required": ["location"],
              },
              "input_examples": [
                  {"location": "San Francisco, CA", "unit": "fahrenheit"},
                  {"location": "Tokyo, Japan", "unit": "celsius"},
                  {
                      "location": "New York, NY"  # 'unit' is optional
                  },
              ],
          }
      ],
      messages=[{"role": "user", "content": "What's the weather like in San Francisco?"}],
  )

  print(response)
  ```

  ```typescript TypeScript
  const client = new Anthropic();

  const response = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 1024,
    tools: [
      {
        name: "get_weather",
        description: "Get the current weather in a given location",
        input_schema: {
          type: "object",
          properties: {
            location: {
              type: "string",
              description: "The city and state, e.g. San Francisco, CA"
            },
            unit: {
              type: "string",
              enum: ["celsius", "fahrenheit"],
              description: "The unit of temperature"
            }
          },
          required: ["location"]
        },
        input_examples: [
          {
            location: "San Francisco, CA",
            unit: "fahrenheit"
          },
          {
            location: "Tokyo, Japan",
            unit: "celsius"
          },
          {
            location: "New York, NY"
            // Zeigt, dass 'unit' optional ist
          }
        ]
      }
    ],
    messages: [{ role: "user", content: "What's the weather like in San Francisco?" }]
  });

  console.log(response);
  ```

  ```csharp C#
  AnthropicClient client = new();

  var parameters = new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 1024,
      Tools = [
          new ToolUnion(new Tool()
          {
              Name = "get_weather",
              Description = "Get the current weather in a given location",
              InputSchema = new InputSchema()
              {
                  Properties = new Dictionary<string, JsonElement>
                  {
                      ["location"] = JsonSerializer.SerializeToElement(new { type = "string", description = "The city and state, e.g. San Francisco, CA" }),
                      ["unit"] = JsonSerializer.SerializeToElement(new { type = "string", @enum = new[] { "celsius", "fahrenheit" }, description = "The unit of temperature" }),
                  },
                  Required = ["location"],
              },
              InputExamples =
              [
                  new Dictionary<string, JsonElement>()
                  {
                      { "location", JsonSerializer.SerializeToElement("San Francisco, CA") },
                      { "unit", JsonSerializer.SerializeToElement("fahrenheit") },
                  },
                  new Dictionary<string, JsonElement>()
                  {
                      { "location", JsonSerializer.SerializeToElement("Tokyo, Japan") },
                      { "unit", JsonSerializer.SerializeToElement("celsius") },
                  },
                  new Dictionary<string, JsonElement>()
                  {
                      { "location", JsonSerializer.SerializeToElement("New York, NY") },
                  },
              ],
          }),
      ],
      Messages = [
          new() { Role = Role.User, Content = "What's the weather like in San Francisco?" }
      ]
  };

  var message = await client.Messages.Create(parameters);
  Console.WriteLine(message);
  ```

  ```go Go
  client := anthropic.NewClient()

  response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 1024,
  	Tools: []anthropic.ToolUnionParam{
  		{OfTool: &anthropic.ToolParam{
  			Name:        "get_weather",
  			Description: anthropic.String("Get the current weather in a given location"),
  			InputSchema: anthropic.ToolInputSchemaParam{
  				Properties: map[string]any{
  					"location": map[string]any{
  						"type":        "string",
  						"description": "The city and state, e.g. San Francisco, CA",
  					},
  					"unit": map[string]any{
  						"type":        "string",
  						"enum":        []string{"celsius", "fahrenheit"},
  						"description": "The unit of temperature",
  					},
  				},
  				Required: []string{"location"},
  			},
  			InputExamples: []map[string]any{
  				{
  					"location": "San Francisco, CA",
  					"unit":     "fahrenheit",
  				},
  				{
  					"location": "Tokyo, Japan",
  					"unit":     "celsius",
  				},
  				{
  					"location": "New York, NY",
  					// Zeigt, dass 'unit' optional ist
  				},
  			},
  		}},
  	},
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("What's the weather like in San Francisco?")),
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(response.RawJSON())
  ```

  ```java Java
  import com.anthropic.models.messages.Tool;
  import com.anthropic.models.messages.Tool.InputSchema;
  // ...
  void main() {
      AnthropicClient client = AnthropicOkHttpClient.fromEnv();

      MessageCreateParams params = MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(1024L)
          .addTool(Tool.builder()
              .name("get_weather")
              .description("Get the current weather in a given location")
              .inputSchema(InputSchema.builder()
                  .properties(JsonValue.from(Map.of(
                      "location", Map.of(
                          "type", "string",
                          "description", "The city and state, e.g. San Francisco, CA"
                      ),
                      "unit", Map.of(
                          "type", "string",
                          "enum", List.of("celsius", "fahrenheit"),
                          "description", "The unit of temperature"
                      )
                  )))
                  .required(List.of("location"))
                  .build())
              .putAdditionalProperty("input_examples", JsonValue.from(List.of(
                  Map.of(
                      "location", "San Francisco, CA",
                      "unit", "fahrenheit"
                  ),
                  Map.of(
                      "location", "Tokyo, Japan",
                      "unit", "celsius"
                  ),
                  Map.of(
                      "location", "New York, NY"
                  )
              )))
              .build())
          .addUserMessage("What's the weather like in San Francisco?")
          .build();

      Message response = client.messages().create(params);
      IO.println(response);
  }
  ```

  ```php PHP
  $client = new Client();

  $message = $client->messages->create(
      maxTokens: 1024,
      messages: [
          ['role' => 'user', 'content' => "What's the weather like in San Francisco?"]
      ],
      model: 'claude-opus-5-5',
      tools: [
          [
              'name' => 'get_weather',
              'description' => 'Get the current weather in a given location',
              'input_schema' => [
                  'type' => 'object',
                  'properties' => [
                      'location' => [
                          'type' => 'string',
                          'description' => 'The city and state, e.g. San Francisco, CA'
                      ],
                      'unit' => [
                          'type' => 'string',
                          'enum' => ['celsius', 'fahrenheit'],
                          'description' => 'The unit of temperature'
                      ]
                  ],
                  'required' => ['location']
              ],
              'input_examples' => [
                  [
                      'location' => 'San Francisco, CA',
                      'unit' => 'fahrenheit'
                  ],
                  [
                      'location' => 'Tokyo, Japan',
                      'unit' => 'celsius'
                  ],
                  [
                      'location' => 'New York, NY'
                  ]
              ]
          ]
      ],
  );
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  message = client.messages.create(
    model: "claude-opus-5-5",
    max_tokens: 1024,
    tools: [
      {
        name: "get_weather",
        description: "Get the current weather in a given location",
        input_schema: {
          type: "object",
          properties: {
            location: {
              type: "string",
              description: "The city and state, e.g. San Francisco, CA"
            },
            unit: {
              type: "string",
              enum: ["celsius", "fahrenheit"],
              description: "The unit of temperature"
            }
          },
          required: ["location"]
        },
        input_examples: [
          {
            location: "San Francisco, CA",
            unit: "fahrenheit"
          },
          {
            location: "Tokyo, Japan",
            unit: "celsius"
          },
          {
            location: "New York, NY"
          }
        ]
      }
    ],
    messages: [
      { role: "user", content: "What's the weather like in San Francisco?" }
    ]
  )
  puts message
  ```
</CodeGroup>

Beispiele werden zusammen mit deinem Tool-Schema in den Prompt aufgenommen und zeigen Claude konkrete Muster für wohlgeformte Tool-Aufrufe. Das hilft Claude zu verstehen, wann optionale Parameter einzuschließen sind, welche Formate zu verwenden sind und wie komplexe Eingaben zu strukturieren sind.

### Anforderungen und Einschränkungen

* **Schemavalidierung** - Jedes Beispiel muss gemäß dem `input_schema` des Tools gültig sein. Ungültige Beispiele geben einen 400-Fehler zurück
* **Nicht unterstützt für serverseitige Tools oder Client-Toolsets** - Eingabebeispiele funktionieren bei benutzerdefinierten Tools und Client-Tools mit Anthropic-Schema mit Ausnahme der Toolsets für [Computer Use](https://platform.claude.com/docs/de/agents-and-tools/tool-use/computer-use-tool) und [Browser Use](https://platform.claude.com/docs/de/agents-and-tools/tool-use/browser-use-tool), jedoch nicht bei Server-Tools wie Websuche oder Codeausführung
* **Token-Kosten** - Beispiele erhöhen die Prompt-Token: \~20–50 Token für einfache Beispiele, \~100–200 Token für komplexe verschachtelte Objekte

## Claudes Ausgabe steuern

### Tool-Nutzung erzwingen

In manchen Fällen möchtest du vielleicht, dass Claude ein bestimmtes Tool verwendet, um die Frage des Benutzers zu beantworten, selbst wenn Claude andernfalls direkt antworten würde, ohne ein Tool aufzurufen. Das erreichst du, indem du das Tool im Feld `tool_choice` der Anfrage angibst.

Nicht jedes Modell und jede Einstellung unterstützt erzwungene Tool-Nutzung. Wo sie nicht unterstützt wird, schlagen `tool_choice: {"type": "any"}` und `tool_choice: {"type": "tool", "name": "..."}` fehl, während `tool_choice: {"type": "auto"}` (der Standard) und `tool_choice: {"type": "none"}` weiterhin funktionieren:

| Modell oder Einstellung                                                                                                                      | Einschränkung                                                                                                                  | Was du stattdessen verwenden kannst                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| -------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Manuelles [erweitertes Nachdenken](https://platform.claude.com/docs/de/build-with-claude/extended-thinking) (`thinking: {type: "enabled"}`)  | `any` und `tool` werden nicht unterstützt und führen zu einem Fehler                                                           | `auto` oder `none`. [Adaptives Nachdenken](https://platform.claude.com/docs/de/build-with-claude/thinking) selbst blockiert erzwungene Tool-Nutzung nicht (Modelle mit standardmäßig aktiviertem Nachdenken, wie Claude Opus 5 und Claude Haiku 5.5, akzeptieren sie, aber ein erzwungener Aufruf überspringt das Nachdenken: Die Antwort beginnt mit dem Tool-Aufruf und enthält keinen `thinking`-Block); die Modelle in der nächsten Zeile lehnen erzwungene Tool-Nutzung unabhängig von den Nachdenk-Einstellungen ab |
| Claude Opus 5.5, Claude Sonnet 5.5, Claude Fable 5.1 und [Claude Mythos 5.1](https://platform.claude.com/docs/de/models/mythos-5-1/overview) | `any` und `tool` geben einen [400-Fehler](https://platform.claude.com/docs/de/api/errors#forced-tool-use-not-supported) zurück | `auto` mit [strikter Tool-Nutzung](https://platform.claude.com/docs/de/agents-and-tools/tool-use/strict-tool-use), um schemavalide Tool-Eingaben zu garantieren, oder [strukturierte Ausgaben](https://platform.claude.com/docs/de/build-with-claude/structured-outputs), wenn du eine Antwort in einer festen JSON-Form benötigst. Prompting beeinflusst weiterhin, welches Tool `auto` auswählt. `none` wird ebenfalls unterstützt                                                                                      |

Bei Modellen, die dies unterstützen, sind die hervorgehobenen Zeilen der einzige Unterschied zu einer Standardanfrage mit Tool-Nutzung:

<CodeGroup>
  ```bash cURL
  curl -sS https://api.anthropic.com/v1/messages \
    -H "content-type: application/json" \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -d '{
      "model": "claude-opus-5",
      "max_tokens": 1024,
      "tools": [
        {
          "name": "get_weather",
          "description": "Get the current weather in a given location",
          "input_schema": {
            "type": "object",
            "properties": {
              "location": {
                "type": "string",
                "description": "The city and state, e.g. San Francisco, CA"
              }
            },
            "required": ["location"]
          }
        }
      ],
      "tool_choice": {"type": "tool", "name": "get_weather"},
      "messages": [
        {"role": "user", "content": "What is the weather like in San Francisco?"}
      ]
    }'
  ```

  ```bash CLI
  ant messages create <<'YAML'
  model: claude-opus-5
  max_tokens: 1024
  tools:
    - name: get_weather
      description: Get the current weather in a given location
      input_schema:
        type: object
        properties:
          location:
            type: string
            description: The city and state, e.g. San Francisco, CA
        required: [location]
  tool_choice:
    type: tool
    name: get_weather
  messages:
    - role: user
      content: What's the weather like in San Francisco?
  YAML
  ```

  ```python Python
  client = anthropic.Anthropic()

  tools = [
      {
          "name": "get_weather",
          "description": "Get the current weather in a given location",
          "input_schema": {
              "type": "object",
              "properties": {
                  "location": {
                      "type": "string",
                      "description": "The city and state, e.g. San Francisco, CA",
                  }
              },
              "required": ["location"],
          },
      }
  ]

  response = client.messages.create(
      model="claude-opus-5",
      max_tokens=1024,
      tools=tools,
      tool_choice={"type": "tool", "name": "get_weather"},
      messages=[{"role": "user", "content": "What's the weather like in San Francisco?"}],
  )

  print(response)
  ```

  ```typescript TypeScript
  const client = new Anthropic();

  const response = await client.messages.create({
    model: "claude-opus-5",
    max_tokens: 1024,
    tools: [
      {
        name: "get_weather",
        description: "Get the current weather in a given location",
        input_schema: {
          type: "object",
          properties: {
            location: {
              type: "string",
              description: "The city and state, e.g. San Francisco, CA"
            }
          },
          required: ["location"]
        }
      }
    ],
    tool_choice: { type: "tool", name: "get_weather" },
    messages: [{ role: "user", content: "What's the weather like in San Francisco?" }]
  });

  console.log(response);
  ```

  ```csharp C#
  AnthropicClient client = new();

  var parameters = new MessageCreateParams
  {
      Model = Model.ClaudeOpus5,
      MaxTokens = 1024,
      Tools = [
          new ToolUnion(new Tool()
          {
              Name = "get_weather",
              Description = "Get the current weather in a given location",
              InputSchema = new InputSchema()
              {
                  Properties = new Dictionary<string, JsonElement>
                  {
                      ["location"] = JsonSerializer.SerializeToElement(new { type = "string", description = "The city and state, e.g. San Francisco, CA" }),
                  },
                  Required = ["location"],
              },
          }),
      ],
      ToolChoice = new ToolChoiceTool { Name = "get_weather" },
      Messages = [
          new() { Role = Role.User, Content = "What's the weather like in San Francisco?" }
      ]
  };

  var message = await client.Messages.Create(parameters);
  Console.WriteLine(message);
  ```

  ```go Go
  client := anthropic.NewClient()

  response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5,
  	MaxTokens: 1024,
  	Tools: []anthropic.ToolUnionParam{
  		{OfTool: &anthropic.ToolParam{
  			Name:        "get_weather",
  			Description: anthropic.String("Get the current weather in a given location"),
  			InputSchema: anthropic.ToolInputSchemaParam{
  				Properties: map[string]any{
  					"location": map[string]any{
  						"type":        "string",
  						"description": "The city and state, e.g. San Francisco, CA",
  					},
  				},
  				Required: []string{"location"},
  			},
  		}},
  	},
  	ToolChoice: anthropic.ToolChoiceUnionParam{OfTool: &anthropic.ToolChoiceToolParam{Name: "get_weather"}},
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("What's the weather like in San Francisco?")),
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(response.RawJSON())
  ```

  ```java Java
  import com.anthropic.models.messages.Tool;
  import com.anthropic.models.messages.Tool.InputSchema;
  import com.anthropic.models.messages.ToolChoice;
  import com.anthropic.models.messages.ToolChoiceTool;
  // ...
  void main() {
      AnthropicClient client = AnthropicOkHttpClient.fromEnv();

      MessageCreateParams params = MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5)
          .maxTokens(1024L)
          .addTool(Tool.builder()
              .name("get_weather")
              .description("Get the current weather in a given location")
              .inputSchema(InputSchema.builder()
                  .properties(JsonValue.from(Map.of(
                      "location", Map.of(
                          "type", "string",
                          "description", "The city and state, e.g. San Francisco, CA"
                      )
                  )))
                  .required(List.of("location"))
                  .build())
              .build())
          .toolChoice(ToolChoice.ofTool(ToolChoiceTool.builder()
              .name("get_weather")
              .build()))
          .addUserMessage("What's the weather like in San Francisco?")
          .build();

      Message response = client.messages().create(params);
      IO.println(response);
  }
  ```

  ```php PHP
  $client = new Client();

  $message = $client->messages->create(
      maxTokens: 1024,
      messages: [
          ['role' => 'user', 'content' => "What's the weather like in San Francisco?"]
      ],
      model: 'claude-opus-5',
      toolChoice: ['type' => 'tool', 'name' => 'get_weather'],
      tools: [
          [
              'name' => 'get_weather',
              'description' => 'Get the current weather in a given location',
              'input_schema' => [
                  'type' => 'object',
                  'properties' => [
                      'location' => [
                          'type' => 'string',
                          'description' => 'The city and state, e.g. San Francisco, CA'
                      ]
                  ],
                  'required' => ['location']
              ]
          ]
      ],
  );
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  message = client.messages.create(
    model: "claude-opus-5",
    max_tokens: 1024,
    tools: [
      {
        name: "get_weather",
        description: "Get the current weather in a given location",
        input_schema: {
          type: "object",
          properties: {
            location: {
              type: "string",
              description: "The city and state, e.g. San Francisco, CA"
            }
          },
          required: ["location"]
        }
      }
    ],
    tool_choice: { type: "tool", name: "get_weather" },
    messages: [
      { role: "user", content: "What's the weather like in San Francisco?" }
    ]
  )
  puts message
  ```
</CodeGroup>

Bei der Arbeit mit dem Parameter `tool_choice` gibt es vier mögliche Optionen:

* `auto` erlaubt Claude zu entscheiden, ob es eines der bereitgestellten Tools aufruft oder nicht. Dies ist der Standardwert, wenn `tools` bereitgestellt werden.
* `any` teilt Claude mit, dass es eines der bereitgestellten Tools verwenden muss, erzwingt aber kein bestimmtes Tool.
* `tool` zwingt Claude, immer ein bestimmtes Tool zu verwenden.
* `none` verhindert, dass Claude Tools verwendet. Dies ist der Standardwert, wenn keine `tools` bereitgestellt werden.

<Note>
  Bei der Verwendung von [Prompt-Caching](https://platform.claude.com/docs/de/build-with-claude/prompt-caching#what-invalidates-the-cache) machen Änderungen am Parameter `tool_choice` zwischengespeicherte Nachrichtenblöcke ungültig. Tool-Definitionen und System-Prompts bleiben zwischengespeichert, aber Nachrichteninhalte müssen erneut verarbeitet werden.
</Note>

Dieses Diagramm veranschaulicht, wie jede Option funktioniert:

<Frame>
  ![Diagramm der drei tool\_choice-Optionen: auto (ein Tool oder eine reine Antwort), any (eines der Tools) und tool (das benannte Tool)](https://platform.claude.com/docs/de/images/tool_choice.svg)
</Frame>

Beachte, dass die API bei `tool_choice` mit dem Wert `any` oder `tool` die Assistant-Nachricht vorab befüllt, um die Verwendung eines Tools zu erzwingen. Das bedeutet, dass die Modelle vor `tool_use`-Inhaltsblöcken keine natürlichsprachliche Antwort oder Erklärung ausgeben, selbst wenn sie ausdrücklich dazu aufgefordert werden.

Tests haben gezeigt, dass dies die Leistung nicht verringern sollte. Wenn du möchtest, dass das Modell natürlichsprachlichen Kontext oder Erklärungen liefert und dennoch ein bestimmtes Tool verwendet, kannst du `{"type": "auto"}` für `tool_choice` (den Standard) verwenden und explizite Anweisungen in einer `user`-Nachricht hinzufügen. Zum Beispiel: `What's the weather like in London? Use the get_weather tool in your response.`

Das Erzwingen eines Tools überspringt außerdem bei jedem Modell, das erzwungene Tool-Nutzung akzeptiert, das Nachdenken: Die Antwort beginnt mit dem `tool_use`-Block und enthält keinen `thinking`-Block. Damit das Modell nachdenken kann, bevor es das Tool aufruft, verwende auf dieselbe Weise `auto` mit einer Anweisung im Prompt.

<Tip>
  **Garantierte Tool-Aufrufe mit strikten Tools**

  Kombiniere bei Modellen, die erzwungene Tool-Nutzung unterstützen, `tool_choice: {"type": "any"}` mit [strikter Tool-Nutzung](https://platform.claude.com/docs/de/agents-and-tools/tool-use/strict-tool-use), um sowohl zu garantieren, dass eines deiner Tools aufgerufen wird, als auch, dass die Tool-Eingaben strikt deinem Schema folgen. Setze `strict: true` in deinen Tool-Definitionen, um die Schemavalidierung zu aktivieren.
</Tip>

### Modellantworten mit Tools

Bei der Verwendung von Tools kommentiert Claude häufig, was es gerade tut, oder antwortet dem Benutzer auf natürliche Weise, bevor es Tools aufruft.

Bei dem Prompt „What's the weather like in San Francisco right now, and what time is it there?“ könnte Claude zum Beispiel so antworten:

```json JSON
{
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "I'll help you check the current weather and time in San Francisco."
    },
    {
      "type": "tool_use",
      "id": "toolu_01A09q90qw90lq917835lq9",
      "name": "get_weather",
      "input": { "location": "San Francisco, CA" }
    }
  ]
}
```

Dieser natürliche Antwortstil hilft Benutzern zu verstehen, was Claude tut, und schafft eine gesprächsähnlichere Interaktion. Du kannst Stil und Inhalt dieser Antworten über deine System-Prompts und durch die Bereitstellung von `<examples>` in deinen Prompts steuern.

Es ist wichtig zu beachten, dass Claude beim Erklären seiner Aktionen verschiedene Formulierungen und Ansätze verwenden kann. Dein Code sollte diese Antworten wie jeden anderen vom Assistant generierten Text behandeln und sich nicht auf bestimmte Formatierungskonventionen verlassen.

## Nächste Schritte

<CardGroup>
  <Card href="https://platform.claude.com/docs/de/agents-and-tools/tool-use/handle-tool-calls" title="Tool-Aufrufe verarbeiten">
    Parse tool\_use-Blöcke und formatiere tool\_result-Antworten.
  </Card>

  <Card href="https://platform.claude.com/docs/de/agents-and-tools/tool-use/tool-runner" title="Tool Runner (SDK)">
    Lass das SDK die agentische Schleife automatisch übernehmen.
  </Card>

  <Card href="https://platform.claude.com/docs/de/agents-and-tools/tool-use/tool-reference" title="Tool-Referenz">
    Verzeichnis der von Anthropic bereitgestellten Tools und optionalen Eigenschaften.
  </Card>
</CardGroup>
