### Getting Tool Use Blocks Example Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/StreamHandler.md Example of retrieving all streamed tool use blocks. ```swift let tools = handler.getToolUseBlocks() for toolUse in tools { print("Tool: \(toolUse.name) (ID: \(toolUse.id))") print("Input: \(toolUse.input)") if let json = toolUse.accumulatedJson { print("Raw JSON: \(json)") } } ``` -------------------------------- ### SkillCreateParameter Example Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/SkillParameter.md Example of how to create a SkillCreateParameter. ```swift let skillContent = "# My Skill\nThis is a skill for..." let markdownData = skillContent.data(using: .utf8)! let files = [ SkillFile(filename: "skill_name/SKILL.md", data: markdownData, mimeType: "text/markdown"), SkillFile(filename: "skill_name/utils.py", data: pythonCode, mimeType: "text/x-python") ] let param = SkillCreateParameter( displayTitle: "My Custom Skill", files: files ) let response = try await service.createSkill(param) print("Skill ID: \(response.id)") ``` -------------------------------- ### ListSkillVersionsParameter Example Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/SkillParameter.md Example of listing versions of a specific skill. ```swift let param = ListSkillVersionsParameter(limit: 50) let response = try await service.listSkillVersions(skillId: "skill_123", parameter: param) for version in response.data { print("Version \(version.version): \(version.createdAt)") } ``` -------------------------------- ### SkillVersionCreateParameter Example Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/SkillParameter.md Example of creating a new version of an existing skill. ```swift let updatedContent = "# My Skill\nUpdated version..." let data = updatedContent.data(using: .utf8)! let files = [ SkillFile(filename: "skill_name/SKILL.md", data: data, mimeType: "text/markdown") ] let param = SkillVersionCreateParameter(files: files) let response = try await service.createSkillVersion(skillId: "skill_123", param) print("New version: \(response.version)") ``` -------------------------------- ### Complete Skill Lifecycle Example Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/SkillResponse.md A comprehensive example demonstrating the full lifecycle of a skill, including creation, listing, versioning, retrieval, and deletion. ```swift // 1. Create initial skill let initialFiles = [ SkillFile(filename: "tool/SKILL.md", data: skillMarkdown, mimeType: "text/markdown") ] let createParam = SkillCreateParameter(displayTitle: "My Tool", files: initialFiles) let skill = try await service.createSkill(createParam) print("Created: \(skill.id) at \(skill.createdAt)") // 2. List all custom skills let listParam = ListSkillsParameter(source: .custom) let skillsList = try await service.listSkills(parameter: listParam) let found = skillsList.data.first { $0.id == skill.id } assert(found != nil, "Skill should be in custom list") // 3. Retrieve to check latest version let retrieved = try await service.retrieveSkill(skillId: skill.id) print("Latest version: \(retrieved.latestVersion ?? "none")") // 4. Create a new version let versionFiles = [ SkillFile(filename: "tool/SKILL.md", data: updatedMarkdown, mimeType: "text/markdown") ] let versionParam = SkillVersionCreateParameter(files: versionFiles) let newVersion = try await service.createSkillVersion(skillId: skill.id, versionParam) print("New version: \(newVersion.version)") // 5. List all versions let versions = try await service.listSkillVersions(skillId: skill.id, parameter: nil) print("Total versions: \(versions.data.count)") // 6. Retrieve specific version let specificVersion = try await service.retrieveSkillVersion( skillId: skill.id, version: newVersion.version ) print("Retrieved: \(specificVersion.createdAt)") // 7. Delete old version (if not the only one) if versions.data.count > 1, let oldVersion = versions.data.first { try await service.deleteSkillVersion(skillId: skill.id, version: oldVersion.version) print("Deleted old version") } // 8. Delete skill (all versions must be gone first) for version in try await service.listSkillVersions(skillId: skill.id, parameter: nil).data { try await service.deleteSkillVersion(skillId: skill.id, version: version.version) } try await service.deleteSkill(skillId: skill.id) print("Deleted skill") ``` -------------------------------- ### StreamHandler Initialization Example Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/StreamHandler.md Example of creating a new StreamHandler instance. ```swift let handler = StreamHandler() ``` -------------------------------- ### ListSkillsParameter Example Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/SkillParameter.md Example of listing skills, including filtering and pagination. ```swift // List all custom skills let param = ListSkillsParameter(source: .custom) let response = try await service.listSkills(parameter: param) for skill in response.data { print("\(skill.displayTitle ?? skill.id): \(skill.latestVersion ?? "N/A")") } // Pagination if let nextPage = response.nextPage { let nextParam = ListSkillsParameter(page: nextPage, limit: 10) let nextResponse = try await service.listSkills(parameter: nextParam) } ``` -------------------------------- ### Getting Thinking Blocks Example Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/StreamHandler.md Example of retrieving only thinking content blocks. ```swift let thinkingBlocks = handler.getThinkingBlocksForAPI() for block in thinkingBlocks { if case .thinking(let content, let signature) = block { print("Thinking: \(content)") } } ``` -------------------------------- ### Creating a Skill Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/SkillResponse.md Example of creating a skill. ```swift let param = SkillCreateParameter( displayTitle: "Data Processor", files: [skillFiles] ) let skill = try await service.createSkill(param) print("Created skill: \(skill.id)") print("Source: \(skill.source)") print("Created at: \(skill.createdAt)") ``` -------------------------------- ### Complete Example Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/StreamHandler.md A comprehensive example demonstrating streaming a message, handling text and tool calls, executing a tool, and continuing the conversation with the tool's result. ```swift let param = MessageParameter( model: .claude35Sonnet, messages: [ .init(role: .user, content: .text("What's the weather?")) ], maxTokens: 1024, tools: [weatherTool] ) let handler = StreamHandler() let stream = try await service.streamMessage(param) print("Streaming response...") for try await event in stream { handler.handleStreamEvent(event) // Print streamed text in real-time if event.streamEvent == .contentBlockDelta, let text = event.delta?.text { print(text, terminator: "") } } // After stream completes print("\nText response: \(handler.textResponse)") // Check for tool calls for toolUse in handler.getToolUseBlocks() { print("Tool called: \(toolUse.name)") // Execute the tool let result = try await executeWeatherTool(with: toolUse.input) // Continue conversation with tool result let nextParam = MessageParameter( model: .claude35Sonnet, messages: [ param.messages[0], // Original user message .init(role: .assistant, content: .list(handler.getContentBlocksForAPI())), .init(role: .user, content: .list([ .toolResult(toolUse.id, result) ])) ], maxTokens: 1024 ) let finalResponse = try await service.createMessage(nextParam) print("\nFinal response: \(finalResponse.content)") } ``` -------------------------------- ### Creating a Skill Version Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/SkillResponse.md Example of creating a skill version. ```swift let param = SkillVersionCreateParameter(files: updatedFiles) let version = try await service.createSkillVersion(skillId: "skill_123", param) print("Version created: \(version.version)") print("Version ID matches skill: \(version.id == "skill_123")") print("Type: \(version.type)") // Always "skill_version" ``` -------------------------------- ### Using the Text Editor Tool Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/README.md Example of how to provide the text editor tool to Claude for code assistance, including message creation, tool definition, parameter setup, and response processing. ```swift // Create a message asking Claude to help with code let messageParameter = MessageParameter.Message(role: .user, content: .text("There's a syntax error in my primes.py file. Can you help fix it?")) // Define the text editor tool using the hosted tool type let textEditorTool = MessageParameter.Tool.hosted( type: "text_editor_20250124", // Use the appropriate version for your model name: "str_replace_editor" ) // Create parameters including the tool let parameters = MessageParameter( model: .claude37Sonnet, messages: [messageParameter], maxTokens: 1024, tools: [textEditorTool] ) // Create message or stream let message = try await service.createMessage(parameters) // Process Claude's response for content in message.content { if case .toolUse(let id, let name, let input) = content { // Handle Claude's tool use request if let command = input["command"]?.stringValue { switch command { case "view": // Handle view file request // Read file and return contents to Claude case "str_replace": // Handle text replacement request // Replace text in file case "create": // Handle file creation request // Create new file case "insert": // Handle text insertion request // Insert text at specific location case "undo_edit": // Handle undo request // Revert last edit default: break } } } } ``` -------------------------------- ### Getting Content Blocks for API Example Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/StreamHandler.md Example of retrieving accumulated content blocks for an API call. ```swift let stream = try await service.streamMessage(param) for try await event in stream { handler.handleStreamEvent(event) } // Get accumulated blocks to send back in next message let blocks = handler.getContentBlocksForAPI() var nextMessages = messages nextMessages.append(.init(role: .assistant, content: .list(blocks))) ``` -------------------------------- ### Complete Skill Workflow Example Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/SkillParameter.md Demonstrates the full lifecycle of a skill, from creation to deletion, using Swift. ```swift import Foundation // 1. Create a skill let skillMarkdown = """ # Calculator Skill This skill provides mathematical operations. ## Functions - add(a, b): Add two numbers - multiply(a, b): Multiply two numbers """ let pythonCode = """ def add(a, b): return a + b def multiply(a, b): return a * b """ let files = [ SkillFile( filename: "calculator/SKILL.md", data: skillMarkdown.data(using: .utf8)!, mimeType: "text/markdown" ), SkillFile( filename: "calculator/calc.py", data: pythonCode.data(using: .utf8)!, mimeType: "text/x-python" ) ] let createParam = SkillCreateParameter( displayTitle: "Calculator", files: files ) let skill = try await service.createSkill(createParam) print("Created skill: \(skill.id)") // 2. List skills let listParam = ListSkillsParameter(source: .custom) let allSkills = try await service.listSkills(parameter: listParam) print("Total skills: \(allSkills.data.count)") // 3. Retrieve specific skill let retrieved = try await service.retrieveSkill(skillId: skill.id) print("Latest version: \(retrieved.latestVersion ?? \"N/A\")") // 4. Create a new version let updatedMarkdown = """ # Calculator Skill v2 Enhanced with more operations. """ let versionFiles = [ SkillFile( filename: "calculator/SKILL.md", data: updatedMarkdown.data(using: .utf8)!, mimeType: "text/markdown" ) ] let versionParam = SkillVersionCreateParameter(files: versionFiles) let newVersion = try await service.createSkillVersion(skillId: skill.id, versionParam) print("New version: \(newVersion.version)") // 5. List versions let versionsParam = ListSkillVersionsParameter() let versions = try await service.listSkillVersions(skillId: skill.id, parameter: versionsParam) print("Total versions: \(versions.data.count)") // 6. Delete version try await service.deleteSkillVersion(skillId: skill.id, version: newVersion.version) // 7. Delete skill try await service.deleteSkill(skillId: skill.id) ``` -------------------------------- ### Prompt Format Example Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/TextCompletionParameter.md An example of the prompt format for the text completion API. ```text Human: What is 2+2? Assistant: ``` -------------------------------- ### PDF Support Example Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/README.md Example of how to send a PDF document along with a text prompt to the API for analysis. ```swift let maxTokens = 1024 let prompt = "Please analyze this document" // Load PDF data let pdfData = // your PDF data let base64PDF = pdfData.base64EncodedString() // Create document source let documentSource = try MessageParameter.Message.Content.DocumentSource.pdf(base64Data: base64PDF) // Create message with document and prompt let message = MessageParameter.Message( role: .user, content: .list([ .document(documentSource), .text(prompt) ]) ) // Create parameters let parameters = MessageParameter( model: .claude35Sonnet, messages: [message], maxTokens: maxTokens ) // Send request let response = try await service.createMessage(parameters) ``` -------------------------------- ### Accessing Text Response Example Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/StreamHandler.md Example of getting the final accumulated text response. ```swift let stream = try await service.streamMessage(param) for try await event in stream { handler.handleStreamEvent(event) } let finalText = handler.textResponse print("Response: \(finalText)") ``` -------------------------------- ### Create Skill Response Example Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/endpoints.md Example JSON response when a skill is successfully created. ```json { "id": "skill_01JA...", "type": "skill", "display_title": "My Skill", "source": "custom", "latest_version": "1759178010641129", "created_at": "2024-10-30T23:58:27.427722Z", "updated_at": "2024-10-30T23:58:27.427722Z" } ``` -------------------------------- ### Getting Accumulated JSON for Tool Use Example Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/StreamHandler.md Example of retrieving the accumulated JSON for a specific tool use ID. ```swift if let json = handler.getAccumulatedJson(forToolUseId: "toolu_123") { if let data = json.data(using: .utf8), let params = try JSONSerialization.jsonObject(with: data) { print("Tool params: \(params)") } } ``` -------------------------------- ### Listing Skills Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/SkillResponse.md Example of listing skills. ```swift let response = try await service.listSkills(parameter: nil) print("Total skills in page: \(response.data.count)") print("More available: \(response.hasMore)") for skill in response.data { print("- \(skill.displayTitle ?? skill.id)") print(" Source: \(skill.source)") print(" Created: \(skill.createdAt)") } ``` -------------------------------- ### Count Tokens Usage Example Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/README.md Example of how to use the countTokens method. ```swift let messageParameter = MessageParameter.Message(role: .user, content: .text("Hello, Claude")) let parameters = MessageTokenCountParameter( model: .claude3Sonnet, messages: [messageParameter] ) let tokenCount = try await service.countTokens(parameter: parameters) print("Input tokens: \(tokenCount.inputTokens)") ``` -------------------------------- ### Basic Setup Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/README.md Demonstrates how to initialize the SwiftAnthropic service and make a basic message request to the Claude API. ```swift import SwiftAnthropic let service = AnthropicServiceFactory.service(apiKey: "sk-ant-...") let param = MessageParameter( model: .claude35Sonnet, messages: [ .init(role: .user, content: .text("Hello, Claude!")) ], maxTokens: 1024 ) let response = try await service.createMessage(param) print(response.content) ``` -------------------------------- ### Direct API Example Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/AnthropicServiceFactory.md Example usage of the service method for direct API access. ```swift let apiKey = "sk-ant-..." // from environment or secure storage let service = AnthropicServiceFactory.service(apiKey: apiKey) let messageParam = MessageParameter( model: .claude35Sonnet, messages: [.init(role: .user, content: .text("Hello Claude"))], maxTokens: 1024 ) let response = try await service.createMessage(messageParam) print(response.content) ``` -------------------------------- ### Text Completion Usage Example Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/README.md Example of how to use the TextCompletionParameter to create a text completion. ```swift let maxTokensToSample = 1024 let prompt = "\n\nHuman: Hello, Claude\n\nAssistant:" let parameters = TextCompletionParameter(model: .claude21, prompt: prompt, maxTokensToSample: 10) let textCompletion = try await service.createTextCompletion(parameters) ``` -------------------------------- ### AIProxy Example Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/AnthropicServiceFactory.md Example usage of the service method for AIProxy-based access. ```swift let service = AnthropicServiceFactory.service( aiproxyPartialKey: "your-partial-key", aiproxyServiceURL: "https://api.aiproxy.pro/v1/", aiproxyClientID: "optional-client-id" ) // Use service as normal; all requests go through AIProxy let messageParam = MessageParameter( model: .claude35Sonnet, messages: [.init(role: .user, content: .text("Query"))], maxTokens: 1024 ) let response = try await service.createMessage(messageParam) ``` -------------------------------- ### Message Usage Example Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/README.md Example of how to send a message and receive a streaming response. ```swift let maxTokens = 1024 let messageParameter = MessageParameter.Message(role: .user, content: "Hello, Claude") let parameters = MessageParameter(model: .claude21, messages: [messageParameter], maxTokens: maxTokens) let message = try await service.streamMessage(parameters) ``` -------------------------------- ### List Skills Response Example Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/endpoints.md Example JSON response when listing skills. ```json { "data": [ {"id": "skill_...", ...} ], "has_more": true, "next_page": "page_token_..." } ``` -------------------------------- ### Pagination Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/SkillResponse.md Example of paginating through skills. ```swift var allSkills: [SkillResponse] = [] var nextPageToken: String? = nil repeat { let param = ListSkillsParameter(page: nextPageToken, limit: 20) let response = try await service.listSkills(parameter: param) allSkills.append(contentsOf: response.data) nextPageToken = response.nextPage } while nextPageToken != nil print("Total skills: \(allSkills.count)") ``` -------------------------------- ### StreamHandler Example Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/StreamHandler.md Demonstrates how to use StreamHandler to process a stream, reset it, and process another stream. ```swift let handler = StreamHandler() // First stream let stream1 = try await service.streamMessage(param1) for try await event in stream1 { handler.handleStreamEvent(event) } let response1 = handler.textResponse // Reset and reuse handler.reset() // Second stream let stream2 = try await service.streamMessage(param2) for try await event in stream2 { handler.handleStreamEvent(event) } let response2 = handler.textResponse ``` -------------------------------- ### Retrieving a Skill Version Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/SkillResponse.md Example of retrieving a skill version. ```swift let version = try await service.retrieveSkillVersion( skillId: "skill_123", version: "1759178010641129" ) print("Retrieved version: \(version.version)") print("Skill display title: \(version.displayTitle ?? "untitled")") print("Created: \(version.createdAt)") ``` -------------------------------- ### Basic Text Streaming Example Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/MessageStreamResponse.md An example demonstrating how to process stream events for basic text streaming. ```swift let param = MessageParameter( model: .claude35Sonnet, messages: [.init(role: .user, content: .text("Write a story"))], maxTokens: 1024 ) let stream = try await service.streamMessage(param) for try await event in stream { switch event.streamEvent { case .messageStart: print("Stream started") case .contentBlockStart: guard let block = event.contentBlock else { break } print("Block type: \(block.type)") case .contentBlockDelta: guard let delta = event.delta else { break } if let text = delta.text { print(text, terminator: "") } case .contentBlockStop: print("\nBlock complete") case .messageDelta: if let stopReason = event.delta?.stopReason { print("Stop reason: \(stopReason)") } case .messageStop: print("Stream finished") default: break } } ``` -------------------------------- ### Counting with Tools Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/MessageTokenCountParameter.md An example showing how to count tokens when tools are defined. ```swift let tool = MessageParameter.Tool( name: "calculate", description: "Perform calculations", inputSchema: JSONSchema( type: .object, properties: [ "expression": .init(type: .string) ], required: ["expression"]) ) let param = MessageTokenCountParameter( model: .claude35Sonnet, messages: [ .init(role: .user, content: .text("Calculate 2^10")) ], tools: [tool] ) let tokenCount = try await service.countTokens(parameter: param) print("Tokens (with tools): \(tokenCount.inputTokens)") ``` -------------------------------- ### Example API Response with a Tool Use Content Block Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/README.md An example of an API response when Claude decides to use a tool, showing the structure of the tool_use content block. ```json { "id": "msg_01Aq9w938a90dw8q", "model": "claude-3-opus-20240229", "stop_reason": "tool_use", "role": "assistant", "content": [ { "type": "text", "text": "I need to use the get_weather, and the user wants SF, which is likely San Francisco, CA." }, { "type": "tool_use", "id": "toolu_01A09q90qw90lq917835lq9", "name": "get_weather", "input": {"location": "San Francisco, CA", "unit": "celsius"} } ] } ``` -------------------------------- ### Handling Text Response Example Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/MessageResponse.md Example of how to handle a text response from the Messages API. ```swift let response = try await service.createMessage(param) for content in response.content { switch content { case .text(let text, let citations): print("Response: \(text)") if let citations = citations { for citation in citations { print("Citation: \(citation.text)") } } default: break } } ``` -------------------------------- ### Retrieving a Skill Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/SkillResponse.md Example of retrieving a skill. ```swift let skill = try await service.retrieveSkill(skillId: "skill_123") print("Skill: \(skill.displayTitle ?? skill.id)") print("Latest version: \(skill.latestVersion ?? "none")") print("Last updated: \(skill.updatedAt)") ``` -------------------------------- ### Text Completion Stream Usage Example Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/README.md Example of how to use the TextCompletionParameter to create a streaming text completion. ```swift let maxTokensToSample = 1024 let prompt = "\n\nHuman: Hello, Claude\n\nAssistant:" let parameters = TextCompletionParameter(model: .claude21, prompt: prompt, maxTokensToSample: 10) let textStreamCompletion = try await service.createStreamTextCompletion(parameters) ``` -------------------------------- ### Vision Usage Example Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/README.md Example of how to send a message with an image and text for vision capabilities. ```swift let maxTokens = 1024 let prompt = "What is this image about?" let base64Image = "/9j/4AAQSkZJRg..." /// Define the image source let imageSource: MessageParameter.Message.Content.ContentObject = .image(.init(type: .base64, mediaType: .jpeg, data: base64Image)) /// Define the text message let text: MessageParameter.Message.Content.ContentObject = .text(prompt) /// Define the content for the message parameter let content: MessageParameter.Message.Content = list([imageSource, text]) /// Define the messages parameter let messagesParameter = [MessageParameter.Message(role: .user, content: content)] /// Define the parameters let parameters = MessageParameter(model: .claude3Sonnet, messages: messagesParameter, maxTokens: maxTokens) let message = try await service.streamMessage(parameters) ``` -------------------------------- ### Web Search Tool Initialization Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/README.md Example of initializing a web search tool with specific parameters like max uses, allowed domains, and user location. ```swift let webSearchTool = MessageParameter.webSearch( maxUses: 5, allowedDomains: ["wikipedia.org"], userLocation: .sanFrancisco ) let parameters = MessageParameter( model: .claude35Sonnet, messages: messages, maxTokens: 1024, tools: [webSearchTool]) ``` -------------------------------- ### Counting with System Prompt Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/MessageTokenCountParameter.md An example demonstrating token counting with a system prompt included. ```swift let param = MessageTokenCountParameter( model: .claude35Sonnet, messages: [ .init(role: .user, content: .text("Explain quantum computing")) ], system: .text("You are an expert physicist. Explain concepts clearly.") ) let tokenCount = try await service.countTokens(parameter: param) print("Total tokens: \(tokenCount.inputTokens)") ``` -------------------------------- ### Message Content Example Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/README.md Illustrates how the response content follows from the last turn, enabling continuous output. Includes examples for text and tool use. ```json [{"role": "user", "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun"}, {"role": "assistant", "content": "The best answer is ("}] ``` ```json [{"type": "text", "text": "B)"}] ``` ```json [{"type": "tool_use", "id": "toolu_01A09q90qw90lq917835lq9", "name": "get_weather", "input": { "location": "San Francisco, CA", "unit": "celsius"}}] ``` -------------------------------- ### Text Completion Response Example Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/endpoints.md Example JSON response for the Create Text Completion endpoint. ```json { "id": "cmpl_123...", "type": "completion", "completion": "The answer is...", "stop_reason": "stop_sequence", "model": "claude-2.1" } ``` -------------------------------- ### Citation Support Example Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/README.md Demonstrates how to enable citation support when sending a document to the Anthropic API. ```swift let maxTokens = 1024 let prompt = "Please analyze this document" // Load PDF data let pdfData = // your PDF data let base64PDF = pdfData.base64EncodedString() // Create document source let documentSource = try MessageParameter.Message.Content.DocumentSource.pdf(base64Data: base64PDF, citations: .init(enabled: true)) // Create message with document and prompt let message = MessageParameter.Message( role: .user, content: .list([ .document(documentSource), .text(prompt) ]) ) // Create parameters let parameters = MessageParameter( model: .claude35Sonnet, messages: [message], maxTokens: maxTokens ) // Send request let response = try await service.streamMessage(parameters) ``` -------------------------------- ### With User Metadata Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/TextCompletionParameter.md Example of text completion with user metadata. ```swift let userId = UUID() let param = TextCompletionParameter( model: .claude21, prompt: "\n\nHuman: Explain quantum computing.\n\nAssistant:", maxTokensToSample: 512, metadata: .init(userId: userId) ) let response = try await service.createTextCompletion(param) ``` -------------------------------- ### List Skills Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/README.md Examples of how to list skills using the SwiftAnthropic service, including listing all skills and listing with filters. ```swift // List all skills let allSkills = try await service.listSkills(parameter: nil) // List with filters let listParams = ListSkillsParameter( page: nil, limit: 20, source: .anthropic // or .custom for user-created skills ) let skills = try await service.listSkills(parameter: listParams) for skill in skills.data { print("Skill ID: \(skill.id)") print("Title: \(skill.displayTitle ?? "N/A")") print("Source: \(skill.source)") print("Latest Version: \(skill.latestVersion ?? "N/A")") } ``` -------------------------------- ### Web Search Tool Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/README.md Example of creating parameters and sending a request using a web search tool. ```swift // Create parameters let parameters = MessageParameter( model: .claude35Sonnet, messages: [message], maxTokens: maxTokens ) // Send request let response = try await service.createMessage(parameters) ``` -------------------------------- ### With Temperature Control Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/TextCompletionParameter.md Example of text completion with temperature control for creativity. ```swift let param = TextCompletionParameter( model: .claude21, prompt: "\n\nHuman: Write a creative story about a robot.\n\nAssistant:", maxTokensToSample: 512, temperature: 0.8 // More creative ) let response = try await service.createTextCompletion(param) print(response.completion) ``` -------------------------------- ### Model Selection Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/configuration.md Examples of how to specify the model for a MessageParameter, using an enum, a string, or a custom model identifier. ```swift // Using enum let param = MessageParameter( model: .claude35Sonnet, messages: [...], maxTokens: 1024 ) // Using string directly let param = MessageParameter( model: "claude-3-5-sonnet-latest", messages: [...], maxTokens: 1024 ) // Using custom model let param = MessageParameter( model: Model.other("custom-model").value, messages: [...], maxTokens: 1024 ) ``` -------------------------------- ### Using a Custom HTTP Client Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/configuration.md Illustrates implementing and using a custom HTTP client. ```swift public protocol HTTPClient { func data(for request: HTTPRequest) async throws -> (Data, HTTPResponse) func bytes(for request: HTTPRequest) async throws -> (HTTPByteStream, HTTPResponse) } // Custom implementation class CustomHTTPClient: HTTPClient { func data(for request: HTTPRequest) async throws -> (Data, HTTPResponse) { // Custom implementation: logging, caching, custom auth, etc. } func bytes(for request: HTTPRequest) async throws -> (HTTPByteStream, HTTPResponse) { // Custom streaming implementation } } // Use custom client let customClient = CustomHTTPClient() let service = AnthropicServiceFactory.service( apiKey: apiKey, httpClient: customClient ) ``` -------------------------------- ### Basic Error Catching Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/errors.md A simple example of how to catch and print any error that occurs during an API call. ```swift do { let response = try await service.createMessage(param) print(response.content) } catch { print("Error: \(error)") } ``` -------------------------------- ### Prompt Caching Token Counting Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/MessageTokenCountParameter.md An example demonstrating token counting with prompt caching. ```swift let cachedSystem = [ MessageParameter.Cache( type: .text, text: "[Large system prompt that will be cached...]", cacheControl: .init(type: "ephemeral") ) ] let param = MessageTokenCountParameter( model: .claude35Sonnet, messages: [...], system: .list(cachedSystem) ) let tokenCount = try await service.countTokens(parameter: param) print("Input tokens (will benefit from caching): \(tokenCount.inputTokens)") ``` -------------------------------- ### API Version Management Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/configuration.md Demonstrates setting the API version for service initialization. ```swift // Default - stable version let service = AnthropicServiceFactory.service( apiKey: apiKey, apiVersion: "2023-06-01" ) // Override for specific features let service = AnthropicServiceFactory.service( apiKey: apiKey, apiVersion: "2024-06-01" ) ``` -------------------------------- ### Beta Features Configuration Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/configuration.md Shows how to enable beta features using the betaHeaders parameter. ```swift // Extended thinking let service = AnthropicServiceFactory.service( apiKey: apiKey, betaHeaders: ["interleaved-thinking-2024-05-24"] ) // Vision with v1 features let service = AnthropicServiceFactory.service( apiKey: apiKey, betaHeaders: ["vision-2024-06-01"] ) // Multiple beta features let service = AnthropicServiceFactory.service( apiKey: apiKey, betaHeaders: [ "interleaved-thinking-2024-05-24", "vision-2024-06-01" ] ) ``` -------------------------------- ### Prompt Caching with Tool Results Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/README.md Example demonstrating prompt caching with tool results, showing cache control at the parent tool_result level. ```swift // Create tool result with cache control at the parent level let toolResult = MessageParameter.Message.Content.ContentObject.toolResult( "tool_123", "Large dataset response that should be cached", cacheControl: .init(type: .ephemeral) // Cache control now at parent tool_result level ) let message = MessageParameter.Message( role: .assistant, content: .list([toolResult]) ) // Include in subsequent message let userMessage = MessageParameter.Message( role: .user, content: .text("Please analyze the data from the previous tool result") ) let parameters = MessageParameter( model: .claude35Sonnet, messages: [message, userMessage], maxTokens: 1024 ) ``` -------------------------------- ### Basic Non-Streaming Example with Extended Thinking Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/README.md Demonstrates how to enable and use the extended thinking feature in a non-streaming API call. ```swift // Create a message with thinking enabled let userMessage = MessageParameter.Message( role: .user, content: .text("What would happen if we doubled the Earth's gravity overnight?") ) // Enable thinking with a budget of 16,000 tokens let parameters = MessageParameter( model: .claude37Sonnet, messages: [userMessage], maxTokens: 4000, thinking: .init(budgetTokens: 16000) ) // Make API call let response = try await service.createMessage(parameters) // Process the response var thinkingContent = "" var responseText = "" for content in response.content { switch content { case .text(let text, _): responseText = text print("Final answer: \(text)") case .thinking(let thinking): thinkingContent = thinking.thinking print("Thinking process: \(thinkingContent)") case .redactedThinking(_): print("Some thinking was redacted for safety reasons") default: break } } ``` -------------------------------- ### Providing Tools to Claude using the Messages API Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/README.md Example of how to define a tool (get_weather) and use it with the Messages API to get weather information. ```swift let maxTokens = 1024 let weatherTool = MessageParameter.Tool.function( name: "get_weather", description: "Get the current weather in a given location", inputSchema: .init( type: .object, properties: [ "location": .init(type: .string, description: "The city and state, e.g. San Francisco, CA"), "unit": .init(type: .string, description: "The unit of temperature, either celsius or fahrenheit") ], required: ["location"])) let messageParameter = MessageParameter.Message(role: .user, content: "What is the weather like in San Francisco?") let parameters = MessageParameter(model: .claude3Opus, messages: [messageParameter], maxTokens: maxTokens, tools: [weatherTool]) let message = try await service.createMessage(parameters) ``` -------------------------------- ### Handling requestFailed error Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/errors.md Example of how to catch and handle a network request failure. ```swift do { let response = try await service.createMessage(param) } catch APIError.requestFailed(let description) { print("Network error: \(description)") // Retry with backoff or inform user } ``` -------------------------------- ### Message with System Prompt Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/MessageParameter.md Shows how to include a system prompt to guide the assistant's behavior. ```swift let param = MessageParameter( model: "claude-3-5-sonnet-20241022", messages: [ .init(role: .user, content: .text("Translate to French: Hello")) ], maxTokens: 256, system: .text("You are a helpful translator. Respond only with the translation.") ) let response = try await service.createMessage(param) ``` -------------------------------- ### Creating a Message with Swift Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/README.md Example of how to create a message using the Swift Anthropic SDK, specifying model, messages, and max tokens. ```swift let maxTokens = 1024 let messageParameter = MessageParameter.Message(role: .user, content: "Hello, Claude") let parameters = MessageParameter(model: .claude21, messages: [messageParameter], maxTokens: maxTokens) let message = try await service.createMessage(parameters) ``` -------------------------------- ### Basic Usage of Skills API Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/README.md Example of creating a message that uses the 'xlsx' skill to create a budget spreadsheet. ```swift // Create a message with a skill let userMessage = MessageParameter.Message( role: .user, content: .text("Create a simple budget spreadsheet with income and expenses") ) // Create parameters with skill reference let parameters = MessageParameter( model: .claude37Sonnet, messages: [userMessage], maxTokens: 4096, tools: [.hosted(type: "code_execution_20250825", name: "code_execution")], container: .init( id: nil, // nil for first request, reuse container ID for subsequent requests skills: [ .init(type: .anthropic, skillId: "xlsx", version: "latest") ] ) ) // Create message let response = try await service.createMessage(parameters) // Extract container ID for reuse if let containerId = response.container?.id { // Save this ID to reuse in the next request for better performance print("Container ID: \(containerId)") } ``` -------------------------------- ### Platform-Specific Defaults Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/configuration.md Shows the default HTTP client adapters for Apple platforms and Linux. ```swift URLSessionHTTPClientAdapter(urlSession: URLSession.shared) ``` ```swift AsyncHTTPClientAdapter(...) ``` -------------------------------- ### Listing Skill Versions Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/SkillResponse.md Demonstrates how to list skill versions and print basic information about them. ```swift let response = try await service.listSkillVersions( skillId: "skill_123", parameter: ListSkillVersionsParameter(limit: 50) ) print("Total versions: \(response.data.count)") for version in response.data { print("- Version \(version.version): \(version.createdAt)") } ``` -------------------------------- ### Custom Logging HTTP Client Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/configuration.md Demonstrates how to create a logging wrapper around the default HTTP client to monitor outgoing requests and incoming response status codes. ```swift class LoggingHTTPClient: HTTPClient { private let wrapped: HTTPClient init(wrapped: HTTPClient) { self.wrapped = wrapped } func data(for request: HTTPRequest) async throws -> (Data, HTTPResponse) { print("→ \(request.method.rawValue) \(request.url.path)") let (data, response) = try await wrapped.data(for: request) print("← \(response.statusCode)") return (data, response) } func bytes(for request: HTTPRequest) async throws -> (HTTPByteStream, HTTPResponse) { print("→ Stream \(request.method.rawValue) \(request.url.path)") return try await wrapped.bytes(for: request) } } let defaultClient = HTTPClientFactory.createDefault() let loggingClient = LoggingHTTPClient(wrapped: defaultClient) let service = AnthropicServiceFactory.service( apiKey: apiKey, httpClient: loggingClient ) ``` -------------------------------- ### Handling Stream Events Example Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/StreamHandler.md Example of processing stream events using StreamHandler. ```swift let stream = try await service.streamMessage(param) for try await event in stream { handler.handleStreamEvent(event) } ``` -------------------------------- ### Direct API Configuration Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/configuration.md Initializes the AnthropicService with direct API configuration parameters. ```swift let service = AnthropicServiceFactory.service( apiKey: String, apiVersion: String = "2023-06-01", basePath: String = "https://api.anthropic.com", betaHeaders: [String]?, httpClient: HTTPClient? = nil, debugEnabled: Bool = false ) ``` -------------------------------- ### Linux HTTP Client Configuration Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/configuration.md Configures the Anthropic service with an AsyncHTTPClientAdapter for Linux. ```swift let service = AnthropicServiceFactory.service( apiKey: apiKey, httpClient: AsyncHTTPClientAdapter(...) ) ``` -------------------------------- ### Message Response Example Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/endpoints.md Example JSON response for the Create Message endpoint. ```json { "id": "msg_123...", "type": "message", "role": "assistant", "content": [ {"type": "text", "text": "..."} ], "stop_reason": "end_turn", "usage": { "input_tokens": 100, "output_tokens": 50 } } ``` -------------------------------- ### Secure API Key Loading Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/configuration.md Demonstrates loading the Anthropic API key from environment variables at runtime, with a fallback to fatalError if not set. ```swift // Recommended: Load from environment at runtime if let apiKey = ProcessInfo.processInfo.environment["ANTHROPIC_API_KEY"] { let service = AnthropicServiceFactory.service(apiKey: apiKey) } else { fatalError("ANTHROPIC_API_KEY not set") } ``` -------------------------------- ### Skills Container - Initialization Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/configuration.md Initializing a skills container for a request, which can be reused in subsequent requests. ```swift // First request initializes container let param1 = MessageParameter( model: .claude35Sonnet, messages: [...], maxTokens: 1024, container: .init(type: "bash") ) let response1 = try await service.createMessage(param1) let containerId = response1.container?.id ``` -------------------------------- ### AIProxy Configuration (Apple platforms only) Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/configuration.md Initializes the AnthropicService using AIProxy configuration for Apple platforms. ```swift #if !os(Linux) let service = AnthropicServiceFactory.service( aiproxyPartialKey: String, aiproxyServiceURL: String, aiproxyClientID: String? = nil, apiVersion: String = "2023-06-01", betaHeaders: [String]?, debugEnabled: Bool = false ) #endif ``` -------------------------------- ### Count Tokens Response Example Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/endpoints.md Example JSON response for the Count Message Tokens endpoint. ```json { "input_tokens": 1234 } ``` -------------------------------- ### Version Pagination Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/SkillResponse.md Shows how to paginate through all available skill versions. ```swift var allVersions: [SkillVersionResponse] = [] var pageToken: String? = nil repeat { let param = ListSkillVersionsParameter(page: pageToken) let response = try await service.listSkillVersions( skillId: "skill_123", parameter: param ) allVersions.append(contentsOf: response.data) pageToken = response.nextPage } while pageToken != nil print("Total versions: \(allVersions.count)") ``` -------------------------------- ### Create a Custom Skill Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/README.md Demonstrates how to create a new custom skill by providing its filename, content, and MIME type. ```swift // Prepare skill files let scriptContent = """\n#!/usr/bin/env python3 print(\"Hello from custom skill!\") """ let scriptData = scriptContent.data(using: .utf8)! let skillFile = SkillFile( filename: "main.py", data: scriptData, mimeType: "text/x-python" ) // Create skill let createParams = SkillCreateParameter( displayTitle: "My Custom Skill", files: [skillFile] ) let newSkill = try await service.createSkill(createParams) print("Created skill with ID: \(newSkill.id)") ``` -------------------------------- ### Sampling Control - Deterministic Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/configuration.md Configuring sampling parameters for deterministic output, suitable for analytical tasks, by setting temperature to 0.0. ```swift // Deterministic (analytical tasks) let param = MessageParameter( model: .claude35Sonnet, messages: [...], maxTokens: 1024, temperature: 0.0 // Deterministic ) ``` -------------------------------- ### Initializing AnthropicService with AIProxy Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/README.md Initialization of AnthropicService when using AIProxy, requiring partial key and service URL. ```swift let service = AnthropicServiceFactory.service( aiproxyPartialKey: "your_partial_key_goes_here", aiproxyServiceURL: "your_service_url_goes_here" ) ``` -------------------------------- ### Streaming Text Completion Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/TextCompletionParameter.md Example of streaming text completion. ```swift let param = TextCompletionParameter( model: .claude21, prompt: "\n\nHuman: Write a poem about nature.\n\nAssistant:", maxTokensToSample: 512 ) let stream = try await service.createStreamTextCompletion(param) for try await event in stream { if let completion = event.completion { print(completion, terminator: "") } } ``` -------------------------------- ### Cost Estimation Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/MessageTokenCountParameter.md An example of using token counting for cost estimation. ```swift let param = MessageTokenCountParameter( model: .claude35Sonnet, messages: messages ) let tokenCount = try await service.countTokens(parameter: param) let inputCost = Double(tokenCount.inputTokens) * 0.003 / 1000 // Claude 3.5 pricing print("Estimated input cost: $\(inputCost)") ``` -------------------------------- ### Multi-turn Conversation Counting Source: https://github.com/jamesrochabrun/swiftanthropic/blob/main/_autodocs/api-reference/MessageTokenCountParameter.md An example for counting tokens in a multi-turn conversation. ```swift let messages = [ MessageParameter.Message(role: .user, content: .text("What's AI?")), MessageParameter.Message(role: .assistant, content: .text("AI is artificial intelligence...")), MessageParameter.Message(role: .user, content: .text("Can you expand on machine learning?")) ] let param = MessageTokenCountParameter( model: .claude35Sonnet, messages: messages ) let tokenCount = try await service.countTokens(parameter: param) print("Conversation tokens: \(tokenCount.inputTokens)") ```