---
title: Definire gli strumenti
url: https://platform.claude.com/docs/it/agents-and-tools/tool-use/define-tools
description: Specifica gli schemi degli strumenti, scrivi descrizioni efficaci e controlla quando Claude chiama i tuoi strumenti.
---

## Prerequisiti

* Familiarità con la [panoramica sull'uso degli strumenti](https://platform.claude.com/docs/it/agents-and-tools/tool-use/overview)
* Una chiave API di Claude e una configurazione funzionante dell'SDK o di cURL

<Tip>
  Se usi Claude con l'uso degli strumenti e il ragionamento, consulta [Ragionamento](https://platform.claude.com/docs/it/build-with-claude/thinking) per maggiori informazioni.
</Tip>

## Specificare gli strumenti client

Gli strumenti client vengono specificati nel parametro di primo livello `tools` della richiesta API. Gli strumenti client con schema Anthropic, come gli strumenti bash ed editor di testo, vengono dichiarati tramite un `type` con versione datata; consulta la pagina di ciascuno strumento, collegata dal [Riferimento degli strumenti](https://platform.claude.com/docs/it/agents-and-tools/tool-use/tool-reference), per i campi che accetta. Gli strumenti computer use e browser use sono [toolset client](https://platform.claude.com/docs/it/agents-and-tools/tool-use/tool-reference#client-toolsets): una singola voce senza `name` che dichiara un insieme fisso di strumenti membri. Una definizione di strumento definita dall'utente include:

| Parametro        | Descrizione                                                                                                                                                                                                                                                          |
| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name`           | Il nome dello strumento. Deve corrispondere alla regex `^[a-zA-Z0-9_-]{1,128}$`.                                                                                                                                                                                     |
| `description`    | Una descrizione dettagliata in testo semplice di cosa fa lo strumento, quando dovrebbe essere usato e come si comporta.                                                                                                                                              |
| `input_schema`   | Un oggetto [JSON Schema](https://json-schema.org/) che definisce i parametri attesi per lo strumento.                                                                                                                                                                |
| `input_examples` | (Facoltativo) Un array di oggetti di input di esempio per aiutare Claude a capire come usare lo strumento. Consulta [Fornire esempi di uso degli strumenti](https://platform.claude.com/docs/it/agents-and-tools/tool-use/define-tools#providing-tool-use-examples). |

Per l'insieme completo delle proprietà opzionali disponibili su qualsiasi singola definizione di strumento, incluse `cache_control`, `strict`, `defer_loading` e `allowed_callers`, consulta il [Riferimento degli strumenti](https://platform.claude.com/docs/it/agents-and-tools/tool-use/tool-reference#tool-definition-properties). Una voce di toolset client accetta `cache_control` e `allowed_callers` sulla voce e imposta `defer_loading` per ciascun membro; consulta [Toolset client](https://platform.claude.com/docs/it/agents-and-tools/tool-use/tool-reference#client-toolsets).

<Accordion title="Esempio di definizione di strumento semplice">
  ```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"]
    }
  }
  ```

  Questo strumento, chiamato `get_weather`, si aspetta un oggetto di input con una stringa `location` obbligatoria e una stringa `unit` opzionale che deve essere "celsius" o "fahrenheit".
</Accordion>

### Prompt di sistema per l'uso degli strumenti

Quando chiami la Claude API con il parametro `tools`, l'API costruisce uno speciale "system prompt" (prompt di sistema) a partire dalle definizioni degli strumenti, dalla configurazione degli strumenti e da qualsiasi prompt di sistema specificato dall'utente. Il prompt costruito è progettato per istruire il modello a usare lo strumento o gli strumenti specificati e fornire il contesto necessario affinché lo strumento funzioni correttamente:

```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 practice per le definizioni degli strumenti

Per ottenere le migliori prestazioni da Claude quando usi gli strumenti, segui queste linee guida:

