Claude Sonnet 5
Text Generation • Anthropic
anthropic/claude-sonnet-5
- Third-party
Claude Sonnet 5 is Anthropic's most agentic Sonnet model yet, built for coding, tool use, reasoning, and long-horizon professional work at lower cost than Opus-class models.
| Model Info | |
|---|---|
| Context Window ↗ | 1,000,000 tokens |
| Terms and License | link ↗ |
| More information | link ↗ |
| Request formats | Anthropic Messages |
| Pricing | <ul><li>Input (per 1M tokens)$2.00</li><li>Output (per 1M tokens)$10.00</li><li>Cached input (per 1M tokens)$0.20</li><li>Cache creation (per 1M tokens)$2.50</li></ul> |
Usage
const response = await env.AI.run(
'anthropic/claude-sonnet-5',
{
max_tokens: 1024,
messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }],
},
)
console.log(response)
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
--header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"model": "anthropic/claude-sonnet-5",
"max_tokens": 1024,
"messages": [
{
"content": "What are the three laws of thermodynamics?",
"role": "user"
}
]
}'
# The Three (Four) Laws of Thermodynamics
Here are the fundamental laws, typically numbered 1-3 (with a "Zeroth Law" often included as foundational):
## Zeroth Law
**If two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other.**
- This establishes the concept of temperature as a measurable property.
## First Law (Conservation of Energy)
**Energy cannot be created or destroyed, only transformed or transferred.**
- Often expressed as: ΔU = Q − W
- (Change in internal energy = Heat added − Work done by the system)
- This means the total energy of an isolated system remains constant.
## Second Law (Entropy)
**The total entropy of an isolated system can never decrease over time; it tends to increase or remain constant.**
- Heat flows spontaneously from hot to cold objects, not the reverse.
- This law explains why certain processes are irreversible and establishes the "arrow of time."
- No heat engine can be 100% efficient at converting heat into work.
## Third Law
**As the temperature of a system approaches absolute zero (0 Kelvin), the entropy of the system approaches a minimum (constant) value.**
- Absolute zero is unattainable in a finite number of steps.
- At absolute zero, a perfect crystal would have exactly zero entropy.
---
**Quick summary often used colloquially:**
1. You can't win (can't get more energy out than you put in)
2. You can't break even (some energy is always lost as unusable heat)
3. You can't get out of the game (can't reach absolute zero)
{
"id": "msg_01RdqxfAYz2PfZTfiAYpX6Tz",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "# The Three (Four) Laws of Thermodynamics\n\nHere are the fundamental laws, typically numbered 1-3 (with a \"Zeroth Law\" often included as foundational):\n\n## Zeroth Law\n**If two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other.**\n- This establishes the concept of temperature as a measurable property.\n\n## First Law (Conservation of Energy)\n**Energy cannot be created or destroyed, only transformed or transferred.**\n- Often expressed as: ΔU = Q − W\n- (Change in internal energy = Heat added − Work done by the system)\n- This means the total energy of an isolated system remains constant.\n\n## Second Law (Entropy)\n**The total entropy of an isolated system can never decrease over time; it tends to increase or remain constant.**\n- Heat flows spontaneously from hot to cold objects, not the reverse.\n- This law explains why certain processes are irreversible and establishes the \"arrow of time.\"\n- No heat engine can be 100% efficient at converting heat into work.\n\n## Third Law\n**As the temperature of a system approaches absolute zero (0 Kelvin), the entropy of the system approaches a minimum (constant) value.**\n- Absolute zero is unattainable in a finite number of steps.\n- At absolute zero, a perfect crystal would have exactly zero entropy.\n\n---\n\n**Quick summary often used colloquially:**\n1. You can't win (can't get more energy out than you put in)\n2. You can't break even (some energy is always lost as unusable heat)\n3. You can't get out of the game (can't reach absolute zero)"
}
],
"model": "claude-sonnet-5",
"stop_reason": "end_turn",
"usage": {
"input_tokens": 20,
"output_tokens": 539
},
"stop_sequence": null,
"stop_details": null,
"gatewayMetadata": {
"keySource": "Unified"
}
}
Examples
<details>
<summary>With System Message — Using a system message to set context</summary>
const response = await env.AI.run(
'anthropic/claude-sonnet-5',
{
max_tokens: 1024,
messages: [{ content: 'How do I read a JSON file in Python?', role: 'user' }],
system: 'You are a helpful coding assistant specializing in Python.',
},
)
console.log(response)
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
--header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"model": "anthropic/claude-sonnet-5",
"max_tokens": 1024,
"messages": [
{
"content": "How do I read a JSON file in Python?",
"role": "user"
}
],
"system": "You are a helpful coding assistant specializing in Python."
}'
# Reading a JSON File in Python
Python's built-in `json` module makes this straightforward.
## Basic Example
```python
import json
with open('data.json', 'r') as file:
data = json.load(file)
print(data)
```
## Explanation
- **`json.load(file)`** — reads from a file object and parses JSON into Python objects
- **`json.loads(string)`** — use this instead if you have a JSON *string* (not a file) to parse
## Example with Sample Data
Suppose `data.json` contains:
```json
{
"name": "Alice",
"age": 30,
"skills": ["Python", "SQL"]
}
```
You can read and use it like this:
```python
import json
with open('data.json', 'r') as file:
data = json.load(file)
print(data['name']) # Alice
print(data['skills']) # ['Python', 'SQL']
```
## Handling Errors
It's good practice to handle common issues like missing files or invalid JSON:
```python
import json
try:
with open('data.json', 'r') as file:
data = json.load(file)
except FileNotFoundError:
print("File not found.")
except json.JSONDecodeError:
print("Invalid JSON format.")
```
## Reading JSON from a String
If your JSON is already a string in memory:
```python
import json
json_string = '{"name": "Bob", "age": 25}'
data = json.loads(json_string)
print(data['name']) # Bob
```
## Key Type Mappings
| JSON Type | Python Type |
|-----------|-------------|
| object | dict |
| array | list |
| string | str |
| number | int / float |
| true/false| bool |
| null | None |
That covers the essentials — let me know if you need help with nested data, writing JSON, or working with large files.
{
"id": "msg_01PptUvPAdU3SPQLQPwG7G3s",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "# Reading a JSON File in Python\n\nPython's built-in `json` module makes this straightforward.\n\n## Basic Example\n\n```python\nimport json\n\nwith open('data.json', 'r') as file:\n data = json.load(file)\n\nprint(data)\n```\n\n## Explanation\n\n- **`json.load(file)`** — reads from a file object and parses JSON into Python objects\n- **`json.loads(string)`** — use this instead if you have a JSON *string* (not a file) to parse\n\n## Example with Sample Data\n\nSuppose `data.json` contains:\n\n```json\n{\n \"name\": \"Alice\",\n \"age\": 30,\n \"skills\": [\"Python\", \"SQL\"]\n}\n```\n\nYou can read and use it like this:\n\n```python\nimport json\n\nwith open('data.json', 'r') as file:\n data = json.load(file)\n\nprint(data['name']) # Alice\nprint(data['skills']) # ['Python', 'SQL']\n```\n\n## Handling Errors\n\nIt's good practice to handle common issues like missing files or invalid JSON:\n\n```python\nimport json\n\ntry:\n with open('data.json', 'r') as file:\n data = json.load(file)\nexcept FileNotFoundError:\n print(\"File not found.\")\nexcept json.JSONDecodeError:\n print(\"Invalid JSON format.\")\n```\n\n## Reading JSON from a String\n\nIf your JSON is already a string in memory:\n\n```python\nimport json\n\njson_string = '{\"name\": \"Bob\", \"age\": 25}'\ndata = json.loads(json_string)\nprint(data['name']) # Bob\n```\n\n## Key Type Mappings\n\n| JSON Type | Python Type |\n|-----------|-------------|\n| object | dict |\n| array | list |\n| string | str |\n| number | int / float |\n| true/false| bool |\n| null | None |\n\nThat covers the essentials — let me know if you need help with nested data, writing JSON, or working with large files."
}
],
"model": "claude-sonnet-5",
"stop_reason": "end_turn",
"usage": {
"input_tokens": 38,
"output_tokens": 609
},
"stop_sequence": null,
"stop_details": null,
"gatewayMetadata": {
"keySource": "Unified"
}
}
</details>
<details>
<summary>Creative Writing with High Effort — Use adaptive thinking with high effort for deeper reasoning.</summary>
const response = await env.AI.run(
'anthropic/claude-sonnet-5',
{
max_tokens: 2048,
messages: [
{
content: 'Write a short story opening about a detective finding an unusual clue.',
role: 'user',
},
],
output_config: { effort: 'high' },
thinking: { type: 'adaptive' },
},
)
console.log(response)
