AgentStack
SKILL unreviewed MIT Self-run

Claude Api

skill-jackspace-claudeskillz-claude-api · by jackspace

|

No reviews yet
0 installs
18 views
0.0% view→install

Install

$ agentstack add skill-jackspace-claudeskillz-claude-api

Open-source listing — not yet scanned by AgentStack. Follow the source repository for install instructions.

Security review

⚠ Flagged

1 finding(s); flagged for manual review. · v0.1.0 How review works →

  • Prompt-injection patterns
  • Secret / credential exfiltration
  • Dangerous shell & filesystem operations
  • Untrusted network calls
  • Known-malicious package signatures
  • high Reads credentials/environment and may exfiltrate them.

What it can access

  • Network access Used
  • Filesystem access Used
  • Shell / process execution No
  • Environment & secrets Used
  • Dynamic code execution No

From automated source analysis of v0.1.0. “Used” means the capability is present in the source — more access means more to trust, not that it’s unsafe.

Are you the author of Claude Api? Claim this listing to set pricing, connect Stripe payouts, and keep 70% of every sale.
Sign up to claim

About

Claude API (Anthropic Messages API)

Status: Production Ready Last Updated: 2025-10-25 Dependencies: None (standalone API skill) Latest Versions: @anthropic-ai/sdk@0.67.0


Quick Start (5 Minutes)

1. Get API Key

# Sign up at https://console.anthropic.com/
# Navigate to API Keys section
# Create new key and save securely
export ANTHROPIC_API_KEY="sk-ant-..."

Why this matters:

  • API key required for all requests
  • Keep secure (never commit to git)
  • Use environment variables

2. Install SDK (Node.js)

npm install @anthropic-ai/sdk
import Anthropic from '@anthropic-ai/sdk';

const anthropic = new Anthropic({
  apiKey: process.env.ANTHROPIC_API_KEY,
});

const message = await anthropic.messages.create({
  model: 'claude-sonnet-4-5-20250929',
  max_tokens: 1024,
  messages: [{ role: 'user', content: 'Hello, Claude!' }],
});

console.log(message.content[0].text);

CRITICAL:

  • Always use server-side (never expose API key in client code)
  • Set max_tokens (required parameter)
  • Model names are versioned (use latest stable)

3. Or Use Direct API (Cloudflare Workers)

// No SDK needed - use fetch()
const response = await fetch('https://api.anthropic.com/v1/messages', {
  method: 'POST',
  headers: {
    'x-api-key': env.ANTHROPIC_API_KEY,
    'anthropic-version': '2023-06-01',
    'content-type': 'application/json',
  },
  body: JSON.stringify({
    model: 'claude-sonnet-4-5-20250929',
    max_tokens: 1024,
    messages: [{ role: 'user', content: 'Hello!' }],
  }),
});

const data = await response.json();

The Complete Claude API Reference

