Skip to content

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-key header)
  • Content Type: application/json

Request Examples

bash
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"
        }
    ]
}'
python
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)
python
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)
javascript
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();
javascript
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();
javascript
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();
go
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

json
{
  "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

json
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

ParameterTypeRequiredDescription
modelstringYesModel name, e.g., claude-sonnet-5
messagesarrayYesArray of messages with role and content
max_tokensintegerYesMaximum tokens to generate
streambooleanNoEnable streaming response, default false
systemstringNoSystem prompt

Note: On Claude Opus 4.7 and newer model families, setting temperature, top_p, or top_k to 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".

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

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

ChangeCompatibility impactRecommended action
Sampling parametersNon-default temperature, top_p, or top_k values can return HTTP 400 on newer model familiesOmit these fields unless the target model explicitly supports them
Thinking modethinking.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 prefillA final assistant prefill is unsupported starting with Claude 4.6 modelsPut constraints in system, or use structured outputs for schema-constrained JSON
Thinking visibilityThinking text is omitted by defaultSet display: "summarized" when a readable thinking summary is required

Adaptive Thinking Example

bash
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

ItemLimit
Claude Fable 5.1 / Opus 5 / Fable 5 / Mythos 5512 tokens
Claude Opus 4.72,048 tokens
Claude Opus 4.6 / Opus 4.5 / Haiku 4.54,096 tokens
Claude Opus 4.8 / Sonnet 5 / Sonnet 4.6 / Sonnet 4.51,024 tokens
Default cache TTL300 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.

bash
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):

json
{
  "usage": {
    "input_tokens": 29,
    "cache_creation_input_tokens": 2480,  
    "cache_read_input_tokens": 0,         
    "output_tokens": 655
  }
}

Subsequent request (cache hit):

json
{
  "usage": {
    "input_tokens": 33,
    "cache_creation_input_tokens": 0,     
    "cache_read_input_tokens": 2480,      
    "output_tokens": 1024
  }
}

Response Field Descriptions

FieldDescription
cache_creation_input_tokensTokens newly cached in this request. A value greater than 0 indicates cache was created successfully
cache_read_input_tokensTokens read from cache in this request. A value greater than 0 indicates a successful cache hit
input_tokensRegular (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 cache
  • cache_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 toolssystemmessages; 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_tokens and usage.cache_read_input_tokens instead of assuming a cache hit.

Important Notes

  1. API Key Security: Do not hardcode API Keys in your code, use environment variables
  2. Request Rate: Please comply with API call rate limits
  3. Error Handling: Implement comprehensive error handling mechanisms
  4. Token Limits: Be aware of different models' context window limits

Supported Models

The following models are available through this interface (sorted by recommendation):

  • claude-fable-5-1 New
  • claude-opus-5 New
  • claude-mythos-5
  • claude-fable-5
  • claude-opus-4-8
  • claude-opus-4-7
  • claude-opus-4-6
  • claude-opus-4-5-20251101
  • claude-opus-4-1-20250805 Retired
  • claude-sonnet-5
  • claude-sonnet-4-6
  • claude-sonnet-4-5-20250929
  • claude-haiku-4-5-20251001
  • claude-sonnet-4-20250514 Retired
  • claude-opus-4-20250514 Retired
  • claude-3-haiku-20240307 Retired

💡 Tip

The model field in the request example can be replaced with any model name above.

This documentation is licensed under CC BY-SA 4.0.