Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Astra9// File : Packages/AstraProviders/Sources/ResponsesAPI.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// The Responses API wire format (`POST /v1/responses`, semantic SSE events), shared by OpenAI and xAI.92//93// Conversation state is always sent in full with `store: false`: nothing is retained server-side on the user's behalf.94// Reasoning items that came with a function call and carry `encrypted_content` (returned by default when nothing is stored)95// are kept in `ToolCall.providerState` and sent back unchanged ahead of that call, as both providers document for tool96// cycles. A call without state is replayed alone, without item ids, which both providers accept (verified live on 2026-11-21).9798/// What a given model accepts, as far as it is known before sending. Unknown fields are sent and removed on a 400.99struct ResponsesModelPlan: Sendable {100 /// nil: unknown, send and fall back. false: never send `temperature` / `top_p`.101 var acceptsSampling: Bool?102 /// nil: unknown. Empty: the model does not reason, never send `reasoning`.103 var reasoningEfforts: [String]?104 /// Put the system text in a leading `developer` message instead of top-level `instructions`.105 var systemAsDeveloperMessage = false106 /// Ask for reasoning summaries even when the user set no effort (models known to reason by default).107 var requestSummaryByDefault = false108 /// Tag of the reasoning items kept in `ToolCall.providerState`; one per provider, so ciphertext never crosses providers.109 var stateFormat = "responses.reasoning"110}111112enum ResponsesEncoder {113 static func body(_ request: GenerationRequest, plan: ResponsesModelPlan) -> [String: JSONValue] {114 var body: [String: JSONValue] = ["model": .string(request.model.modelID), "stream": true, "store": false]115 var input: [JSONValue] = []116 if let system = request.system?.trimmingCharacters(in: .whitespacesAndNewlines), !system.isEmpty {117 if plan.systemAsDeveloperMessage { input.append(["role": "developer", "content": .string(system)]) } else { body["instructions"] = .string(system) }118 }119 for message in request.messages { input.append(contentsOf: items(message, stateFormat: plan.stateFormat)) }120 body["input"] = .array(input)121 if !request.tools.isEmpty {122 body["tools"] = .array(request.tools.map { tool in123 ["type": "function", "name": .string(tool.name), "description": .string(tool.summary), "parameters": tool.parameters, "strict": false]124 })125 }126 let p = request.parameters127 if let max = p.maxOutputTokens { body["max_output_tokens"] = .number(Double(max)) }128 if plan.acceptsSampling != false {129 if let t = p.temperature { body["temperature"] = .number(t) }130 if let t = p.topP { body["top_p"] = .number(t) }131 }132 if let reasoning = reasoning(p.reasoning, plan: plan) { body["reasoning"] = reasoning }133 return body134 }135136 /// Maps the app's four levels onto what the model accepts. "Off" becomes the lowest effort the model has.137 static func reasoning(_ effort: ReasoningEffort?, plan: ResponsesModelPlan) -> JSONValue? {138 if let known = plan.reasoningEfforts, known.isEmpty { return nil }139 guard let effort else { return plan.requestSummaryByDefault ? ["summary": "auto"] : nil }140 let wanted: String141 switch effort {142 case .off: wanted = "none"143 case .low: wanted = "low"144 case .medium: wanted = "medium"145 case .high: wanted = "high"146 }147 var value = wanted148 if let known = plan.reasoningEfforts, !known.contains(wanted) {149 value = effort == .off ? (["none", "minimal", "low"].first(where: known.contains) ?? known.first ?? "low") : (known.contains("medium") ? "medium" : known.first ?? wanted)150 }151 return value == "none" ? ["effort": "none"] : ["effort": .string(value), "summary": "auto"]152 }153154 static func isReasoningItem(_ item: JSONValue) -> Bool { item["type"] == "reasoning" }155156 static func items(_ message: PromptMessage, stateFormat: String = "responses.reasoning") -> [JSONValue] {157 switch message.role {158 case .user:159 var parts: [JSONValue] = message.images.map { ["type": "input_image", "image_url": .string(dataURL($0)), "detail": "auto"] }160 if !message.text.isEmpty || parts.isEmpty { parts.append(["type": "input_text", "text": .string(message.text)]) }161 return [["role": "user", "content": .array(parts)]]162 case .assistant:163 // Output order of the turn: reasoning, message, function call (more reasoning may precede a later call).164 func reasoning(_ call: ToolCall) -> [JSONValue] { (ProviderState.payload(call, format: stateFormat)?.arrayValue ?? []).filter(isReasoningItem) }165 var out: [JSONValue] = message.toolCalls.first.map(reasoning) ?? []166 if !message.text.isEmpty { out.append(["role": "assistant", "content": .string(message.text)]) }167 for (index, call) in message.toolCalls.enumerated() {168 if index > 0 { out += reasoning(call) }169 out.append(["type": "function_call", "call_id": .string(call.id), "name": .string(call.name), "arguments": .string(ToolArguments.wireText(call.arguments))])170 }171 return out172 case .tool:173 let text = message.toolIsError ? "Error: " + message.text : message.text174 return [["type": "function_call_output", "call_id": .string(message.toolCallID ?? ""), "output": .string(text)]]175 }176 }177178 /// Edits the body after a parameter rejection. Returns false when the failure is not one this layer can route around.179 static func adjust(_ failure: ProviderHTTP.Failure, _ body: inout [String: JSONValue]) -> Bool {180 // Replayed reasoning the provider cannot use (another model, another organisation, an expired item): send the calls alone.181 if failure.status == 400 || failure.status == 404, case .array(let input)? = body["input"], input.contains(where: isReasoningItem) {182 let message = (failure.body.message ?? "").lowercased()183 if message.contains("encrypted") || message.contains("reasoning item") || message.contains("rs_") || (message.contains("reasoning") && message.contains("item")) {184 body["input"] = .array(input.filter { !isReasoningItem($0) })185 return true186 }187 }188 var candidates: [UnsupportedParameter.Candidate] = []189 if body["temperature"] != nil { candidates.append(.init("temperature")) }190 if body["top_p"] != nil { candidates.append(.init("top_p", ["topP"])) }191 if body["reasoning"] != nil { candidates.append(.init("reasoning", ["reasoning_effort", "reasoningEffort", "reasoning.effort", "reasoning.summary", "summary"])) }192 if body["instructions"] != nil { candidates.append(.init("instructions")) }193 guard let hit = UnsupportedParameter.detect(failure, candidates: candidates) else { return false }194 switch hit {195 case "reasoning":196 // A model that reasons but has no "none" level: ask for its lowest real level instead of giving up on the setting.197 let message = (failure.body.message ?? "").lowercased()198 if body["reasoning"]?["effort"]?.stringValue == "none", message.contains("none") {199 body["reasoning"] = ["effort": "low", "summary": "auto"]200 } else if body["reasoning"]?["summary"] != nil, message.contains("summary"), let effort = body["reasoning"]?["effort"] {201 body["reasoning"] = ["effort": effort]202 } else {203 body.removeValue(forKey: "reasoning")204 }205 case "instructions":206 guard let text = body["instructions"], case .array(let input)? = body["input"] else { return false }207 body.removeValue(forKey: "instructions")208 body["input"] = .array([["role": "system", "content": text]] + input)209 default: body.removeValue(forKey: hit)210 }211 return true212 }213}214215/// Turns Responses API stream events into `StreamEvent`s. One instance per response.216struct ResponsesStreamDecoder {217 private struct Call { var id: String; var name: String; var arguments = ""; var completed = false }218219 let modelID: String220 /// Divisor that turns the provider's reported cost into US dollars (xAI reports `cost_in_usd_ticks`, 1e10 ticks per dollar).221 var costTicksPerUSD: Double?222 private(set) var started = false223 private(set) var finished = false224 private var calls: [String: Call] = [:] // by item id225 private var callOrder: [String] = []226 private var sawRefusal = false227 private var emittedCalls = false228 let stateFormat: String229 /// Reasoning items completed since the last function call, reduced to what a replay needs.230 private var pendingReasoning: [JSONValue] = []231232 init(modelID: String, costTicksPerUSD: Double? = nil, stateFormat: String = "responses.reasoning") {233 self.modelID = modelID; self.costTicksPerUSD = costTicksPerUSD; self.stateFormat = stateFormat234 }235236 mutating func consume(_ event: SSEEvent) throws -> [StreamEvent] {237 let data = event.data.trimmingCharacters(in: .whitespaces)238 if data == "[DONE]" || data.isEmpty { return [] }239 guard let json = JSONValue.parse(data) else { throw AstraError.decoding("a stream event was not valid JSON") }240 let type = json["type"]?.stringValue ?? event.event ?? ""241 var out: [StreamEvent] = []242243 func start(_ response: JSONValue?) -> [StreamEvent] {244 guard !started else { return [] }245 return [.messageStarted(MessageStart(responseID: response?["id"]?.stringValue, reportedModel: response?["model"]?.stringValue))]246 }247248 switch type {249 case "response.created", "response.in_progress", "response.queued":250 out += start(json["response"]); started = true251252 case "response.output_text.delta":253 out += start(nil); started = true254 if let delta = json["delta"]?.stringValue, !delta.isEmpty { out.append(.textDelta(delta)) }255256 case "response.refusal.delta":257 out += start(nil); started = true258 sawRefusal = true259 if let delta = json["delta"]?.stringValue, !delta.isEmpty { out.append(.textDelta(delta)) }260261 case "response.reasoning_summary_part.added":262 // Separate consecutive summary parts; the summary is the only reasoning text ever surfaced.263 if let index = json["summary_index"]?.intValue, index > 0 { out.append(.reasoningSummaryDelta("\n\n")) }264265 case "response.reasoning_summary_text.delta":266 out += start(nil); started = true267 if let delta = json["delta"]?.stringValue, !delta.isEmpty { out.append(.reasoningSummaryDelta(delta)) }268269 case "response.output_item.added":270 out += start(nil); started = true271 if let item = json["item"], item["type"]?.stringValue == "function_call" { out += open(item) }272273 case "response.function_call_arguments.delta":274 guard let itemID = json["item_id"]?.stringValue, let delta = json["delta"]?.stringValue, var call = calls[itemID], !call.completed else { break }275 call.arguments += delta276 calls[itemID] = call277 if !delta.isEmpty { out.append(.toolCallDelta(id: call.id, argumentsFragment: delta)) }278279 case "response.output_item.done":280 if let item = json["item"], item["type"]?.stringValue == "function_call" {281 out += open(item)282 out += complete(itemID: item["id"]?.stringValue ?? item["call_id"]?.stringValue ?? "", finalArguments: item["arguments"]?.stringValue)283 } else if let item = json["item"], item["type"]?.stringValue == "reasoning", let encrypted = item["encrypted_content"]?.stringValue, !encrypted.isEmpty {284 // Without stored responses the ciphertext is the only form in which this reasoning can be sent back.285 var kept: [String: JSONValue] = ["type": "reasoning", "summary": item["summary"] ?? .array([]), "encrypted_content": .string(encrypted)]286 if let id = item["id"] { kept["id"] = id }287 pendingReasoning.append(.object(kept))288 }289290 case "response.completed", "response.incomplete":291 out += start(json["response"]); started = true292 out += completeAll()293 if let usage = usage(json["response"]?["usage"]) { out.append(.usage(usage)) }294 let reason: StopReason295 if type == "response.incomplete" {296 switch json["response"]?["incomplete_details"]?["reason"]?.stringValue {297 case "max_output_tokens": reason = .maxTokens298 case "content_filter": reason = .contentFilter299 default: reason = .unknown300 }301 } else {302 reason = emittedCalls ? .toolCalls : sawRefusal ? .contentFilter : .endOfTurn303 }304 out.append(.messageCompleted(reason))305 finished = true306307 case "response.failed":308 let error = json["response"]?["error"]309 throw Self.streamError(code: error?["code"]?.stringValue, message: error?["message"]?.stringValue, modelID: modelID)310311 case "error":312 let error = json["error"] ?? json313 throw Self.streamError(code: error["code"]?.stringValue ?? error["type"]?.stringValue, message: error["message"]?.stringValue ?? error.stringValue, modelID: modelID)314315 default:316 break // content parts, *.done echoes, hosted-tool progress, raw reasoning text: nothing to surface317 }318 return out319 }320321 private mutating func open(_ item: JSONValue) -> [StreamEvent] {322 let itemID = item["id"]?.stringValue ?? item["call_id"]?.stringValue ?? ""323 guard calls[itemID] == nil, let name = item["name"]?.stringValue else { return [] }324 let callID = item["call_id"]?.stringValue ?? itemID325 calls[itemID] = Call(id: callID, name: name)326 callOrder.append(itemID)327 emittedCalls = true328 return [.toolCallStarted(id: callID, name: name)]329 }330331 private mutating func complete(itemID: String, finalArguments: String?) -> [StreamEvent] {332 guard var call = calls[itemID], !call.completed else { return [] }333 var out: [StreamEvent] = []334 if let final = finalArguments, !final.isEmpty, final != call.arguments {335 // The provider sent the arguments whole (or the deltas were lost): surface the part not yet seen.336 if final.hasPrefix(call.arguments) {337 let rest = String(final.dropFirst(call.arguments.count))338 if !rest.isEmpty { out.append(.toolCallDelta(id: call.id, argumentsFragment: rest)) }339 }340 call.arguments = final341 }342 call.completed = true343 calls[itemID] = call344 let state = ProviderState.make(stateFormat, .array(pendingReasoning))345 pendingReasoning.removeAll()346 out.append(.toolCallCompleted(ToolCall(id: call.id, name: call.name, arguments: ToolArguments.parse(call.arguments), providerState: state)))347 return out348 }349350 private mutating func completeAll() -> [StreamEvent] {351 var out: [StreamEvent] = []352 for itemID in callOrder { out += complete(itemID: itemID, finalArguments: nil) }353 return out354 }355356 /// `input_tokens` already counts cached tokens; `cached_tokens` and `cache_write_tokens` are subsets of it.357 func usage(_ json: JSONValue?) -> TokenUsage? {358 guard let json, json.objectValue != nil else { return nil }359 var cost: Double?360 if let divisor = costTicksPerUSD, let ticks = json["cost_in_usd_ticks"]?.doubleValue { cost = ticks / divisor }361 return TokenUsage(inputTokens: json["input_tokens"]?.intValue, outputTokens: json["output_tokens"]?.intValue,362 cachedInputTokens: json["input_tokens_details"]?["cached_tokens"]?.intValue,363 cacheWriteTokens: json["input_tokens_details"]?["cache_write_tokens"]?.intValue,364 reasoningTokens: json["output_tokens_details"]?["reasoning_tokens"]?.intValue, reportedCostUSD: cost)365 }366367 /// Errors that arrive inside a 200 stream carry a code, not a status: map the documented codes onto the HTTP classes.368 static func streamError(code: String?, message: String?, modelID: String) -> AstraError {369 let c = (code ?? "").lowercased()370 let status: Int371 // The specific codes first: "invalid_api_key" and "model_not_found" must not be swallowed by the generic "invalid".372 if c.contains("authentication") || c.contains("api_key") { return mapHTTPError(status: 401, code: code, message: message, retryAfter: nil, model: modelID) }373 if c.contains("model_not_found") { return mapHTTPError(status: 404, code: code, message: message, retryAfter: nil, model: modelID) }374 if c.contains("rate_limit") || c.contains("slow_down") || c.contains("insufficient_quota") || c.contains("credit") || c.contains("spend_limit") || c.contains("usage_limit") {375 status = 429376 } else if c.contains("context_length") || c.contains("invalid") || c.contains("unsupported") || c.contains("content_policy") || c.contains("string_above_max_length") {377 status = 400378 } else if c.contains("overloaded") || c.contains("unavailable") {379 status = 503380 } else if c.contains("model_not_found") {381 status = 404382 } else if c.contains("authentication") || c.contains("api_key") {383 status = 401384 } else {385 status = 500386 }387 return mapHTTPError(status: status, code: code, message: message, retryAfter: nil, model: modelID)388 }389}390391/// Drives one Responses API generation: request (with parameter fallback), SSE decoding, terminal-event guarantee.392func runResponsesStream(http: ProviderHTTP, request: GenerationRequest, plan: ResponsesModelPlan, secrets: [String], costTicksPerUSD: Double? = nil,393 normalize: (ProviderHTTP.Failure) -> ProviderHTTP.Failure = { $0 },394 makeRequest: (JSONValue) throws -> URLRequest, continuation: EventContinuation) async throws {395 let body = ResponsesEncoder.body(request, plan: plan)396 let (_, lines) = try await http.openAdjusting(body: body, modelID: request.model.modelID, secrets: secrets, makeRequest: makeRequest,397 normalize: normalize, adjust: ResponsesEncoder.adjust)398 var parser = SSEParser()399 var decoder = ResponsesStreamDecoder(modelID: request.model.modelID, costTicksPerUSD: costTicksPerUSD, stateFormat: plan.stateFormat)400 for try await line in lines {401 guard let event = parser.feed(line) else { continue }402 for out in try decoder.consume(event) { continuation.yield(out) }403 if decoder.finished { return }404 }405 if let event = parser.finish() { for out in try decoder.consume(event) { continuation.yield(out) } }406 try Task.checkCancellation()407 if !decoder.finished { throw AstraError.network("The connection closed before the answer was complete.") }408}409