Anthropic Swift SDK
β οΈ UNOFFICIAL LIBRARY: This is an unofficial Swift SDK for the Anthropic Claude API and is not affiliated with, endorsed, or supported by Anthropic in any way.
A modern, native Swift SDK for the Anthropic Claude API, designed specifically for iOS and macOS applications. Built with modern Swift features including async/await, actors, and comprehensive error handling.
β¨ Key Features
- π Native Swift API - Idiomatic Swift patterns with full async/await support
- π Real-time Streaming - AsyncSequence-based streaming for live responses
- π Tool Integration - Built-in support for Claudeβs advanced tool use capabilities
- π§ Extended Thinking - Access to Claudeβs reasoning process and step-by-step logic
- π¦ Batch Operations - Efficient bulk message processing for high-throughput scenarios
- π File Management - Upload and manage files for document analysis and processing
- β‘ Performance Optimized - Connection pooling, intelligent caching, and retry strategies
- π― Type Safe - Comprehensive type definitions for all API interactions
- π± Mobile Ready - Optimized configurations for iOS/macOS memory and performance constraints
- π§ͺ Test Driven - >95% test coverage with comprehensive BDD test suite
π Quick Start
Installation
Add to your Package.swift
:
dependencies: [
.package(url: "https://github.com/tthew/anthropic-swift-sdk", from: "1.0.0")
]
Basic Usage
import AnthropicSDK
// Initialize client
let client = try AnthropicClient(apiKey: "your-token")
// Send a message
let response = try await client.sendMessage("Hello, Claude!")
print(response.content.first?.text ?? "No response")
// Stream responses in real-time
let stream = try await client.streamMessage("Write a story about space exploration")
for try await chunk in stream {
if case .contentBlockDelta(let delta) = chunk,
case .textDelta(let text) = delta.delta {
print(text, terminator: "")
}
}
π― Advanced Features
Tool Use Integration
Define custom tools and let Claude use them to solve complex problems:
let tools = [
Tool(
name: "calculate",
description: "Perform mathematical calculations",
inputSchema: [
"type": "object",
"properties": [
"expression": [
"type": "string",
"description": "Mathematical expression to evaluate"
]
],
"required": ["expression"]
]
)
]
let response = try await client.sendMessageWithTools(
"What is 15 * 23 + 45?",
tools: tools
) { toolName, input in
// Handle tool execution
switch toolName {
case "calculate":
return evaluateExpression(input["expression"] as? String ?? "")
default:
return "Unknown tool"
}
}
Extended Thinking Access
Access Claudeβs reasoning process for complex problem-solving:
let response = try await client.sendMessageWithThinking(
"Solve this logic puzzle: Three friends each have different pets...",
thinkingMode: .extended
)
// Access reasoning steps
if let thinkingSteps = response.thinking {
print("Claude's reasoning:")
for step in thinkingSteps {
print("- \(step.content)")
}
}
Batch Processing
Process multiple requests efficiently:
let requests = [
BatchRequest(customId: "task_1", method: .POST, url: "/v1/messages",
body: CreateMessageRequest(model: .claude3_5Sonnet,
messages: [.user("Summarize renewable energy")],
maxTokens: 500)),
BatchRequest(customId: "task_2", method: .POST, url: "/v1/messages",
body: CreateMessageRequest(model: .claude3_5Sonnet,
messages: [.user("Explain machine learning")],
maxTokens: 500))
]
let batch = try await client.batches.create(CreateBatchRequest(requests: requests))
π Documentation
- Getting Started Guide - Complete setup and basic usage
- API Reference - Detailed API documentation
- Examples - Real-world usage examples
- Troubleshooting - Common issues and solutions
π€ Supported Models
Model | Description | Context Window | Vision Support |
---|---|---|---|
claude4Opus |
Most intelligent model with hybrid reasoning | 200K tokens | β |
claude4Sonnet |
Advanced model with superior coding capabilities | 200K tokens | β |
claude3_5Sonnet |
Most intelligent, balanced performance | 200K tokens | β |
claude3_5Haiku |
Fastest, lightweight for everyday tasks | 200K tokens | β |
claude3Opus |
Most powerful for complex reasoning | 200K tokens | β |
claude3Sonnet |
Balanced intelligence and speed | 200K tokens | β |
claude3Haiku |
Fast and cost-effective | 200K tokens | β |
π Requirements
- iOS 15.0+ / macOS 12.0+ / tvOS 15.0+ / watchOS 8.0+
- Swift 5.9+
- Xcode 14.0+
π§ Architecture
The SDK follows a layered architecture with progressive disclosure:
Core Layer
βββ HTTPClient (Actor) - Thread-safe networking
βββ Authentication - API key management
βββ Error Handling - Comprehensive error mapping
API Resources
βββ MessagesResource - Text generation and streaming
βββ ModelsResource - Model discovery and capabilities
βββ BatchesResource - Bulk operations
βββ FilesResource - File upload/management
Advanced Features
βββ Streaming - AsyncSequence for real-time responses
βββ Tool Use - Custom tool integration
βββ Extended Thinking - Reasoning step access
ποΈ Development Methodology
This project follows strict Test-Driven Development (TDD) and Behavior-Driven Development (BDD) principles:
- RED Phase: Write failing tests that define expected behavior
- GREEN Phase: Write minimal implementation to pass tests
- REFACTOR Phase: Improve code while keeping tests green
- Quality Gate: All tests must pass with β₯95% coverage before proceeding
π€ Contributing
We welcome contributions! The project uses comprehensive CI/CD with:
- Multi-Platform Testing: macOS, iOS Simulator, Linux compatibility
- Quality Gates: 95%+ test coverage requirement
- Automated Validation: All example projects and documentation
- Security Scanning: Basic security pattern analysis
See our Contributing Guide for details.
π License
This project is licensed under the MIT License - see the LICENSE file for details.
π Links
- π Official Anthropic API Documentation
- π Report Issues
- π¬ Discussions
- π¦ Swift Package Index
Disclaimer: This is an unofficial library. For official support or questions about the Anthropic API itself, please contact Anthropic directly through their official channels.