Table of Contents

  1. [Core API](#core-api-messages-api)
  2. [Streaming Responses](#streaming-responses-sse)
  3. [Prompt Caching](#prompt-caching--90-cost-savings)
  4. [Tool Use (Function Calling)](#tool-use-function-calling)
  5. [Vision (Image Understanding)](#vision-image-understanding)
  6. [Extended Thinking Mode](#extended-thinking-mode)
  7. [Rate Limits](#rate-limits)
  8. [Error Handling](#error-handling)
  9. [Platform Integrations](#platform-integrations)
  10. [Known Issues](#known-issues-prevention)

Core API (Messages API)

Available Models (October 2025)

| Model | ID | Context | Best For | Cost (per MTok) | |-------|-----|---------|----------|-----------------| | Claude Sonnet 4.5 | claude-sonnet-4-5-20250929 | 200k tokens | Balanced performance | $3/$15 (in/out) | | Claude 3.7 Sonnet | claude-3-7-sonnet-20250228 | 2M tokens | Extended thinking | $3/$15 | | Claude Opus 4 | claude-opus-4-20250514 | 200k tokens | Highest capability | $15/$75 | | Claude 3.5 Haiku | claude-3-5-haiku-20241022 | 200k tokens | Fast, cost-effective | $1/$5 |

Basic Message Creation

import Anthropic from '@anthropic-ai/sdk';

const anthropic = new Anthropic({
  apiKey: process.env.ANTHROPIC_API_KEY,
});

const message = await anthropic.messages.create({
  model: 'claude-sonnet-4-5-20250929',
  max_tokens: 1024,
  messages: [
    { role: 'user', content: 'Explain quantum computing in simple terms' }
  ],
});

console.log(message.content[0].text);

Multi-Turn Conversations

const messages = [
  { role: 'user', content: 'What is the capital of France?' },
  { role: 'assistant', content: 'The capital of France is Paris.' },
  { role: 'user', content: 'What is its population?' },
];

const message = await anthropic.messages.create({
  model: 'claude-sonnet-4-5-20250929',
  max_tokens: 1024,
  messages,
});

System Prompts

const message = await anthropic.messages.create({
  model: 'claude-sonnet-4-5-20250929',
  max_tokens: 1024,
  system: 'You are a helpful Python coding assistant. Always provide type hints and docstrings.',
  messages: [
    { role: 'user', content: 'Write a function to sort a list' }
  ],
});

CRITICAL:

  • System prompt MUST come before messages array
  • System prompt sets behavior for entire conversation
  • Can be 1-10k tokens (affects context window)

Streaming Responses (SSE)

Using SDK Stream Helper

const stream = anthropic.messages.stream({
  model: 'claude-sonnet-4-5-20250929',
  max_tokens: 1024,
  messages: [{ role: 'user', content: 'Write a short story' }],
});

// Method 1: Event listeners
stream
  .on('text', (text) => {
    process.stdout.write(text);
  })
  .on('message', (message) => {
    console.log('\n\nFinal message:', message);
  })
  .on('error', (error) => {
    console.error('Stream error:', error);
  });

// Wait for completion
await stream.finalMessage();

Streaming with Manual Iteration

const stream = await anthropic.messages.create({
  model: 'claude-sonnet-4-5-20250929',
  max_tokens: 1024,
  messages: [{ role: 'user', content: 'Explain AI' }],
  stream: true,
});

for await (const event of stream) {
  if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') {
    process.stdout.write(event.delta.text);
  }
}

Streaming Event Types

| Event | When | Use Case | |-------|------|----------| | message_start | Message begins | Initialize UI | | content_block_start | New content block | Track blocks | | content_block_delta | Text chunk received | Display text | | content_block_stop | Block complete | Format block | | message_delta | Metadata update | Update stop reason | | message_stop | Message complete | Finalize UI |

Cloudflare Workers Streaming

export default {
  async fetch(request: Request, env: Env): Promise {
    const response = await fetch('https://api.anthropic.com/v1/messages', {
      method: 'POST',
      headers: {
        'x-api-key': env.ANTHROPIC_API_KEY,
        'anthropic-version': '2023-06-01',
        'content-type': 'application/json',
      },
      body: JSON.stringify({
        model: 'claude-sonnet-4-5-20250929',
        max_tokens: 1024,
        messages: [{ role: 'user', content: 'Hello!' }],
        stream: true,
      }),
    });

    // Return SSE stream directly
    return new Response(response.body, {
      headers: {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive',
      },
    });
  },
};

CRITICAL:

  • Errors can occur AFTER initial 200 response
  • Always implement error event handlers
  • Use stream.abort() to cancel
  • Set proper Content-Type headers

Prompt Caching (⭐ 90% Cost Savings)

Overview

Prompt caching allows you to cache frequently used context (system prompts, documents, codebases) to:

  • Reduce costs by 90% (cache reads = 10% of input token price)
  • Reduce latency by 85% (time to first token)
  • Cache lifetime: 5 minutes (default) or 1 hour (configurable)

Minimum Requirements

  • Claude 3.5 Sonnet: 1,024 tokens minimum
  • Claude 3.5 Haiku: 2,048 tokens minimum

Basic Prompt Caching

const message = await anthropic.messages.create({
  model: 'claude-sonnet-4-5-20250929',
  max_tokens: 1024,
  system: [
    {
      type: 'text',
      text: 'You are an AI assistant analyzing the following codebase...',
    },
    {
      type: 'text',
      text: LARGE_CODEBASE_CONTENT, // 50k tokens
      cache_control: { type: 'ephemeral' },
    },
  ],
  messages: [
    { role: 'user', content: 'Explain the auth module' }
  ],
});

// Check cache usage
console.log('Cache read tokens:', message.usage.cache_read_input_tokens);
console.log('Cache creation tokens:', message.usage.cache_creation_input_tokens);

Caching in Messages

const message = await anthropic.messages.create({
  model: 'claude-sonnet-4-5-20250929',
  max_tokens: 1024,
  messages: [
    {
      role: 'user',
      content: [
        {
          type: 'text',
          text: 'Analyze this documentation:',
        },
        {
          type: 'text',
          text: LONG_DOCUMENTATION, // 20k tokens
          cache_control: { type: 'ephemeral' },
        },
        {
          type: 'text',
          text: 'What are the main API endpoints?',
        },
      ],
    },
  ],
});

Multi-Turn Caching (Chatbot Pattern)

// First request - creates cache
const message1 = await anthropic.messages.create({
  model: 'claude-sonnet-4-5-20250929',
  max_tokens: 1024,
  system: [
    {
      type: 'text',
      text: SYSTEM_INSTRUCTIONS,
      cache_control: { type: 'ephemeral' },
    },
  ],
  messages: [
    { role: 'user', content: 'Hello!' }
  ],
});

// Second request - hits cache (within 5 minutes)
const message2 = await anthropic.messages.create({
  model: 'claude-sonnet-4-5-20250929',
  max_tokens: 1024,
  system: [
    {
      type: 'text',
      text: SYSTEM_INSTRUCTIONS, // Same content = cache hit
      cache_control: { type: 'ephemeral' },
    },
  ],
  messages: [
    { role: 'user', content: 'Hello!' },
    { role: 'assistant', content: message1.content[0].text },
    { role: 'user', content: 'Tell me a joke' },
  ],
});

Cost Comparison

Without Caching:
- 100k input tokens = 100k × $3/MTok = $0.30

With Caching (after first request):
- Cache write: 100k × $3.75/MTok = $0.375 (first request)
- Cache read: 100k × $0.30/MTok = $0.03 (subsequent requests)
- Savings: 90% per request after first

CRITICAL:

  • cache_control MUST be on LAST block of cacheable content
  • Cache shared across requests with IDENTICAL content
  • Monitor cache_creation_input_tokens vs cache_read_input_tokens
  • 5-minute TTL refreshes on each use

Tool Use (Function Calling)

Basic Tool Definition

const tools = [
  {
    name: 'get_weather',
    description: 'Get the current weather in a given location',
    input_schema: {
      type: 'object',
      properties: {
        location: {
          type: 'string',
          description: 'City name, e.g. San Francisco, CA',
        },
        unit: {
          type: 'string',
          enum: ['celsius', 'fahrenheit'],
          description: 'Temperature unit',
        },
      },
      required: ['location'],
    },
  },
];

const message = await anthropic.messages.create({
  model: 'claude-sonnet-4-5-20250929',
  max_tokens: 1024,
  tools,
  messages: [{ role: 'user', content: 'What is the weather in NYC?' }],
});

if (message.stop_reason === 'tool_use') {
  const toolUse = message.content.find(block => block.type === 'tool_use');
  console.log('Claude wants to use:', toolUse.name);
  console.log('With parameters:', toolUse.input);
}

Tool Execution Loop

async function chatWithTools(userMessage: string) {
  const messages = [{ role: 'user', content: userMessage }];

  while (true) {
    const response = await anthropic.messages.create({
      model: 'claude-sonnet-4-5-20250929',
      max_tokens: 1024,
      tools,
      messages,
    });

    // Add assistant response
    messages.push({
      role: 'assistant',
      content: response.content,
    });

    // Check if tools need to be executed
    if (response.stop_reason === 'tool_use') {
      const toolResults = [];

      for (const block of response.content) {
        if (block.type === 'tool_use') {
          // Execute tool
          const result = await executeToolFunction(block.name, block.input);

          toolResults.push({
            type: 'tool_result',
            tool_use_id: block.id,
            content: JSON.stringify(result),
          });
        }
      }

      // Add tool results
      messages.push({
        role: 'user',
        content: toolResults,
      });
    } else {
      // Final response
      return response.content.find(block => block.type === 'text')?.text;
    }
  }
}

Beta Tool Runner (SDK Helper)

import { betaZodTool } from '@anthropic-ai/sdk/helpers/zod';
import { z } from 'zod';

const weatherTool = betaZodTool({
  name: 'get_weather',
  inputSchema: z.object({
    location: z.string(),
    unit: z.enum(['celsius', 'fahrenheit']).optional(),
  }),
  description: 'Get the current weather in a given location',
  run: async (input) => {
    // Execute actual API call
    const weather = await fetchWeatherAPI(input.location, input.unit);
    return `The weather in ${input.location} is ${weather.temp}°${input.unit || 'F'}`;
  },
});

const finalMessage = await anthropic.beta.messages.toolRunner({
  model: 'claude-sonnet-4-5-20250929',
  max_tokens: 1000,
  messages: [{ role: 'user', content: 'What is the weather in San Francisco?' }],
  tools: [weatherTool],
});

console.log(finalMessage.content[0].text);

CRITICAL:

  • Tool schemas MUST be valid JSON Schema
  • tool_use_id MUST match in tool_result
  • Handle tool execution errors gracefully
  • Set reasonable max_iterations to prevent loops

Vision (Image Understanding)

Supported Image Formats

  • Formats: JPEG, PNG, WebP, GIF (non-animated)
  • Max size: 5MB per image
  • Input methods: Base64 encoded, URL (if accessible)

Single Image

import fs from 'fs';

const imageData = fs.readFileSync('./photo.jpg', 'base64');

const message = await anthropic.messages.create({
  model: 'claude-sonnet-4-5-20250929',
  max_tokens: 1024,
  messages: [
    {
      role: 'user',
      content: [
        {
          type: 'image',
          source: {
            type: 'base64',
            media_type: 'image/jpeg',
            data: imageData,
          },
        },
        {
          type: 'text',
          text: 'What is in this image?',
        },
      ],
    },
  ],
});

Multiple Images

const message = await anthropic.messages.create({
  model: 'claude-sonnet-4-5-20250929',
  max_tokens: 1024,
  messages: [
    {
      role: 'user',
      content: [
        {
          type: 'text',
          text: 'Compare these two images:',
        },
        {
          type: 'image',
          source: {
            type: 'base64',
            media_type: 'image/jpeg',
            data: image1Data,
          },
        },
        {
          type: 'image',
          source: {
            type: 'base64',
            media_type: 'image/png',
            data: image2Data,
          },
        },
        {
          type: 'text',
          text: 'What are the differences?',
        },
      ],
    },
  ],
});

Vision with Tools

const message = await anthropic.messages.create({
  model: 'claude-sonnet-4-5-20250929',
  max_tokens: 1024,
  tools: [searchTool, saveTool],
  messages: [
    {
      role: 'user',
      content: [
        {
          type: 'image',
          source: {
            type: 'base64',
            media_type: 'image/jpeg',
            data: productImage,
          },
        },
        {
          type: 'text',
          text: 'Search for similar products and save the top 3 results',
        },
      ],
    },
  ],
});

CRITICAL:

  • Images count toward context window
  • Base64 encoding increases size (~33% overhead)
  • Validate image format before encoding
  • Consider caching for repeated image analysis

Extended Thinking Mode

⚠️ Model Availability

Extended thinking is ONLY available in:

  • Claude 3.7 Sonnet (claude-3-7-sonnet-20250228)
  • Claude 4 models (Opus 4, Sonnet 4)

NOT available in Claude 3.5 Sonnet

How It Works

Extended thinking allows Claude to "think out loud" before responding, showing its reasoning process. This is useful for:

  • Complex STEM problems (physics, mathematics)
  • Software debugging and architecture
  • Legal analysis and financial modeling
  • Multi-step reasoning tasks

Basic Usage

// Only works with Claude 3.7 Sonnet or Claude 4
const message = await anthropic.messages.create({
  model: 'claude-3-7-sonnet-20250228', // NOT claude-sonnet-4-5
  max_tokens: 4096, // Higher token limit for thinking
  messages: [
    {
      role: 'user',
      content: 'Solve this physics problem: A ball is thrown upward with velocity 20 m/s. How high does it go?'
    }
  ],
});

…

## Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [jackspace](https://github.com/jackspace)
- **Source:** [jackspace/ClaudeSkillz](https://github.com/jackspace/ClaudeSkillz)
- **License:** MIT
- **Homepage:** http://claudeskillz.jackspace.com/

Install and usage instructions live in the source repository linked above.

Reviews

No reviews yet — be the first.

Versions

  • v0.1.0 Imported from the upstream source.