* **Fornisci descrizioni estremamente dettagliate.** Questo è di gran lunga il fattore più importante per le prestazioni degli strumenti. Le tue descrizioni dovrebbero spiegare ogni dettaglio dello strumento, tra cui:

  * Cosa fa lo strumento
  * Quando dovrebbe essere usato (e quando no)
  * Cosa significa ciascun parametro e come influisce sul comportamento dello strumento
  * Eventuali avvertenze o limitazioni importanti, ad esempio quali informazioni lo strumento non restituisce se il nome dello strumento non è chiaro. Più contesto riesci a dare a Claude sui tuoi strumenti, meglio saprà determinare quando e come usarli. Punta ad almeno 3–4 frasi per ciascuna descrizione di strumento, di più se lo strumento è complesso.

* **Dai priorità alle descrizioni, ma considera l'uso di `input_examples` per strumenti complessi.** Descrizioni chiare sono la cosa più importante, ma per strumenti con input complessi, oggetti annidati o parametri sensibili al formato, puoi usare il campo `input_examples` per fornire esempi validati rispetto allo schema. Consulta [Fornire esempi di uso degli strumenti](https://platform.claude.com/docs/it/agents-and-tools/tool-use/define-tools#providing-tool-use-examples) per i dettagli.

* **Consolida le operazioni correlate in meno strumenti.** Invece di creare uno strumento separato per ogni azione (`create_pr`, `review_pr`, `merge_pr`), raggruppale in un singolo strumento con un parametro `action`. Strumenti meno numerosi e più capaci riducono l'ambiguità nella selezione e rendono la tua superficie di strumenti più facile da navigare per Claude.

* **Usa un namespacing significativo nei nomi degli strumenti.** Quando i tuoi strumenti coprono più servizi o risorse, anteponi ai nomi il servizio (ad esempio, `github_list_prs`, `slack_send_message`). Questo rende la selezione degli strumenti non ambigua man mano che la tua libreria cresce, ed è particolarmente importante quando usi la [ricerca degli strumenti](https://platform.claude.com/docs/it/agents-and-tools/tool-use/tool-search-tool).

* **Progetta le risposte degli strumenti in modo che restituiscano solo informazioni ad alto segnale.** Restituisci identificatori semantici e stabili (ad esempio, slug o UUID) invece di riferimenti interni opachi, e includi solo i campi di cui Claude ha bisogno per ragionare sul passo successivo. Risposte gonfiate sprecano contesto e rendono più difficile per Claude estrarre ciò che conta.

* **Chiedi una spiegazione, non il ragionamento.** Se un parametro chiede a Claude perché sta effettuando la chiamata, chiedi una breve spiegazione o le prove a supporto. Un parametro che chiede il ragionamento del modello o un ragionamento passo dopo passo può portare a un rifiuto `reasoning_extraction`. Consulta [Mantieni il ragionamento nei blocchi di ragionamento](https://platform.claude.com/docs/it/build-with-claude/refusals-and-fallback#keep-reasoning-in-thinking-blocks).

<AccordionGroup>
  <Accordion title="Esempio di una buona descrizione di strumento">
    ```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="Esempio di descrizione di strumento scadente">
    ```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>

La buona descrizione spiega chiaramente cosa fa lo strumento, quando usarlo, quali dati restituisce e cosa significa il parametro `ticker`. La descrizione scadente è troppo breve e lascia Claude con molte domande aperte sul comportamento e sull'utilizzo dello strumento.

<Tip>
  Per indicazioni più approfondite sulla progettazione degli strumenti (consolidamento, denominazione e modellazione delle risposte), consulta [Writing tools for agents](https://www.anthropic.com/engineering/writing-tools-for-agents).
</Tip>

## Fornire esempi di uso degli strumenti

Puoi fornire esempi concreti di input validi per gli strumenti per aiutare Claude a capire come usare i tuoi strumenti in modo più efficace. Questo è particolarmente utile per strumenti complessi con oggetti annidati, parametri opzionali o input sensibili al formato.

### Utilizzo di base

Aggiungi un campo opzionale `input_examples` alla definizione del tuo strumento con un array di oggetti di input di esempio. Ogni esempio deve essere valido secondo l'`input_schema` dello strumento:

<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"
            // Dimostra che 'unit' è facoltativo
          }
        ]
      }
    ],
    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",
  					// Dimostra che 'unit' è facoltativo
  				},
  			},
  		}},
  	},
  	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>

