Penggunaan tool dengan Claude
Claude mampu berinteraksi dengan tools dan fungsi, memungkinkan Anda memperluas kemampuan Claude untuk melakukan berbagai tugas yang lebih luas.
Berikut adalah contoh cara menyediakan tools kepada Claude menggunakan Messages API:
curl 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-sonnet-4-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"]
}
}
],
"messages": [
{
"role": "user",
"content": "What is the weather like in San Francisco?"
}
]
}'import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-sonnet-4-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"],
},
}
],
messages=[{"role": "user", "content": "What's the weather like in San Francisco?"}],
)
print(response)import { Anthropic } from '@anthropic-ai/sdk';
const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY
});
async function main() {
const response = await anthropic.messages.create({
model: "claude-sonnet-4-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"]
}
}],
messages: [{
role: "user",
content: "Tell me the weather in San Francisco."
}]
});
console.log(response);
}
main().catch(console.error);import java.util.List;
import java.util.Map;
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.core.JsonValue;
import com.anthropic.models.messages.Message;
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.Model;
import com.anthropic.models.messages.Tool;
import com.anthropic.models.messages.Tool.InputSchema;
public class GetWeatherExample {
public static void main(String[] args) {
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
InputSchema schema = InputSchema.builder()
.properties(JsonValue.from(Map.of(
"location",
Map.of(
"type", "string",
"description", "The city and state, e.g. San Francisco, CA"))))
.putAdditionalProperty("required", JsonValue.from(List.of("location")))
.build();
MessageCreateParams params = MessageCreateParams.builder()
.model(Model.CLAUDE_OPUS_4_0)
.maxTokens(1024)
.addTool(Tool.builder()
.name("get_weather")
.description("Get the current weather in a given location")
.inputSchema(schema)
.build())
.addUserMessage("What's the weather like in San Francisco?")
.build();
Message message = client.messages().create(params);
System.out.println(message);
}
}Cara kerja penggunaan tool
Claude mendukung dua jenis tools:
-
Client tools: Tools yang dieksekusi pada sistem Anda, yang meliputi:
- Tools kustom yang ditentukan pengguna yang Anda buat dan implementasikan
- Tools yang ditentukan Anthropic seperti computer use dan text editor yang memerlukan implementasi klien
-
Server tools: Tools yang dieksekusi pada server Anthropic, seperti tools web search dan web fetch. Tools ini harus ditentukan dalam permintaan API tetapi tidak memerlukan implementasi dari pihak Anda.
Tools yang ditentukan Anthropic menggunakan jenis berversi (misalnya, web_search_20250305, text_editor_20250124) untuk memastikan kompatibilitas di seluruh versi model.
Client tools
Integrasikan client tools dengan Claude dalam langkah-langkah berikut:
Berikan Claude tools dan prompt pengguna
- Tentukan client tools dengan nama, deskripsi, dan skema input dalam permintaan API Anda.
- Sertakan prompt pengguna yang mungkin memerlukan tools ini, misalnya, "Bagaimana cuaca di San Francisco?"
Claude memutuskan untuk menggunakan tool
- Claude menilai apakah ada tools yang dapat membantu dengan kueri pengguna.
- Jika ya, Claude membuat permintaan penggunaan tool yang diformat dengan benar.
- Untuk client tools, respons API memiliki
stop_reasonberupatool_use, menandakan niat Claude.
Eksekusi tool dan kembalikan hasil
- Ekstrak nama tool dan input dari permintaan Claude
- Eksekusi kode tool pada sistem Anda
- Kembalikan hasil dalam pesan
userbaru yang berisi blok kontentool_result
Claude menggunakan hasil tool untuk merumuskan respons
- Claude menganalisis hasil tool untuk menyusun respons akhirnya terhadap prompt pengguna asli.
Catatan: Langkah 3 dan 4 bersifat opsional. Untuk beberapa alur kerja, permintaan penggunaan tool Claude (langkah 2) mungkin sudah cukup, tanpa mengirim hasil kembali ke Claude.
Server tools
Server tools mengikuti alur kerja yang berbeda:
Berikan Claude tools dan prompt pengguna
- Server tools, seperti web search dan web fetch, memiliki parameter mereka sendiri.
- Sertakan prompt pengguna yang mungkin memerlukan tools ini, misalnya, "Cari berita terbaru tentang AI" atau "Analisis konten di URL ini."
Claude mengeksekusi server tool
- Claude menilai apakah server tool dapat membantu dengan kueri pengguna.
- Jika ya, Claude mengeksekusi tool, dan hasilnya secara otomatis dimasukkan ke dalam respons Claude.
Claude menggunakan hasil server tool untuk merumuskan respons
- Claude menganalisis hasil server tool untuk menyusun respons akhirnya terhadap prompt pengguna asli.
- Tidak diperlukan interaksi pengguna tambahan untuk eksekusi server tool.
Contoh penggunaan tool
Berikut adalah beberapa contoh kode yang mendemonstrasikan berbagai pola dan teknik penggunaan tool. Untuk singkatnya, tools yang digunakan adalah tools sederhana, dan deskripsi tool lebih pendek dari yang ideal untuk memastikan performa terbaik.
Harga
Tool use requests are priced based on:
- The total number of input tokens sent to the model (including in the
toolsparameter) - The number of output tokens generated
- For server-side tools, additional usage-based pricing (e.g., web search charges per search performed)
Client-side tools are priced the same as any other Claude API request, while server-side tools may incur additional charges based on their specific usage.
The additional tokens from tool use come from:
- The
toolsparameter in API requests (tool names, descriptions, and schemas) tool_usecontent blocks in API requests and responsestool_resultcontent blocks in API requests
When you use tools, we also automatically include a special system prompt for the model which enables tool use. The number of tool use tokens required for each model are listed below (excluding the additional tokens listed above). Note that the table assumes at least 1 tool is provided. If no tools are provided, then a tool choice of none uses 0 additional system prompt tokens.
| Model | Tool choice | Tool use system prompt token count |
|---|---|---|
| Claude Opus 4.1 | auto, noneany, tool | 346 tokens 313 tokens |
| Claude Opus 4 | auto, noneany, tool | 346 tokens 313 tokens |
| Claude Sonnet 4.5 | auto, noneany, tool | 346 tokens 313 tokens |
| Claude Sonnet 4 | auto, noneany, tool | 346 tokens 313 tokens |
| Claude Sonnet 3.7 (deprecated) | auto, noneany, tool | 346 tokens 313 tokens |
| Claude Haiku 4.5 | auto, noneany, tool | 346 tokens 313 tokens |
| Claude Haiku 3.5 | auto, noneany, tool | 264 tokens 340 tokens |
| Claude Opus 3 (deprecated) | auto, noneany, tool | 530 tokens 281 tokens |
| Claude Sonnet 3 | auto, noneany, tool | 159 tokens 235 tokens |
| Claude Haiku 3 | auto, noneany, tool | 264 tokens 340 tokens |
These token counts are added to your normal input and output tokens to calculate the total cost of a request.
Lihat tabel gambaran umum model kami untuk harga per model saat ini.
Ketika Anda mengirim prompt penggunaan tool, seperti permintaan API lainnya, respons akan mengeluarkan jumlah token input dan output sebagai bagian dari metrik usage yang dilaporkan.
Langkah Selanjutnya
Jelajahi repositori contoh kode penggunaan tool siap implementasi kami dalam cookbook kami:
Calculator Tool
Pelajari cara mengintegrasikan tool kalkulator sederhana dengan Claude untuk komputasi numerik yang presisi.
Customer Service Agent
Bangun bot layanan pelanggan yang responsif yang memanfaatkan client tools untuk meningkatkan dukungan.
JSON Extractor
Lihat bagaimana Claude dan penggunaan tool dapat mengekstrak data terstruktur dari teks tidak terstruktur.