Claude API Examples
This page provides examples of using the Agentsflare Claude API to help you quickly integrate and use Claude AI services.
Basic Configuration
Before starting to use the API, please ensure you have obtained an API Key. If not, please refer to Create API Key.
Basic Information
- API Base URL:
https://api.agentsflare.com/anthropic/v1/messages - Authentication Method: API Key (
x-api-keyheader) - Content Type:
application/json
Request Examples
curl --location --request POST 'https://api.agentsflare.com/anthropic/v1/messages' \
--header 'Content-Type: application/json' \
--header 'x-api-key: YOUR_API_KEY' \
--header 'anthropic-version: 2025-06-18' \
--data-raw '{
"model": "claude-sonnet-5",
"max_tokens": 1024,
"messages": [
{
"role": "user",
"content": "Hello, please introduce yourself"
}
]
}'import anthropic
client = anthropic.Anthropic(
api_key="YOUR_API_KEY",
base_url="https://api.agentsflare.com/anthropic"
)
message = client.messages.create(
model="claude-sonnet-5",
max_tokens=1024,
messages=[
{
"role": "user",
"content": "Hello, please introduce yourself"
}
]
)
print(message.content[0].text)import anthropic
client = anthropic.Anthropic(
api_key="YOUR_API_KEY",
base_url="https://api.agentsflare.com/anthropic"
)
message = client.messages.create(
model="claude-sonnet-5",
max_tokens=1024,
messages=[
{
"role": "user",
"content": "Hello, please introduce yourself"
}
],
stream=True
)
for event in message:
if event.type == "content_block_delta":
delta = event.delta
if delta.type == "text_delta":
print(delta.text, end="", flush=True)import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic({
apiKey: process.env.AGENTSFLARE_API_KEY,
baseURL: "https://api.agentsflare.com/anthropic"
});
async function main() {
try {
const message = await client.messages.create({
model: "claude-sonnet-5",
max_tokens: 1024,
messages: [
{
role: "user",
content: "Hello, please introduce yourself"
}
]
});
console.log(message.content[0].text);
} catch (err) {
console.error(err?.response?.data ?? err);
}
}
main();import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic({
apiKey: process.env.AGENTSFLARE_API_KEY,
baseURL: "https://api.agentsflare.com/anthropic"
});
async function main() {
try {
const stream = await client.messages.create({
model: "claude-sonnet-5",
max_tokens: 1024,
messages: [
{
role: "user",
content: "Hello, please introduce yourself"
}
],
stream: true
});
for await (const event of stream) {
if (event.type === 'content_block_delta') {
if (event.delta.type === 'text_delta') {
process.stdout.write(event.delta.text);
}
}
}
} catch (err) {
console.error(err?.response?.data ?? err);
}
}
main();const Anthropic = require("@anthropic-ai/sdk");
const client = new Anthropic({
apiKey: process.env.AGENTSFLARE_API_KEY,
baseURL: "https://api.agentsflare.com/anthropic"
});
async function main() {
try {
const message = await client.messages.create({
model: "claude-sonnet-5",
max_tokens: 1024,
messages: [
{
role: "user",
content: "Hello, please introduce yourself"
}
]
});
console.log(message.content[0].text);
} catch (err) {
console.error(err?.response?.data ?? err);
}
}
main();package main
import (
"context"
"fmt"
"log"
"os"
"github.com/anthropics/anthropic-sdk-go"
"github.com/anthropics/anthropic-sdk-go/option"
)
func main() {
apiKey := os.Getenv("AGENTSFLARE_API_KEY")
if apiKey == "" {
log.Fatal("missing env AGENTSFLARE_API_KEY")
}
client := anthropic.NewClient(
option.WithAPIKey(apiKey),
option.WithBaseURL("https://api.agentsflare.com/anthropic"),
)
ctx := context.Background()
message, err := client.Messages.New(ctx, anthropic.MessageNewParams{
Model: anthropic.F("claude-sonnet-5"),
MaxTokens: anthropic.F(int64(1024)),
Messages: anthropic.F([]anthropic.MessageParam{
anthropic.NewUserMessage(anthropic.NewTextBlock("Hello, please introduce yourself")),
}),
})
if err != nil {
log.Fatalf("message creation failed: %v", err)
}
fmt.Println(message.Content[0].Text)
}Response Examples
Non-streaming Response
{
"id": "msg_01XFDUDYJgAACzvnptvVoYEL",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "Hello! I'm Claude, an AI assistant created by Anthropic. I'm designed to be helpful, harmless, and honest. I can assist you with a wide variety of tasks including writing, analysis, programming, learning, and more. How can I help you today?"
}
],
"model": "claude-sonnet-5",
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {
"input_tokens": 15,
"output_tokens": 65
}
}Streaming Response
event: message_start
data: {"type":"message_start","message":{"id":"msg_123","type":"message","role":"assistant","content":[],"model":"claude-sonnet-5","stop_reason":null,"usage":{"input_tokens":15,"output_tokens":0}}}
event: content_block_start
data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}
event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hello"}}
event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"!"}}
event: content_block_stop
data: {"type":"content_block_stop","index":0}
event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":65}}
event: message_stop
data: {"type":"message_stop"}Request Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| model | string | Yes | Model name, e.g., claude-sonnet-5 |
| messages | array | Yes | Array of messages with role and content |
| max_tokens | integer | Yes | Maximum tokens to generate |
| stream | boolean | No | Enable streaming response, default false |
| system | string | No | System prompt |
Note: On Claude Opus 4.7 and newer model families, setting
temperature,top_p, ortop_kto non-default values can return HTTP 400. Omit these parameters unless the target model explicitly supports them.
Features
Streaming Output
Claude API supports streaming output (SSE) by setting stream: true. Streaming responses allow real-time content generation, providing a better user experience.
System Prompts
Claude supports system prompts via the system parameter to define the assistant's role and behavior.
Structured Outputs
Use output_config.format when you need valid JSON that conforms to a JSON Schema. The format value must be an object with type: "json_schema" and a nested schema; it is not the string "json".
curl -s https://api.agentsflare.com/anthropic/v1/messages \
-H "content-type: application/json" \
-H "x-api-key: YOUR_API_KEY" \
-H "anthropic-version: 2025-06-18" \
-d '{
"model": "claude-sonnet-5",
"max_tokens": 1024,
"messages": [
{"role": "user", "content": "Return a summary and key points."}
],
"output_config": {
"format": {
"type": "json_schema",
"schema": {
"type": "object",
"properties": {
"summary": {"type": "string"},
"key_points": {"type": "array", "items": {"type": "string"}}
},
"required": ["summary", "key_points"],
"additionalProperties": false
}
}
}
}'Multi-turn Conversations
Include previous user and assistant messages in the messages array:
messages = [
{"role": "user", "content": "What is machine learning?"},
{"role": "assistant", "content": "Machine learning is a branch of AI..."},
{"role": "user", "content": "What are its applications?"},
]
message = client.messages.create(
model="claude-sonnet-5",
max_tokens=1024,
messages=messages,
)Claude 4.7+ Migration and Advanced Features
The following compatibility notes apply when migrating from older Claude models, especially from Opus 4.6 to Opus 4.7 or later models.
| Change | Compatibility impact | Recommended action |
|---|---|---|
| Sampling parameters | Non-default temperature, top_p, or top_k values can return HTTP 400 on newer model families | Omit these fields unless the target model explicitly supports them |
| Thinking mode | thinking.type: "enabled" is deprecated on Claude 4.6 and rejected on Claude 4.7+ | Use thinking.type: "adaptive" and control depth with output_config.effort |
| Assistant prefill | A final assistant prefill is unsupported starting with Claude 4.6 models | Put constraints in system, or use structured outputs for schema-constrained JSON |
| Thinking visibility | Thinking text is omitted by default | Set display: "summarized" when a readable thinking summary is required |
Adaptive Thinking Example
curl -s https://api.agentsflare.com/anthropic/v1/messages \
-H "content-type: application/json" \
-H "x-api-key: YOUR_API_KEY" \
-H "anthropic-version: 2025-06-18" \
-d '{
"model": "claude-opus-4-7",
"max_tokens": 16000,
"messages": [
{"role": "user", "content": "Analyze the trade-offs of this architecture."}
],
"thinking": {
"type": "adaptive",
"display": "summarized"
},
"output_config": {
"effort": "high"
}
}'OpenAI SDK compatibility
When calling Claude through the OpenAI-compatible /v1 endpoint, pass thinking and output_config through extra_body. See Claude Reasoning for a complete example.
Prompt Caching
Claude API supports Prompt Caching, allowing you to cache large context blocks in system or messages (such as project specifications, reference documents, etc.). Subsequent requests can reuse the cached content, significantly reducing token consumption and response latency.
Limitations
| Item | Limit |
|---|---|
| Claude Fable 5.1 / Opus 5 / Fable 5 / Mythos 5 | 512 tokens |
| Claude Opus 4.7 | 2,048 tokens |
| Claude Opus 4.6 / Opus 4.5 / Haiku 4.5 | 4,096 tokens |
| Claude Opus 4.8 / Sonnet 5 / Sonnet 4.6 / Sonnet 4.5 | 1,024 tokens |
| Default cache TTL | 300 seconds (5 minutes); a 1-hour TTL is available only where supported |
Prompts shorter than the applicable minimum are processed normally but are not cached, and no error is returned.
Usage
Use the array format for system and add the cache_control field to the content block you want to cache.
Recommendation
Keep stable content before the cache breakpoint and move dynamic values, timestamps, and request-specific text after it.
curl -s https://api.agentsflare.com/anthropic/v1/messages \
-H "content-type: application/json" \
-H "x-api-key: YOUR_API_KEY" \
-H "anthropic-version: 2025-06-18" \
-d '{
"model": "claude-sonnet-5",
"max_tokens": 1024,
"system": [
{
"type": "text",
"text": "[Project: project-alpha]\n\nPlace your large context here, such as project specs, technical docs, coding standards...",
"cache_control": {"type": "ephemeral"}
}
],
"messages": [
{
"role": "user",
"content": "Based on the above specs, help me review this code."
}
]
}'Response Examples
First request (cache creation):
{
"usage": {
"input_tokens": 29,
"cache_creation_input_tokens": 2480,
"cache_read_input_tokens": 0,
"output_tokens": 655
}
}Subsequent request (cache hit):
{
"usage": {
"input_tokens": 33,
"cache_creation_input_tokens": 0,
"cache_read_input_tokens": 2480,
"output_tokens": 1024
}
}Response Field Descriptions
| Field | Description |
|---|---|
cache_creation_input_tokens | Tokens newly cached in this request. A value greater than 0 indicates cache was created successfully |
cache_read_input_tokens | Tokens read from cache in this request. A value greater than 0 indicates a successful cache hit |
input_tokens | Regular (non-cached) input tokens, such as user messages in messages |
Determining Cache Status
cache_creation_input_tokens > 0: Cache created successfully — the content has been cached and subsequent identical requests will hit the cachecache_read_input_tokens > 0: Cache hit successfully — this request reused previously cached content, saving token consumption- Both are
0: Cache did not take effect — the content may be below the model-specific minimum, the prefix may have changed, or the cache may have expired
Cache Hit Rules and Troubleshooting
- Cache matching is prefix-based. A byte-level change before a breakpoint invalidates that breakpoint and all content after it.
- The cache hierarchy follows
tools→system→messages; changing tools or switching models invalidates the affected prefix. - A request can contain up to 4 explicit cache breakpoints.
- Avoid timestamps, random IDs, unstable JSON key ordering, or other dynamic content before a breakpoint.
- Verify behavior with
usage.cache_creation_input_tokensandusage.cache_read_input_tokensinstead of assuming a cache hit.
Important Notes
- API Key Security: Do not hardcode API Keys in your code, use environment variables
- Request Rate: Please comply with API call rate limits
- Error Handling: Implement comprehensive error handling mechanisms
- Token Limits: Be aware of different models' context window limits
Related Links
- Claude Official Documentation
- Thinking
- Structured Outputs
- Prompt Caching
- API Address
- Billing
- Supported Models
Supported Models
The following models are available through this interface (sorted by recommendation):
claude-fable-5-1Newclaude-opus-5Newclaude-mythos-5claude-fable-5claude-opus-4-8claude-opus-4-7claude-opus-4-6claude-opus-4-5-20251101claude-opus-4-1-20250805Retiredclaude-sonnet-5claude-sonnet-4-6claude-sonnet-4-5-20250929claude-haiku-4-5-20251001claude-sonnet-4-20250514Retiredclaude-opus-4-20250514Retiredclaude-3-haiku-20240307Retired
💡 Tip
The model field in the request example can be replaced with any model name above.
