Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Astra9// File : Packages/AstraProviders/Sources/AnthropicProvider.swift10// Module : Packages11// Repository : https://git.spboucher.ai/orix-astra12// Created : 2026-11-2113// Last Modified : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author : Simon-Pierre Boucher20// Position : Professor of Finance21// Institution : Université du Québec en Outaouais (UQO)22// Department : Département des sciences administratives23// Organization : SP Boucher24//25// Website : https://spboucher.ai26// Git : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General : info@spboucher.ai33// Professional : contact@spboucher.ai34// Direct : simon@spboucher.ai35// Research : research@spboucher.ai36// Development : dev@spboucher.ai37// Support : support@spboucher.ai38// Security/Admin : admin@spboucher.ai39// Notifications : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification : Public66// Distribution : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License : Proprietary, all rights reserved (see license file)80// License File : LICENSE81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import AstraCore89import Foundation9091/// Anthropic through the Messages API (`POST /v1/messages`, `anthropic-version: 2026-10-21`).92///93/// Choices worth knowing:94/// - Sampling parameters are never sent: API version 2026-10-21 rejects `temperature`, `top_p` and `top_k` on every model.95/// - Thinking blocks of the tool cycle in progress are replayed verbatim, with their signatures, ahead of the `tool_use`96/// block they preceded. They travel in `ToolCall.providerState`. Only the trailing cycle (the assistant turns after the97/// last user message) carries them: a plain answer has no tool call to hold its blocks, and the API accepts a leading98/// run of thinking blocks being absent but not a gap in the middle. Because the app may trim or edit history, requests99/// that replay blocks ask the API to drop a block that no longer matches its conversation instead of failing100/// (`thinking.block_binding`, beta `thinking-binding-controls-2026-08-01`); a signature the API still refuses is101/// answered by removing the replayed blocks and retrying once, which is the behaviour of a call without state.102/// - Thinking text reaches the app only as the summary the API returns (`display: "summarized"`), as `.reasoningSummaryDelta`.103/// - Server-side refusal fallbacks are not enabled: the model that answers is always the model that was requested.104public struct AnthropicProvider: ChatProvider {105 public let kind: ProviderKind = .anthropic106 public static let defaultBaseURL = URL(string: "https://api.anthropic.com/v1")!107 public static let apiVersion = "2026-10-21"108109 private let http: ProviderHTTP110 private let apiKey: KeyProvider111 private let baseURL: URL112113 public init(transport: any HTTPTransport, apiKey: @escaping KeyProvider, diagnostics: (any DiagnosticsSink)? = nil, baseURL: URL = AnthropicProvider.defaultBaseURL) {114 self.http = ProviderHTTP(kind: .anthropic, transport: transport, diagnostics: diagnostics)115 self.apiKey = apiKey116 self.baseURL = baseURL117 }118119 static func headers(_ key: String) -> [String: String] { ["x-api-key": key, "anthropic-version": apiVersion] }120121 static let thinkingStateFormat = "anthropic.thinking"122 static let bindingControlsBeta = "thinking-binding-controls-2026-08-01"123 private static let thinkingBlockTypes: Set<String> = ["thinking", "redacted_thinking"]124125 static func isThinkingBlock(_ block: JSONValue) -> Bool { block["type"]?.stringValue.map(thinkingBlockTypes.contains) ?? false }126127 static func replaysThinking(_ body: [String: JSONValue]) -> Bool {128 (body["messages"]?.arrayValue ?? []).contains { ($0["content"]?.arrayValue ?? []).contains(where: isThinkingBlock) }129 }130131 /// Removes every replayed thinking block (and the binding control that goes with them) from a request body.132 static func stripThinkingBlocks(_ body: inout [String: JSONValue]) {133 guard case .array(let messages)? = body["messages"] else { return }134 body["messages"] = .array(messages.map { message in135 guard case .object(var fields) = message, case .array(let content)? = fields["content"] else { return message }136 fields["content"] = .array(content.filter { !isThinkingBlock($0) })137 return .object(fields)138 })139 removeBlockBinding(&body)140 }141142 static func removeBlockBinding(_ body: inout [String: JSONValue]) {143 guard case .object(var thinking)? = body["thinking"], thinking["block_binding"] != nil else { return }144 thinking.removeValue(forKey: "block_binding")145 body["thinking"] = .object(thinking)146 }147148 // MARK: Models149150 public func listModels() async throws -> [ModelInfo] {151 let key = try resolveKey(apiKey, kind: kind, required: true) ?? ""152 var out: [ModelInfo] = []153 var after: String?154 let fetchedAt = Date()155 for _ in 0..<20 {156 var components = URLComponents(url: baseURL.appendingPathComponent("models"), resolvingAgainstBaseURL: false)!157 components.queryItems = [URLQueryItem(name: "limit", value: "1000")] + (after.map { [URLQueryItem(name: "after_id", value: $0)] } ?? [])158 let (json, _) = try await http.json(ProviderHTTP.request(components.url!, headers: Self.headers(key)), secrets: [key])159 guard let data = json["data"]?.arrayValue else { throw AstraError.decoding("the model list has no data array") }160 out += data.compactMap { Self.modelInfo($0, fetchedAt: fetchedAt) }161 guard json["has_more"]?.boolValue == true, let last = json["last_id"]?.stringValue, last != after else { break }162 after = last163 }164 return out165 }166167 static func modelInfo(_ entry: JSONValue, fetchedAt: Date) -> ModelInfo? {168 guard let id = entry["id"]?.stringValue else { return nil }169 let ref = ModelRef(provider: .anthropic, modelID: id)170 let created = entry["created_at"]?.stringValue.flatMap { ISO8601DateFormatter().date(from: $0) }171 let name = entry["display_name"]?.stringValue172 if var info = CuratedCatalog.info(for: ref) {173 // Limits the API reports today win over the curated copy.174 info.displayName = name ?? info.displayName175 info.contextLength = entry["max_input_tokens"]?.intValue ?? info.contextLength176 info.maxOutputTokens = entry["max_tokens"]?.intValue ?? info.maxOutputTokens177 info.createdAt = created178 return info179 }180 // Unknown to the curated table: claim only what the API itself reports.181 var capabilities: Set<Capability> = [.text]182 let reported = entry["capabilities"]183 if reported?["image_input"]?["supported"]?.boolValue == true { capabilities.insert(.vision) }184 if reported?["pdf_input"]?["supported"]?.boolValue == true { capabilities.insert(.documents) }185 if reported?["structured_outputs"]?["supported"]?.boolValue == true { capabilities.insert(.structuredOutput) }186 if reported?["thinking"]?["supported"]?.boolValue == true { capabilities.insert(.reasoning) }187 return ModelInfo(ref: ref, displayName: name ?? id, contextLength: entry["max_input_tokens"]?.intValue, maxOutputTokens: entry["max_tokens"]?.intValue,188 capabilities: capabilities, source: .providerAPI(fetchedAt: fetchedAt), vendor: "anthropic", createdAt: created)189 }190191 public func verify() async throws -> ConnectionStatus {192 let models = try await listModels()193 return ConnectionStatus(ok: true, detail: "Key accepted. \(models.count) models available.", modelCount: models.count)194 }195196 // MARK: Request197198 static func body(_ request: GenerationRequest) -> [String: JSONValue] {199 let modelID = request.model.modelID200 let entry = CuratedCatalog.anthropic(modelID)201 var body: [String: JSONValue] = ["model": .string(modelID), "stream": true, "messages": .array(messages(request.messages))]202203 if let system = request.system?.trimmingCharacters(in: .whitespacesAndNewlines), !system.isEmpty {204 var block: [String: JSONValue] = ["type": "text", "text": .string(system)]205 // Cache the stable prefix (tools, then system) when it is long enough for this model to store.206 let prefixTokens = TokenEstimator.estimate(system) + request.tools.reduce(0) { $0 + TokenEstimator.estimate($1.summary) + TokenEstimator.estimate($1.parameters.serialized()) }207 if prefixTokens >= (entry?.cacheMinimumTokens ?? 4096) { block["cache_control"] = ["type": "ephemeral"] }208 body["system"] = [.object(block)]209 }210 if !request.tools.isEmpty {211 body["tools"] = .array(request.tools.map { tool in212 ["name": .string(tool.name), "description": .string(tool.summary), "input_schema": tool.parameters, "eager_input_streaming": true]213 })214 }215 if !request.parameters.stop.isEmpty { body["stop_sequences"] = .array(request.parameters.stop.prefix(4).map(JSONValue.string)) }216217 var maxTokens = request.parameters.maxOutputTokens ?? min(entry?.maxOutputTokens ?? 4096, 16_000)218 let effort = request.parameters.reasoning219 switch entry?.thinking {220 case .adaptive(let off, let onByDefault, let summaryOptIn):221 var thinking: [String: JSONValue] = ["type": "adaptive"]222 if summaryOptIn { thinking["display"] = "summarized" }223 switch effort {224 case nil:225 if onByDefault { body["thinking"] = .object(thinking) }226 case .off?:227 switch off {228 case .disabled: body["thinking"] = ["type": "disabled"]229 case .betweenTools: body["thinking"] = ["type": "between_tools"]230 case .unavailable:231 body["thinking"] = .object(thinking)232 body["output_config"] = ["effort": "low"]233 }234 case let level?:235 body["thinking"] = .object(thinking)236 if entry?.effort == true { body["output_config"] = ["effort": .string(level.rawValue)] }237 }238 case .budget:239 if let effort, effort != .off {240 let budget = effort == .low ? 1024 : effort == .medium ? 4096 : 16_000241 body["thinking"] = ["type": "enabled", "budget_tokens": .number(Double(budget))]242 // The budget must stay below max_tokens and should not eat the answer; the sum must not pass what the model accepts.243 let cap = entry?.maxOutputTokens ?? .max244 maxTokens = min(cap, maxTokens + budget)245 if budget >= maxTokens { body["thinking"] = ["type": "enabled", "budget_tokens": .number(Double(max(1024, maxTokens / 2)))] }246 }247 case nil:248 // A model this build does not know: ask for adaptive thinking only when the user asked for reasoning; removed on a 400.249 if let effort, effort != .off {250 body["thinking"] = ["type": "adaptive", "display": "summarized"]251 body["output_config"] = ["effort": .string(effort.rawValue)]252 }253 }254 body["max_tokens"] = .number(Double(maxTokens))255 // Replayed blocks are bound to the conversation that produced them. If the app changed anything before them, have256 // the API drop them rather than refuse the request. Only adaptive thinking takes the control.257 if replaysThinking(body), case .object(var thinking)? = body["thinking"], thinking["type"] == "adaptive" {258 thinking["block_binding"] = ["prefix_mismatch_behavior": "drop_block"]259 body["thinking"] = .object(thinking)260 }261 return body262 }263264 /// Roles must alternate and tool results travel in a user turn: consecutive turns of the same wire role are merged,265 /// so several tool results (and a user message that follows them) become one user turn with the results first.266 static func messages(_ messages: [PromptMessage]) -> [JSONValue] {267 var turns: [(role: String, content: [JSONValue])] = []268 func append(_ role: String, _ blocks: [JSONValue]) {269 guard !blocks.isEmpty else { return }270 if let last = turns.last, last.role == role { turns[turns.count - 1].content += blocks } else { turns.append((role, blocks)) }271 }272 // Thinking blocks are replayed for the tool cycle in progress only: the assistant turns after the last user message.273 let cycleStart = messages.lastIndex { $0.role == .user } ?? -1274 for (position, message) in messages.enumerated() {275 switch message.role {276 case .user:277 var blocks: [JSONValue] = message.images.map { image in278 ["type": "image", "source": ["type": "base64", "media_type": .string(image.mimeType), "data": .string(image.data.base64EncodedString())]]279 }280 if !message.text.isEmpty { blocks.append(["type": "text", "text": .string(message.text)]) }281 append("user", blocks)282 case .assistant:283 // The order the model produced: thinking, text, tool_use; with interleaved thinking, more thinking before a later tool_use.284 func thinking(_ call: ToolCall) -> [JSONValue] {285 guard position > cycleStart else { return [] }286 return (ProviderState.payload(call, format: thinkingStateFormat)?.arrayValue ?? []).filter(isThinkingBlock)287 }288 var blocks: [JSONValue] = message.toolCalls.first.map(thinking) ?? []289 if !message.text.isEmpty { blocks.append(["type": "text", "text": .string(message.text)]) }290 for (index, call) in message.toolCalls.enumerated() {291 if index > 0 { blocks += thinking(call) }292 blocks.append(["type": "tool_use", "id": .string(call.id), "name": .string(call.name), "input": ToolArguments.wireObject(call.arguments)])293 }294 append("assistant", blocks)295 case .tool:296 var block: [String: JSONValue] = ["type": "tool_result", "tool_use_id": .string(message.toolCallID ?? ""), "content": .string(message.text)]297 if message.toolIsError { block["is_error"] = true }298 append("user", [.object(block)])299 }300 }301 return turns.map { ["role": .string($0.role), "content": .array($0.content)] }302 }303304 static func adjust(_ failure: ProviderHTTP.Failure, _ body: inout [String: JSONValue]) -> Bool {305 let rejection = (failure.body.message ?? "").lowercased()306 if failure.status == 400, replaysThinking(body), rejection.contains("signature") || rejection.contains("redacted_thinking") || rejection.contains("thinking` block") || rejection.contains("thinking block") {307 stripThinkingBlocks(&body) // the documented recovery: answer this turn without the replayed reasoning308 return true309 }310 if failure.status == 400, body["thinking"]?["block_binding"] != nil, rejection.contains("block_binding") {311 removeBlockBinding(&body) // a model or platform that does not take the control312 return true313 }314 var candidates: [UnsupportedParameter.Candidate] = []315 if body["thinking"] != nil { candidates.append(.init("thinking", ["budget_tokens", "display"])) }316 if body["output_config"] != nil { candidates.append(.init("output_config", ["effort", "effort parameter"])) }317 if body["tools"]?[0]?["eager_input_streaming"] != nil { candidates.append(.init("eager_input_streaming")) }318 guard failure.status == 400, let hit = candidates.first(where: { c in319 let message = (failure.body.message ?? "").lowercased()320 return ([c.key] + c.aliases).contains { message.contains($0.lowercased()) }321 })?.key else { return false }322 switch hit {323 case "eager_input_streaming":324 guard case .array(let tools)? = body["tools"] else { return false }325 body["tools"] = .array(tools.map { tool in326 guard case .object(var o) = tool else { return tool }327 o.removeValue(forKey: "eager_input_streaming")328 return .object(o)329 })330 case "thinking":331 body.removeValue(forKey: "thinking")332 default:333 body.removeValue(forKey: "output_config")334 }335 return true336 }337338 // MARK: Stream339340 public func stream(_ request: GenerationRequest) -> AsyncThrowingStream<StreamEvent, Error> {341 let http = http, apiKey = apiKey, url = baseURL.appendingPathComponent("messages")342 let secretBox = SecretBox()343 return makeEventStream(secrets: { secretBox.values }) { continuation in344 let key = try resolveKey(apiKey, kind: .anthropic, required: true) ?? ""345 secretBox.add(key)346 let modelID = request.model.modelID347 var headers = Self.headers(key)348 headers["Accept"] = "text/event-stream"349 let (_, lines) = try await http.openAdjusting(body: Self.body(request), modelID: modelID, secrets: [key], makeRequest: { body in350 var headers = headers351 if body["thinking"]?["block_binding"] != nil { headers["anthropic-beta"] = Self.bindingControlsBeta }352 return ProviderHTTP.request(url, method: "POST", headers: headers, body: body)353 }, adjust: Self.adjust)354 var parser = SSEParser()355 var decoder = AnthropicStreamDecoder(modelID: modelID)356 for try await line in lines {357 guard let event = parser.feed(line) else { continue }358 for out in try decoder.consume(event) { continuation.yield(out) }359 if decoder.finished { return }360 }361 if let event = parser.finish() { for out in try decoder.consume(event) { continuation.yield(out) } }362 try Task.checkCancellation()363 if !decoder.finished { throw AstraError.network("The connection closed before the answer was complete.") }364 }365 }366}367368/// Turns Messages API stream events into `StreamEvent`s. One instance per response.369struct AnthropicStreamDecoder {370 private enum Block { case text, thinking(text: String, signature: String), tool(id: String, name: String, json: String), other }371372 let modelID: String373 private(set) var started = false374 private(set) var finished = false375 private var blocks: [Int: Block] = [:]376 private var stopReason: StopReason?377 private var usage = TokenUsage()378 private var thinkingBlocks = 0379 /// Thinking blocks completed since the last tool call, verbatim: they go back with the tool call that follows them.380 private var pendingThinking: [JSONValue] = []381382 private mutating func completedCall(id: String, name: String, buffer: String) -> StreamEvent {383 let state = ProviderState.make(AnthropicProvider.thinkingStateFormat, .array(pendingThinking))384 pendingThinking.removeAll()385 return .toolCallCompleted(ToolCall(id: id, name: name, arguments: ToolArguments.parse(buffer), providerState: state))386 }387388 init(modelID: String) { self.modelID = modelID }389390 mutating func consume(_ event: SSEEvent) throws -> [StreamEvent] {391 guard let json = JSONValue.parse(event.data) else { throw AstraError.decoding("a stream event was not valid JSON") }392 let type = json["type"]?.stringValue ?? event.event ?? ""393 var out: [StreamEvent] = []394 switch type {395 case "message_start":396 let message = json["message"]397 if !started {398 started = true399 out.append(.messageStarted(MessageStart(responseID: message?["id"]?.stringValue, reportedModel: message?["model"]?.stringValue)))400 }401 if let u = Self.usage(message?["usage"]) { usage = usage.merged(with: u); out.append(.usage(usage)) }402403 case "content_block_start":404 guard let index = json["index"]?.intValue else { break }405 let block = json["content_block"]406 switch block?["type"]?.stringValue {407 case "text":408 blocks[index] = .text409 if let text = block?["text"]?.stringValue, !text.isEmpty { out.append(.textDelta(text)) }410 case "thinking":411 blocks[index] = .thinking(text: block?["thinking"]?.stringValue ?? "", signature: block?["signature"]?.stringValue ?? "")412 thinkingBlocks += 1413 if thinkingBlocks > 1 { out.append(.reasoningSummaryDelta("\n\n")) }414 if let text = block?["thinking"]?.stringValue, !text.isEmpty { out.append(.reasoningSummaryDelta(text)) }415 case "tool_use":416 let id = block?["id"]?.stringValue ?? "toolu_\(index)", name = block?["name"]?.stringValue ?? ""417 // Without eager streaming a non-empty `input` can arrive whole in the start event.418 var initial = ""419 if let input = block?["input"], case .object(let o) = input, !o.isEmpty { initial = input.serialized() }420 blocks[index] = .tool(id: id, name: name, json: initial)421 out.append(.toolCallStarted(id: id, name: name))422 if !initial.isEmpty { out.append(.toolCallDelta(id: id, argumentsFragment: initial)) }423 case "redacted_thinking":424 blocks[index] = .other // nothing to show; the opaque block is kept for replay425 if let block, block["data"]?.stringValue?.isEmpty == false { pendingThinking.append(block) }426 default:427 blocks[index] = .other // server tool blocks, fallback markers: nothing to show428 }429430 case "content_block_delta":431 guard let index = json["index"]?.intValue, let delta = json["delta"] else { break }432 switch delta["type"]?.stringValue {433 case "text_delta":434 if let text = delta["text"]?.stringValue, !text.isEmpty { out.append(.textDelta(text)) }435 case "thinking_delta":436 if let text = delta["thinking"]?.stringValue, !text.isEmpty {437 out.append(.reasoningSummaryDelta(text))438 if case .thinking(let soFar, let signature)? = blocks[index] { blocks[index] = .thinking(text: soFar + text, signature: signature) }439 }440 case "signature_delta":441 // Integrity data: never shown, kept so the block can be sent back unchanged.442 if case .thinking(let text, let soFar)? = blocks[index], let part = delta["signature"]?.stringValue {443 blocks[index] = .thinking(text: text, signature: soFar + part)444 }445 case "input_json_delta":446 guard case .tool(let id, let name, var buffer)? = blocks[index], let fragment = delta["partial_json"]?.stringValue else { break }447 // A start event that carried a whole input is replaced by the streamed one.448 if buffer.hasPrefix("{"), buffer.hasSuffix("}"), !fragment.isEmpty, JSONValue.parse(buffer) != nil, fragment.hasPrefix("{") { buffer = "" }449 buffer += fragment450 blocks[index] = .tool(id: id, name: name, json: buffer)451 if !fragment.isEmpty { out.append(.toolCallDelta(id: id, argumentsFragment: fragment)) }452 default:453 break // citations_delta: not content454 }455456 case "content_block_stop":457 guard let index = json["index"]?.intValue else { break }458 if case .tool(let id, let name, let buffer)? = blocks[index] {459 out.append(completedCall(id: id, name: name, buffer: buffer))460 } else if case .thinking(let text, let signature)? = blocks[index], !signature.isEmpty {461 pendingThinking.append(["type": "thinking", "thinking": .string(text), "signature": .string(signature)])462 }463 blocks[index] = nil464465 case "message_delta":466 if let reason = json["delta"]?["stop_reason"]?.stringValue { stopReason = Self.stopReason(reason) }467 if let u = Self.usage(json["usage"]) { usage = usage.merged(with: u); out.append(.usage(usage)) }468469 case "message_stop":470 // A tool call cut off by max_tokens never got its block stop: close it so the stream stays well formed.471 for (_, block) in blocks.sorted(by: { $0.key < $1.key }) {472 if case .tool(let id, let name, let buffer) = block { out.append(completedCall(id: id, name: name, buffer: buffer)) }473 }474 blocks.removeAll()475 out.append(.messageCompleted(stopReason ?? .unknown))476 finished = true477478 case "error":479 let error = json["error"]480 throw Self.streamError(type: error?["type"]?.stringValue, message: error?["message"]?.stringValue, modelID: modelID)481482 default:483 break // ping and event types added later484 }485 return out486 }487488 static func stopReason(_ raw: String) -> StopReason {489 switch raw {490 case "end_turn": .endOfTurn491 case "max_tokens", "model_context_window_exceeded": .maxTokens492 case "tool_use": .toolCalls493 case "stop_sequence": .stopSequence494 case "refusal": .contentFilter495 case "pause_turn": .endOfTurn496 default: .unknown497 }498 }499500 /// Anthropic reports `input_tokens` without the cached part. The app's `inputTokens` is the whole prompt:501 /// uncached + cache reads + cache writes, with the last two also reported on their own as subsets.502 static func usage(_ json: JSONValue?) -> TokenUsage? {503 guard let json, json.objectValue != nil else { return nil }504 let read = json["cache_read_input_tokens"]?.intValue505 let write = json["cache_creation_input_tokens"]?.intValue506 var total: Int?507 if let base = json["input_tokens"]?.intValue { total = TokenUsage.sum(base, read, write) }508 return TokenUsage(inputTokens: total, outputTokens: json["output_tokens"]?.intValue, cachedInputTokens: total == nil ? nil : read,509 cacheWriteTokens: total == nil ? nil : write, reasoningTokens: json["output_tokens_details"]?["thinking_tokens"]?.intValue)510 }511512 static func streamError(type: String?, message: String?, modelID: String) -> AstraError {513 let status: Int514 switch type {515 case "overloaded_error": status = 529516 case "rate_limit_error": status = 429517 case "invalid_request_error": status = 400518 case "authentication_error": status = 401519 case "billing_error": status = 402520 case "permission_error": status = 403521 case "not_found_error": status = 404522 case "request_too_large": status = 413523 case "timeout_error": status = 408524 default: status = 500525 }526 return mapHTTPError(status: status, code: type, message: message, retryAfter: nil, model: modelID)527 }528}529