SPB Git

Repository Public License

AnthropicProvider.swift 20.1 KB 355 lines swift

1import Foundation23/// Anthropic Messages API (`POST /v1/messages`, server-sent events).4public struct AnthropicProvider: ChatProvider {5    public let family: ProviderFamily = .anthropic67    /// The `anthropic-version` this adapter is written for. On this version the API rejects `temperature`, `top_p`8    /// and `top_k`, so sampling parameters are never sent.9    public static let apiVersion = "2026-10-21"10    /// `max_tokens` is mandatory; used when neither the request nor the configuration sets one.11    public static let defaultMaxOutputTokens = 16_0001213    static let thinkingStateFormat = "anthropic.thinking"1415    private let http: ProviderHTTP16    private let apiKey: KeySource17    private let baseURL: URL1819    public init(apiKey: @escaping KeySource, baseURL: URL? = nil, environment: ProviderEnvironment = ProviderEnvironment()) {20        self.http = ProviderHTTP(family: .anthropic, environment: environment)21        self.apiKey = apiKey22        self.baseURL = baseURL ?? ProviderFamily.anthropic.defaultBaseURL!23    }2425    static func headers(_ key: String) -> [String: String] { ["x-api-key": key, "anthropic-version": apiVersion] }2627    // MARK: Models2829    public func listModels() async throws -> [ModelInfo] {30        let key = try await resolveKey(apiKey, family: family, required: true) ?? ""31        var out: [ModelInfo] = []32        var after: String?33        for _ in 0..<20 {   // pages; the bound only guards against a server that never ends34            var components = URLComponents(url: baseURL.appendingPathComponent("models"), resolvingAgainstBaseURL: false)!35            components.queryItems = [URLQueryItem(name: "limit", value: "1000")] + (after.map { [URLQueryItem(name: "after_id", value: $0)] } ?? [])36            let json = try await http.json(ProviderHTTP.request(components.url!, headers: Self.headers(key), timeout: http.environment.timeouts.request), secrets: [key])37            guard let data = json["data"]?.arrayValue else { throw ProviderError.malformedResponse("the model list has no data array.") }38            out += data.compactMap(Self.modelInfo)39            guard json["has_more"]?.boolValue == true, let last = json["last_id"]?.stringValue, last != after else { break }40            after = last41        }42        return out43    }4445    static func modelInfo(_ entry: JSONValue) -> ModelInfo? {46        guard let id = entry["id"]?.stringValue else { return nil }47        return ModelInfo(id: id, displayName: entry["display_name"]?.stringValue,48                         contextLength: entry["max_input_tokens"]?.intValue, maxOutputTokens: entry["max_tokens"]?.intValue,49                         supportsTools: nil,   // the capability tree does not list tool calling50                         supportsImages: entry["capabilities"]?["image_input"]?["supported"]?.boolValue,51                         createdAt: entry["created_at"]?.stringValue.flatMap { ISO8601DateFormatter().date(from: $0) })52    }5354    public func testConnection() async throws -> ConnectionReport {55        let started = Date()56        let models = try await listModels()57        return ConnectionReport(family: family, summary: "Key accepted. \(models.count) models available.", modelCount: models.count,58                                latencyMilliseconds: Int(Date().timeIntervalSince(started) * 1_000))59    }6061    // MARK: Request6263    static func body(_ request: ChatRequest) -> [String: JSONValue] {64        var body: [String: JSONValue] = [65            "model": .string(request.model), "stream": true, "messages": .array(messages(request.conversation)),66            "max_tokens": .number(Double(request.options.maxOutputTokens ?? defaultMaxOutputTokens)),67        ]68        if let system = request.combinedSystem { body["system"] = .string(system) }69        if !request.tools.isEmpty {70            // Eager input streaming delivers tool arguments as they are generated; the accumulated JSON is parsed and71            // checked when the block closes (see `ToolCall.hasValidArguments`).72            body["tools"] = .array(request.tools.map { tool in73                ["name": .string(tool.name), "description": .string(tool.description), "input_schema": tool.parameters, "eager_input_streaming": true]74            })75        }76        if !request.options.stop.isEmpty { body["stop_sequences"] = .array(request.options.stop.prefix(4).map(JSONValue.string)) }77        // Thinking is left at the model's default unless the user chose an effort. Both fields are dropped again if78        // the model refuses them (see `adjust`).79        if let effort = request.options.reasoningEffort {80            body["thinking"] = ["type": "adaptive", "display": "summarized"]81            body["output_config"] = ["effort": .string(effort.rawValue)]82        }83        // A conversation in progress is resent in full with every request. Automatic caching moves a breakpoint to84        // its end, so the next request reads the history at the cache price. A single opening message is left85        // alone: caching it would cost the write premium for a prefix that may never be read.86        if request.conversation.count > 1 { body["cache_control"] = ["type": "ephemeral"] }87        return body88    }8990    private static let thinkingBlockTypes: Set<String> = ["thinking", "redacted_thinking"]91    static func isThinkingBlock(_ block: JSONValue) -> Bool { block["type"]?.stringValue.map(thinkingBlockTypes.contains) ?? false }9293    static func messages(_ messages: [ChatMessage]) -> [JSONValue] {94        var turns: [(role: String, content: [JSONValue])] = []95        // The API wants alternating roles; consecutive blocks of one role are merged (several tool results answer96        // one assistant turn in a single user message).97        func append(_ role: String, _ blocks: [JSONValue]) {98            guard !blocks.isEmpty else { return }99            if let last = turns.last, last.role == role { turns[turns.count - 1].content += blocks } else { turns.append((role, blocks)) }100        }101        func blocks(_ parts: [ContentPart]) -> [JSONValue] {102            parts.compactMap { part in103                switch part {104                case .text(let text): text.isEmpty ? nil : ["type": "text", "text": .string(text)]105                case .image(let image):106                    ["type": "image", "source": ["type": "base64", "media_type": .string(image.mimeType), "data": .string(image.data.base64EncodedString())]]107                }108            }109        }110        // Thinking blocks are replayed for the tool cycle in progress only: the assistant turns after the last user message.111        let cycleStart = messages.lastIndex { $0.role == .user } ?? -1112        for (position, message) in messages.enumerated() {113            switch message.role {114            case .system: break   // folded into the top-level system prompt by `ChatRequest.combinedSystem`115            case .user: append("user", blocks(message.parts))116            case .assistant:117                // The order the model produced: thinking, text, tool_use.118                func thinking(_ call: ToolCall) -> [JSONValue] {119                    guard position > cycleStart else { return [] }120                    return (ProviderState.payload(call, format: thinkingStateFormat)?.arrayValue ?? []).filter(isThinkingBlock)121                }122                var content: [JSONValue] = message.toolCalls.first.map(thinking) ?? []123                if !message.text.isEmpty { content.append(["type": "text", "text": .string(message.text)]) }124                for (index, call) in message.toolCalls.enumerated() {125                    if index > 0 { content += thinking(call) }126                    content.append(["type": "tool_use", "id": .string(call.id), "name": .string(call.name),127                                    "input": call.hasValidArguments ? call.arguments : .object([:])])128                }129                append("assistant", content)130            case .tool:131                var result: [String: JSONValue] = ["type": "tool_result", "tool_use_id": .string(message.toolCallID ?? "")]132                result["content"] = message.images.isEmpty ? .string(message.text) : .array(blocks(message.parts))133                if message.isError { result["is_error"] = true }134                append("user", [.object(result)])135            }136        }137        return turns.map { ["role": .string($0.role), "content": .array($0.content)] }138    }139140    /// Drops what a model or platform refused. Returns `true` when the body changed and should be sent again.141    static func adjust(_ failure: ProviderHTTP.Failure, _ body: inout [String: JSONValue]) -> Bool {142        guard failure.status == 400 else { return false }143        let message = (failure.body.message ?? "").lowercased()144        let replaysThinking = (body["messages"]?.arrayValue ?? []).contains { ($0["content"]?.arrayValue ?? []).contains(where: isThinkingBlock) }145        if replaysThinking, message.contains("signature") || message.contains("redacted_thinking") || message.contains("thinking block")146            || message.contains("thinking` block") {147            // The documented recovery: answer this turn without the replayed reasoning.148            if case .array(let messages)? = body["messages"] {149                body["messages"] = .array(messages.map { message in150                    guard case .object(var fields) = message, case .array(let content)? = fields["content"] else { return message }151                    fields["content"] = .array(content.filter { !isThinkingBlock($0) })152                    return .object(fields)153                })154            }155            return true156        }157        // A platform or proxy that does not take request-level caching.158        if body["cache_control"] != nil, message.contains("cache_control") { body.removeValue(forKey: "cache_control"); return true }159        if body["tools"]?[0]?["eager_input_streaming"] != nil, message.contains("eager_input_streaming"), case .array(let tools)? = body["tools"] {160            body["tools"] = .array(tools.map { tool in161                guard case .object(var fields) = tool else { return tool }162                fields.removeValue(forKey: "eager_input_streaming")163                return .object(fields)164            })165            return true166        }167        if body["output_config"] != nil, message.contains("output_config") || message.contains("effort") { body.removeValue(forKey: "output_config"); return true }168        if body["thinking"] != nil, message.contains("thinking") { body.removeValue(forKey: "thinking"); return true }169        return false170    }171172    // MARK: Stream173174    public func stream(_ request: ChatRequest) -> AsyncThrowingStream<ChatEvent, Error> {175        let http = http, apiKey = apiKey, url = baseURL.appendingPathComponent("messages")176        let secrets = SecretBox()177        return makeEventStream(secrets: secrets) { continuation in178            let key = try await resolveKey(apiKey, family: .anthropic, required: true) ?? ""179            secrets.add(key)180            var headers = Self.headers(key)181            headers["Accept"] = "text/event-stream"182            let timeout = http.environment.timeouts.streamIdle183            let chunks = try await http.openAdjusting(body: Self.body(request), model: request.model, secrets: [key], makeRequest: { body in184                ProviderHTTP.request(url, method: "POST", headers: headers, body: body, timeout: timeout)185            }, adjust: Self.adjust)186            var parser = SSEParser()187            var decoder = AnthropicStreamDecoder(model: request.model)188            for try await chunk in chunks {189                for event in try parser.feed(chunk) {190                    for out in try decoder.consume(event) { continuation.yield(out) }191                    if decoder.finished { return }192                }193            }194            try Task.checkCancellation()195            if let event = parser.finish() { for out in try decoder.consume(event) { continuation.yield(out) } }196            if !decoder.finished { throw ProviderError.connectionClosedEarly }197        }198    }199}200201/// Turns Messages API stream events into `ChatEvent`s.202struct AnthropicStreamDecoder {203    private enum Block {204        case text205        case thinking(text: String, signature: String)206        case tool(id: String, name: String, json: String)207        case other208    }209210    let model: String211    private(set) var started = false212    private(set) var finished = false213    private var blocks: [Int: Block] = [:]214    private var finishReason: FinishReason?215    private var usage = ProviderUsage()216    private var thinkingBlocks = 0217    /// Thinking blocks produced since the last tool call; they ride on the next call so they can be sent back unchanged.218    private var pendingThinking: [JSONValue] = []219220    init(model: String) { self.model = model }221222    private mutating func completedCall(id: String, name: String, json: String) -> ChatEvent {223        let state = ProviderState.make(AnthropicProvider.thinkingStateFormat, .array(pendingThinking))224        pendingThinking.removeAll()225        return .toolCallCompleted(ToolCall(id: id, name: name, streamedArguments: json, providerState: state))226    }227228    mutating func consume(_ event: SSEEvent) throws -> [ChatEvent] {229        guard let json = JSONValue.parse(event.data) else { throw ProviderError.malformedResponse("a stream event was not valid JSON.") }230        var out: [ChatEvent] = []231        switch json["type"]?.stringValue ?? event.event ?? "" {232        case "message_start":233            let message = json["message"]234            if !started {235                started = true236                out.append(.started(ResponseStart(responseID: message?["id"]?.stringValue, model: message?["model"]?.stringValue)))237            }238            if let reported = Self.usage(message?["usage"]) { usage = usage.merged(with: reported); out.append(.usage(usage)) }239        case "content_block_start":240            guard let index = json["index"]?.intValue else { break }241            let block = json["content_block"]242            switch block?["type"]?.stringValue {243            case "text":244                blocks[index] = .text245                if let text = block?["text"]?.stringValue, !text.isEmpty { out.append(.textDelta(text)) }246            case "thinking":247                blocks[index] = .thinking(text: block?["thinking"]?.stringValue ?? "", signature: block?["signature"]?.stringValue ?? "")248                thinkingBlocks += 1249                if thinkingBlocks > 1 { out.append(.reasoningDelta("\n\n")) }250                if let text = block?["thinking"]?.stringValue, !text.isEmpty { out.append(.reasoningDelta(text)) }251            case "redacted_thinking":252                blocks[index] = .other   // nothing to show; the opaque block is kept for replay253                if let block, block["data"]?.stringValue?.isEmpty == false { pendingThinking.append(block) }254            case "tool_use":255                let id = block?["id"]?.stringValue ?? "toolu_\(index)", name = block?["name"]?.stringValue ?? ""256                // Without eager streaming a non-empty `input` can arrive whole in the start event.257                var initial = ""258                if let input = block?["input"], let fields = input.objectValue, !fields.isEmpty { initial = input.serialized() }259                blocks[index] = .tool(id: id, name: name, json: initial)260                out.append(.toolCallStarted(id: id, name: name))261                if !initial.isEmpty { out.append(.toolCallArgumentsDelta(id: id, fragment: initial)) }262            default:263                blocks[index] = .other   // server tool blocks and block types added later: nothing to show264            }265        case "content_block_delta":266            guard let index = json["index"]?.intValue, let delta = json["delta"] else { break }267            switch delta["type"]?.stringValue {268            case "text_delta":269                if let text = delta["text"]?.stringValue, !text.isEmpty { out.append(.textDelta(text)) }270            case "thinking_delta":271                if let text = delta["thinking"]?.stringValue, !text.isEmpty {272                    out.append(.reasoningDelta(text))273                    if case .thinking(let soFar, let signature)? = blocks[index] { blocks[index] = .thinking(text: soFar + text, signature: signature) }274                }275            case "signature_delta":276                // Integrity data: never shown, kept so the block can be sent back unchanged.277                if case .thinking(let text, let soFar)? = blocks[index], let part = delta["signature"]?.stringValue {278                    blocks[index] = .thinking(text: text, signature: soFar + part)279                }280            case "input_json_delta":281                guard case .tool(let id, let name, let buffer)? = blocks[index], let fragment = delta["partial_json"]?.stringValue else { break }282                blocks[index] = .tool(id: id, name: name, json: buffer + fragment)283                if !fragment.isEmpty { out.append(.toolCallArgumentsDelta(id: id, fragment: fragment)) }284            default:285                break   // citations_delta and delta types added later286            }287        case "content_block_stop":288            guard let index = json["index"]?.intValue else { break }289            if case .tool(let id, let name, let buffer)? = blocks[index] {290                out.append(completedCall(id: id, name: name, json: buffer))291            } else if case .thinking(let text, let signature)? = blocks[index], !signature.isEmpty {292                pendingThinking.append(["type": "thinking", "thinking": .string(text), "signature": .string(signature)])293            }294            blocks[index] = nil295        case "message_delta":296            if let reason = json["delta"]?["stop_reason"]?.stringValue { finishReason = Self.finishReason(reason) }297            if let reported = Self.usage(json["usage"]) { usage = usage.merged(with: reported); out.append(.usage(usage)) }298        case "message_stop":299            // A tool call cut off by max_tokens never got its block stop: close it so the stream stays well formed.300            // Its arguments are incomplete JSON, which `ToolCall.hasValidArguments` reports.301            for (_, block) in blocks.sorted(by: { $0.key < $1.key }) {302                if case .tool(let id, let name, let buffer) = block { out.append(completedCall(id: id, name: name, json: buffer)) }303            }304            blocks.removeAll()305            out.append(.finished(finishReason ?? .unknown))306            finished = true307        case "error":308            let error = json["error"]309            throw Self.streamError(type: error?["type"]?.stringValue, message: error?["message"]?.stringValue, model: model)310        default:311            break   // ping and event types added later312        }313        return out314    }315316    static func finishReason(_ raw: String) -> FinishReason {317        switch raw {318        case "end_turn", "pause_turn": .endOfTurn319        case "max_tokens", "model_context_window_exceeded": .maxTokens320        case "tool_use": .toolCalls321        case "stop_sequence": .stopSequence322        case "refusal": .contentFilter323        default: .unknown324        }325    }326327    /// `input_tokens` excludes cached tokens on this API; the neutral model counts them in `inputTokens`.328    static func usage(_ json: JSONValue?) -> ProviderUsage? {329        guard let json, json.objectValue != nil else { return nil }330        let read = json["cache_read_input_tokens"]?.intValue331        let write = json["cache_creation_input_tokens"]?.intValue332        let total = json["input_tokens"]?.intValue.map { $0 + (read ?? 0) + (write ?? 0) }333        let usage = ProviderUsage(inputTokens: total, outputTokens: json["output_tokens"]?.intValue,334                                  cacheReadTokens: total == nil ? nil : read, cacheWriteTokens: total == nil ? nil : write)335        return usage.isReported ? usage : nil336    }337338    /// An `error` event inside a 200 stream, mapped like the HTTP status it stands for.339    static func streamError(type: String?, message: String?, model: String) -> ProviderError {340        let status: Int = switch type {341        case "overloaded_error": 529342        case "rate_limit_error": 429343        case "invalid_request_error": 400344        case "authentication_error": 401345        case "billing_error": 402346        case "permission_error": 403347        case "not_found_error": 404348        case "request_too_large": 413349        case "timeout_error": 408350        default: 500351        }352        return .http(status: status, code: type, message: message, retryAfter: nil, model: model)353    }354}355
Files main
Menu

Theme