Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Astra9// File : Packages/AstraProviders/Sources/GeminiProvider.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/// Google Gemini through the native API (`POST /v1beta/models/{model}:streamGenerateContent?alt=sse`).92///93/// - The key travels in the `x-goog-api-key` header and is never part of a URL.94/// - Gemini 3 and later return a `thoughtSignature` on the first `functionCall` part of a turn and reject (HTTP 400) a95/// tool cycle that does not send it back. Signatures are kept in memory, keyed by tool-call id, and echoed verbatim.96/// When a signature is not available (the app was restarted mid-cycle, or the history comes from another model) the97/// documented placeholder `skip_thought_signature_validator` is sent instead; both paths were verified live on 2026-11-21.98/// - Gemini 2.5 and earlier return no call ids: ids are synthesised from the response id and the call's position.99/// - Thought summaries (`thought: true` parts) are surfaced as `.reasoningSummaryDelta` only when the API returns them.100public struct GeminiProvider: ChatProvider {101 public let kind: ProviderKind = .google102 public static let defaultBaseURL = URL(string: "https://generativelanguage.googleapis.com/v1beta")!103 static let signaturePlaceholder = "skip_thought_signature_validator"104 static let synthesizedIDPrefix = "gemini-call-"105 static let thoughtSignatureFormat = "gemini.thoughtSignature"106107 private let http: ProviderHTTP108 private let apiKey: KeyProvider109 private let baseURL: URL110111 public init(transport: any HTTPTransport, apiKey: @escaping KeyProvider, diagnostics: (any DiagnosticsSink)? = nil, baseURL: URL = GeminiProvider.defaultBaseURL) {112 self.http = ProviderHTTP(kind: .google, transport: transport, diagnostics: diagnostics)113 self.apiKey = apiKey114 self.baseURL = baseURL115 }116117 static func headers(_ key: String) -> [String: String] { ["x-goog-api-key": key] }118119 /// Google answers an invalid key with HTTP 400 and reason `API_KEY_INVALID`.120 static func normalize(_ failure: ProviderHTTP.Failure) -> ProviderHTTP.Failure {121 var f = failure122 let code = f.body.code ?? "", message = (f.body.message ?? "").lowercased()123 if f.status == 400, code.contains("API_KEY_INVALID") || message.contains("api key not valid") || message.contains("api key expired") { f.status = 401 }124 // A 429 that says when to retry is a rate limit, whatever its wording says about plans and billing.125 if f.status == 429, f.retryAfter != nil, message.contains("billing") || message.contains("credit") { f.body.message = nil; f.body.code = "RESOURCE_EXHAUSTED" }126 return f127 }128129 // MARK: Models130131 public func listModels() async throws -> [ModelInfo] {132 let key = try resolveKey(apiKey, kind: kind, required: true) ?? ""133 var out: [ModelInfo] = []134 var pageToken: String?135 let fetchedAt = Date()136 for _ in 0..<20 {137 var components = URLComponents(url: baseURL.appendingPathComponent("models"), resolvingAgainstBaseURL: false)!138 components.queryItems = [URLQueryItem(name: "pageSize", value: "1000")] + (pageToken.map { [URLQueryItem(name: "pageToken", value: $0)] } ?? [])139 let (json, _) = try await http.json(ProviderHTTP.request(components.url!, headers: Self.headers(key)), secrets: [key], normalize: Self.normalize)140 guard let models = json["models"]?.arrayValue else { throw AstraError.decoding("the model list has no models array") }141 out += models.compactMap { Self.modelInfo($0, fetchedAt: fetchedAt) }142 guard let next = json["nextPageToken"]?.stringValue, !next.isEmpty else { break }143 pageToken = next144 }145 return out146 }147148 static func modelInfo(_ entry: JSONValue, fetchedAt: Date) -> ModelInfo? {149 guard let name = entry["name"]?.stringValue else { return nil }150 let id = name.hasPrefix("models/") ? String(name.dropFirst("models/".count)) : name151 let methods = entry["supportedGenerationMethods"]?.arrayValue?.compactMap(\.stringValue) ?? []152 guard methods.contains("generateContent"), isTextModel(id) else { return nil }153 let ref = ModelRef(provider: .google, modelID: id)154 var capabilities: Set<Capability> = [.text]155 if entry["thinking"]?.boolValue == true { capabilities.insert(.reasoning) }156 var pricing: Pricing?157 if let curated = CuratedCatalog.gemini(id) {158 capabilities.formUnion(curated.capabilities)159 pricing = CuratedCatalog.pricing(curated)160 }161 // Limits and the thinking flag come from the API; prices and the remaining capabilities, where present, from the curated table.162 return ModelInfo(ref: ref, displayName: entry["displayName"]?.stringValue ?? id, summary: entry["description"]?.stringValue.map { String($0.prefix(400)) },163 contextLength: entry["inputTokenLimit"]?.intValue, maxOutputTokens: entry["outputTokenLimit"]?.intValue, capabilities: capabilities,164 source: .providerAPI(fetchedAt: fetchedAt), pricing: pricing, supportedParameters: Set(methods), vendor: "google")165 }166167 /// `generateContent` is also offered by speech, image, music, video and agent models, which do not answer a chat turn with text.168 static func isTextModel(_ id: String) -> Bool {169 let lower = id.lowercased()170 let excluded = ["tts", "image", "banana", "lyria", "veo", "omni", "live", "transcribe", "embedding", "aqa", "computer-use", "deep-research", "antigravity", "robotics", "genie"]171 return !excluded.contains(where: { lower.contains($0) })172 }173174 public func verify() async throws -> ConnectionStatus {175 let models = try await listModels()176 return ConnectionStatus(ok: true, detail: "Key accepted. \(models.count) text models available.", modelCount: models.count)177 }178179 // MARK: Request180181 static func body(_ request: GenerationRequest, signatures: ThoughtSignatureStore = .shared) -> [String: JSONValue] {182 var body: [String: JSONValue] = ["contents": .array(contents(request.messages, signatures: signatures))]183 if let system = request.system?.trimmingCharacters(in: .whitespacesAndNewlines), !system.isEmpty {184 body["systemInstruction"] = ["parts": [["text": .string(system)]]]185 }186 if !request.tools.isEmpty {187 // `parametersJsonSchema` takes a full JSON Schema; the older `parameters` field rejects keywords such as additionalProperties.188 body["tools"] = [["functionDeclarations": .array(request.tools.map { tool in189 ["name": .string(tool.name), "description": .string(tool.summary), "parametersJsonSchema": tool.parameters]190 })]]191 }192 var config: [String: JSONValue] = [:]193 let p = request.parameters194 if let v = p.maxOutputTokens { config["maxOutputTokens"] = .number(Double(v)) }195 if let v = p.temperature { config["temperature"] = .number(v) }196 if let v = p.topP { config["topP"] = .number(v) }197 if let v = p.seed { config["seed"] = .number(Double(v)) }198 if !p.stop.isEmpty { config["stopSequences"] = .array(p.stop.prefix(5).map(JSONValue.string)) }199 if let thinking = thinkingConfig(p.reasoning, modelID: request.model.modelID) { config["thinkingConfig"] = thinking }200 if !config.isEmpty { body["generationConfig"] = .object(config) }201 return body202 }203204 /// Gemini 2.5 takes a token budget; Gemini 3 and later take a level. Anything the model refuses is removed on a 400.205 static func thinkingConfig(_ effort: ReasoningEffort?, modelID: String) -> JSONValue? {206 let id = modelID.lowercased()207 guard id.hasPrefix("gemini-") || id.hasPrefix("gemma-") else { return nil }208 guard let effort else { return ["includeThoughts": true] }209 if id.contains("gemini-2.5") || id.contains("gemini-2.0") {210 switch effort {211 case .off: return ["thinkingBudget": id.contains("pro") ? 128 : 0] // 2.5 Pro cannot turn thinking off212 case .low: return ["thinkingBudget": 1024, "includeThoughts": true]213 case .medium: return ["thinkingBudget": 8192, "includeThoughts": true]214 case .high: return ["thinkingBudget": 24576, "includeThoughts": true]215 }216 }217 switch effort {218 case .off: return ["thinkingLevel": "minimal"]219 case .low: return ["thinkingLevel": "low", "includeThoughts": true]220 case .medium: return ["thinkingLevel": "medium", "includeThoughts": true]221 case .high: return ["thinkingLevel": "high", "includeThoughts": true]222 }223 }224225 /// Roles are `user` and `model` and must alternate: consecutive turns of the same role are merged, so the results of226 /// parallel calls travel in one user turn, in call order.227 static func contents(_ messages: [PromptMessage], signatures: ThoughtSignatureStore) -> [JSONValue] {228 var turns: [(role: String, parts: [JSONValue])] = []229 func append(_ role: String, _ parts: [JSONValue]) {230 guard !parts.isEmpty else { return }231 if let last = turns.last, last.role == role { turns[turns.count - 1].parts += parts } else { turns.append((role, parts)) }232 }233 for message in messages {234 switch message.role {235 case .user:236 var parts: [JSONValue] = message.images.map { ["inlineData": ["mimeType": .string($0.mimeType), "data": .string($0.data.base64EncodedString())]] }237 if !message.text.isEmpty { parts.append(["text": .string(message.text)]) }238 append("user", parts)239 case .assistant:240 var parts: [JSONValue] = []241 if !message.text.isEmpty { parts.append(["text": .string(message.text)]) }242 for (position, call) in message.toolCalls.enumerated() {243 var functionCall: [String: JSONValue] = ["name": .string(call.name), "args": ToolArguments.wireObject(call.arguments)]244 if !call.id.hasPrefix(synthesizedIDPrefix) { functionCall["id"] = .string(call.id) }245 var part: [String: JSONValue] = ["functionCall": .object(functionCall)]246 // The signature the call came with: from the call's own state (survives a restart), else from this247 // process's memory (a call stored before state existed), else the documented placeholder on the first call.248 if let signature = ProviderState.payload(call, format: thoughtSignatureFormat)?.stringValue ?? signatures.signature(for: call.id) {249 part["thoughtSignature"] = .string(signature)250 } else if position == 0 {251 part["thoughtSignature"] = .string(signaturePlaceholder)252 }253 parts.append(.object(part))254 }255 append("model", parts)256 case .tool:257 var response: [String: JSONValue] = ["name": .string(message.toolName ?? ""), "response": [message.toolIsError ? "error" : "result": .string(message.text)]]258 if let id = message.toolCallID, !id.isEmpty, !id.hasPrefix(synthesizedIDPrefix) { response["id"] = .string(id) }259 append("user", [["functionResponse": .object(response)]])260 }261 }262 return turns.map { ["role": .string($0.role), "parts": .array($0.parts)] }263 }264265 static func adjust(_ failure: ProviderHTTP.Failure, _ body: inout [String: JSONValue]) -> Bool {266 guard failure.status == 400, case .object(var config)? = body["generationConfig"] else { return false }267 let message = (failure.body.message ?? "").lowercased()268 func store() { if config.isEmpty { body.removeValue(forKey: "generationConfig") } else { body["generationConfig"] = .object(config) } }269 if config["thinkingConfig"] != nil, message.contains("thinking") || message.contains("thought") {270 if config["thinkingConfig"]?["thinkingLevel"]?.stringValue == "minimal", message.contains("minimal") {271 config["thinkingConfig"] = ["thinkingLevel": "low"] // the model has no near-off level272 } else {273 config.removeValue(forKey: "thinkingConfig")274 }275 store()276 return true277 }278 for (key, names) in [("seed", ["seed"]), ("topP", ["top_p", "topp"]), ("temperature", ["temperature"]), ("stopSequences", ["stop_sequences", "stopsequences"])] {279 if config[key] != nil, names.contains(where: message.contains), message.contains("not supported") || message.contains("unknown name") || message.contains("invalid") {280 config.removeValue(forKey: key)281 store()282 return true283 }284 }285 return false286 }287288 // MARK: Stream289290 public func stream(_ request: GenerationRequest) -> AsyncThrowingStream<StreamEvent, Error> {291 let http = http, apiKey = apiKey, baseURL = baseURL292 let secretBox = SecretBox()293 return makeEventStream(secrets: { secretBox.values }) { continuation in294 let key = try resolveKey(apiKey, kind: .google, required: true) ?? ""295 secretBox.add(key)296 let modelID = request.model.modelID297 guard modelID.range(of: #"^[A-Za-z0-9._\-]+$"#, options: .regularExpression) != nil,298 let url = URL(string: baseURL.absoluteString + "/models/\(modelID):streamGenerateContent?alt=sse") else {299 throw AstraError.modelNotFound(modelID)300 }301 var headers = Self.headers(key)302 headers["Accept"] = "text/event-stream"303 let (_, lines) = try await http.openAdjusting(body: Self.body(request), modelID: modelID, secrets: [key], makeRequest: { body in304 ProviderHTTP.request(url, method: "POST", headers: headers, body: body)305 }, normalize: Self.normalize, adjust: Self.adjust)306 var parser = SSEParser()307 var decoder = GeminiStreamDecoder(modelID: modelID)308 for try await line in lines {309 guard let event = parser.feed(line) else { continue }310 for out in try decoder.consume(event.data) { continuation.yield(out) }311 if decoder.finished { return }312 }313 if let event = parser.finish() { for out in try decoder.consume(event.data) { continuation.yield(out) } }314 try Task.checkCancellation()315 if !decoder.finished { throw AstraError.network("The connection closed before the answer was complete.") }316 }317 }318}319320/// Thought signatures of recent function calls, by tool-call id, in memory. The durable copy is `ToolCall.providerState`;321/// this store is only the fallback for a call that reaches the encoder without its state.322final class ThoughtSignatureStore: @unchecked Sendable {323 static let shared = ThoughtSignatureStore()324 private let lock = NSLock()325 private var values: [String: String] = [:]326 private var order: [String] = []327 private let capacity: Int328329 init(capacity: Int = 512) { self.capacity = capacity }330331 func signature(for callID: String) -> String? { lock.withLock { values[callID] } }332333 func store(_ signature: String, for callID: String) {334 lock.withLock {335 if values[callID] == nil { order.append(callID) }336 values[callID] = signature337 while order.count > capacity { values.removeValue(forKey: order.removeFirst()) }338 }339 }340}341342/// Turns `GenerateContentResponse` chunks into `StreamEvent`s. One instance per response.343struct GeminiStreamDecoder {344 let modelID: String345 let signatures: ThoughtSignatureStore346 private(set) var started = false347 private(set) var finished = false348 private var responseID: String?349 private var callCount = 0350 private var usage: TokenUsage?351352 init(modelID: String, signatures: ThoughtSignatureStore = .shared) { self.modelID = modelID; self.signatures = signatures }353354 mutating func consume(_ data: String) throws -> [StreamEvent] {355 let trimmed = data.trimmingCharacters(in: .whitespaces)356 if trimmed.isEmpty || trimmed == "[DONE]" || finished { return [] }357 guard let json = JSONValue.parse(trimmed) else { throw AstraError.decoding("a stream chunk was not valid JSON") }358 if let error = json["error"], !error.isNull {359 let body = ProviderErrorBody.parse(json)360 let failure = GeminiProvider.normalize(ProviderHTTP.Failure(status: error["code"]?.intValue ?? 500, body: body, retryAfter: body.retryDelay))361 throw mapHTTPError(status: failure.status, code: failure.body.code, message: failure.body.message, retryAfter: failure.retryAfter, model: modelID)362 }363 var out: [StreamEvent] = []364 if !started {365 started = true366 responseID = json["responseId"]?.stringValue367 out.append(.messageStarted(MessageStart(responseID: responseID, reportedModel: json["modelVersion"]?.stringValue)))368 }369 if let u = Self.usage(json["usageMetadata"]) { usage = usage?.merged(with: u) ?? u }370371 // The prompt itself was refused: there is no candidate, only the reason.372 if let block = json["promptFeedback"]?["blockReason"]?.stringValue, !block.isEmpty, (json["candidates"]?.arrayValue ?? []).isEmpty {373 return out + end(.contentFilter)374 }375 guard let candidate = json["candidates"]?[0] else { return out }376 for part in candidate["content"]?["parts"]?.arrayValue ?? [] {377 if let call = part["functionCall"] {378 let name = call["name"]?.stringValue ?? ""379 let id = call["id"]?.stringValue ?? "\(GeminiProvider.synthesizedIDPrefix)\(responseID ?? "r")-\(callCount)"380 callCount += 1381 var state: JSONValue?382 if let signature = part["thoughtSignature"]?.stringValue, !signature.isEmpty {383 signatures.store(signature, for: id)384 state = ProviderState.make(GeminiProvider.thoughtSignatureFormat, .string(signature))385 }386 let arguments = call["args"].flatMap { value -> JSONValue? in if case .object = value { return value }; return nil } ?? .object([:])387 out.append(.toolCallStarted(id: id, name: name))388 out.append(.toolCallDelta(id: id, argumentsFragment: arguments.serialized()))389 out.append(.toolCallCompleted(ToolCall(id: id, name: name, arguments: arguments, providerState: state)))390 } else if let text = part["text"]?.stringValue, !text.isEmpty {391 out.append(part["thought"]?.boolValue == true ? .reasoningSummaryDelta(text) : .textDelta(text))392 }393 }394 if let reason = candidate["finishReason"]?.stringValue, !reason.isEmpty {395 switch reason {396 case "MALFORMED_FUNCTION_CALL", "UNEXPECTED_TOOL_CALL", "TOO_MANY_TOOL_CALLS", "MISSING_THOUGHT_SIGNATURE":397 throw AstraError.protocolViolation("the model produced a tool call the provider could not use (\(reason.lowercased()))")398 default:399 out += end(Self.stopReason(reason, calledTools: callCount > 0))400 }401 }402 return out403 }404405 private mutating func end(_ reason: StopReason) -> [StreamEvent] {406 finished = true407 var out: [StreamEvent] = []408 if let usage { out.append(.usage(usage)) }409 out.append(.messageCompleted(reason))410 return out411 }412413 /// Gemini reports `STOP` for a turn that ends in function calls.414 static func stopReason(_ raw: String, calledTools: Bool) -> StopReason {415 switch raw {416 case "STOP": calledTools ? .toolCalls : .endOfTurn417 case "MAX_TOKENS": .maxTokens418 case "SAFETY", "RECITATION", "BLOCKLIST", "PROHIBITED_CONTENT", "SPII", "LANGUAGE", "IMAGE_SAFETY", "IMAGE_PROHIBITED_CONTENT", "IMAGE_RECITATION": .contentFilter419 default: .unknown420 }421 }422423 /// `promptTokenCount` is the whole prompt, cached part included. Thinking is billed as output, so it is added to the424 /// visible `candidatesTokenCount` and also reported on its own as reasoning tokens.425 static func usage(_ json: JSONValue?) -> TokenUsage? {426 guard let json, json.objectValue != nil else { return nil }427 let thoughts = json["thoughtsTokenCount"]?.intValue428 let candidates = json["candidatesTokenCount"]?.intValue429 let output = TokenUsage.sum(candidates, thoughts)430 return TokenUsage(inputTokens: json["promptTokenCount"]?.intValue, outputTokens: output, cachedInputTokens: json["cachedContentTokenCount"]?.intValue, reasoningTokens: thoughts)431 }432}433