Gli esempi vengono inclusi nel prompt insieme allo schema del tuo strumento, mostrando a Claude pattern concreti di chiamate di strumenti ben formate. Questo aiuta Claude a capire quando includere parametri opzionali, quali formati usare e come strutturare input complessi.

### Requisiti e limitazioni

* **Validazione dello schema** - Ogni esempio deve essere valido secondo l'`input_schema` dello strumento. Esempi non validi restituiscono un errore 400
* **Non supportato per strumenti lato server o toolset client** - Gli esempi di input funzionano sugli strumenti client definiti dall'utente e con schema Anthropic diversi dai toolset [computer use](https://platform.claude.com/docs/it/agents-and-tools/tool-use/computer-use-tool) e [browser use](https://platform.claude.com/docs/it/agents-and-tools/tool-use/browser-use-tool), ma non sugli strumenti server come la ricerca web o l'esecuzione di codice
* **Costo in token** - Gli esempi si aggiungono ai token del prompt: \~20–50 token per esempi semplici, \~100–200 token per oggetti annidati complessi

## Controllare l'output di Claude

### Forzare l'uso degli strumenti

In alcuni casi, potresti volere che Claude usi uno strumento specifico per rispondere alla domanda dell'utente, anche se Claude altrimenti risponderebbe direttamente senza chiamare uno strumento. Puoi farlo specificando lo strumento nel campo `tool_choice` della richiesta.

Non tutti i modelli e le impostazioni supportano l'uso forzato degli strumenti. Dove non è supportato, `tool_choice: {"type": "any"}` e `tool_choice: {"type": "tool", "name": "..."}` falliscono, mentre `tool_choice: {"type": "auto"}` (il valore predefinito) e `tool_choice: {"type": "none"}` continuano a funzionare:

| Modello o impostazione                                                                                                                     | Restrizione                                                                                                                | Cosa usare invece                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| ------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Ragionamento esteso](https://platform.claude.com/docs/it/build-with-claude/extended-thinking) manuale (`thinking: {type: "enabled"}`)     | `any` e `tool` non sono supportati e generano un errore                                                                    | `auto` o `none`. Il [ragionamento adattivo](https://platform.claude.com/docs/it/build-with-claude/thinking) di per sé non blocca l'uso forzato degli strumenti (i modelli con il ragionamento attivo per impostazione predefinita, come Claude Opus 5 e Claude Haiku 5.5, lo accettano, ma una chiamata forzata salta il ragionamento: la risposta inizia con la chiamata allo strumento e non ha alcun blocco `thinking`); i modelli nella riga successiva rifiutano l'uso forzato degli strumenti indipendentemente dalle impostazioni di ragionamento |
| Claude Opus 5.5, Claude Sonnet 5.5, Claude Fable 5.1 e [Claude Mythos 5.1](https://platform.claude.com/docs/it/models/mythos-5-1/overview) | `any` e `tool` restituiscono un [errore 400](https://platform.claude.com/docs/it/api/errors#forced-tool-use-not-supported) | `auto` con l'[uso rigoroso degli strumenti](https://platform.claude.com/docs/it/agents-and-tools/tool-use/strict-tool-use) per garantire input degli strumenti validi rispetto allo schema, oppure gli [output strutturati](https://platform.claude.com/docs/it/build-with-claude/structured-outputs) quando hai bisogno di una risposta in una forma JSON fissa. Il prompt influenza comunque quale strumento sceglie `auto`. È supportato anche `none`                                                                                                 |

Sui modelli che lo supportano, le righe evidenziate sono l'unica differenza rispetto a una richiesta standard di uso degli strumenti:

<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>

Quando lavori con il parametro `tool_choice`, ci sono quattro opzioni possibili:

* `auto` consente a Claude di decidere se chiamare o meno uno qualsiasi degli strumenti forniti. Questo è il valore predefinito quando vengono forniti `tools`.
* `any` dice a Claude che deve usare uno degli strumenti forniti, ma non forza uno strumento in particolare.
* `tool` forza Claude a usare sempre uno strumento in particolare.
* `none` impedisce a Claude di usare qualsiasi strumento. Questo è il valore predefinito quando non vengono forniti `tools`.

<Note>
  Quando usi la [cache dei prompt](https://platform.claude.com/docs/it/build-with-claude/prompt-caching#what-invalidates-the-cache), le modifiche al parametro `tool_choice` invalideranno i blocchi di messaggi in cache. Le definizioni degli strumenti e i prompt di sistema rimangono in cache, ma il contenuto dei messaggi deve essere rielaborato.
</Note>

Questo diagramma illustra come funziona ciascuna opzione:

<Frame>
  ![Diagramma delle tre opzioni di tool\_choice: auto (uno strumento o una risposta semplice), any (uno degli strumenti) e tool (lo strumento indicato)](https://platform.claude.com/docs/it/images/tool_choice.svg)
</Frame>

Nota che quando hai `tool_choice` impostato su `any` o `tool`, l'API precompila il messaggio dell'assistente per forzare l'uso di uno strumento. Questo significa che i modelli non emetteranno una risposta o spiegazione in linguaggio naturale prima dei blocchi di contenuto `tool_use`, anche se viene chiesto esplicitamente di farlo.

I test hanno dimostrato che questo non dovrebbe ridurre le prestazioni. Se desideri che il modello fornisca contesto o spiegazioni in linguaggio naturale pur richiedendo che il modello usi uno strumento specifico, puoi usare `{"type": "auto"}` per `tool_choice` (il valore predefinito) e aggiungere istruzioni esplicite in un messaggio `user`. Ad esempio: `What's the weather like in London? Use the get_weather tool in your response.`

Forzare uno strumento salta anche il ragionamento su ogni modello che accetta l'uso forzato degli strumenti: la risposta inizia con il blocco `tool_use` e non ha alcun blocco `thinking`. Per consentire al modello di ragionare prima di chiamare lo strumento, usa `auto` con un'istruzione nel prompt allo stesso modo.

<Tip>
  **Chiamate di strumenti garantite con strumenti rigorosi**

  Sui modelli che supportano l'uso forzato degli strumenti, combina `tool_choice: {"type": "any"}` con l'[uso rigoroso degli strumenti](https://platform.claude.com/docs/it/agents-and-tools/tool-use/strict-tool-use) per garantire sia che uno dei tuoi strumenti venga chiamato sia che gli input dello strumento seguano rigorosamente il tuo schema. Imposta `strict: true` sulle definizioni dei tuoi strumenti per abilitare la validazione dello schema.
</Tip>

### Risposte del modello con gli strumenti

Quando usa gli strumenti, Claude spesso commenta ciò che sta facendo o risponde in modo naturale all'utente prima di chiamare gli strumenti.

Ad esempio, dato il prompt "What's the weather like in San Francisco right now, and what time is it there?", Claude potrebbe rispondere con:

```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" }
    }
  ]
}
```

Questo stile di risposta naturale aiuta gli utenti a capire cosa sta facendo Claude e crea un'interazione più conversazionale. Puoi guidare lo stile e il contenuto di queste risposte attraverso i tuoi prompt di sistema e fornendo `<examples>` nei tuoi prompt.

È importante notare che Claude può usare varie formulazioni e approcci quando spiega le sue azioni. Il tuo codice dovrebbe trattare queste risposte come qualsiasi altro testo generato dall'assistente, e non fare affidamento su convenzioni di formattazione specifiche.

## Prossimi passi

<CardGroup>
  <Card href="https://platform.claude.com/docs/it/agents-and-tools/tool-use/handle-tool-calls" title="Gestire le chiamate degli strumenti">
    Analizza i blocchi tool\_use e formatta le risposte tool\_result.
  </Card>

  <Card href="https://platform.claude.com/docs/it/agents-and-tools/tool-use/tool-runner" title="Tool Runner (SDK)">
    Lascia che l'SDK gestisca automaticamente il ciclo agentico.
  </Card>

  <Card href="https://platform.claude.com/docs/it/agents-and-tools/tool-use/tool-reference" title="Riferimento degli strumenti">
    Elenco degli strumenti forniti da Anthropic e delle proprietà opzionali.
  </Card>
</CardGroup>
