Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Docs9// File : Packages/ORIXDocsAI/Tests/DocAITests/LiveHubSmokeTests.swift10// Description : Live check of the provider hub against the real providers.11// Skipped unless ORIXDOCS_LIVE_TESTS=1; a provider runs only12// when its key variable is set (same names as ORIX Astra's13// Scripts/smoke-env.sh). Per provider: connection test, one14// tiny streamed completion, one tool call, all through15// `ProviderHub`. Keys are read from the environment into an16// in-memory store: never printed, never written. Run with17// Scripts/ai-live-smoke.sh.18// Module : DocAITests19// Repository : https://git.spboucher.ai/orix-docs20// Created : 2026-11-2221// Last Modified : 2026-11-2222//23// =============================================================================24// AUTHOR & PROFESSIONAL AFFILIATION25// =============================================================================26//27// Author : Simon-Pierre Boucher28// Position : Professor of Finance29// Institution : Université du Québec en Outaouais (UQO)30// Department : Département des sciences administratives31// Organization : SP Boucher32//33// Website : https://spboucher.ai34// Git : https://git.spboucher.ai35//36// =============================================================================37// OFFICIAL CONTACT DIRECTORY38// =============================================================================39//40// General : info@spboucher.ai41// Professional : contact@spboucher.ai42// Direct : simon@spboucher.ai43// Research : research@spboucher.ai44// Development : dev@spboucher.ai45// Support : support@spboucher.ai46// Security/Admin : admin@spboucher.ai47// Notifications : notifications@spboucher.ai48//49// Preferred Contact: support@spboucher.ai50//51// =============================================================================52// COPYRIGHT & INTELLECTUAL PROPERTY53// =============================================================================54//55// Copyright (c) 202656// Simon-Pierre Boucher57//58// All rights reserved where applicable.59//60// This file is governed by the applicable project license,61// copyright notices, institutional agreements and relevant law.62//63// Unless expressly authorized by the applicable license or64// rights holder, copying, redistribution, sublicensing,65// publication and commercial exploitation are not permitted.66//67// Existing third-party rights and notices remain unaffected.68//69// =============================================================================70// CONFIDENTIALITY & SECURITY71// =============================================================================72//73// Classification : Public74// Distribution : Public repository; use is governed by the project license75// Security Contact : admin@spboucher.ai76//77// Access to this source does not independently grant permission78// to redistribute or disclose confidential materials.79//80// Do not embed credentials, private keys, access tokens,81// certificates or confidential personal information.82//83// =============================================================================84// LICENSE & MAINTENANCE85// =============================================================================86//87// License : None specified (no license file in this repository)88// Maintainer : Simon-Pierre Boucher89// Technical Contact: dev@spboucher.ai90//91// =============================================================================92// END OF SP BOUCHER SOURCE HEADER93// =============================================================================9495import AstraCore96import Foundation97import Testing98@testable import DocAI99100enum LiveHub {101 static let env = ProcessInfo.processInfo.environment102 static let on = env["ORIXDOCS_LIVE_TESTS"] == "1"103104 struct Target: Sendable, CustomTestStringConvertible {105 var kind: ProviderKind106 var keyVariable: String107 /// The cheapest current chat model that takes tools, as ORIX Astra's live tests use it (2026-11-21 / 2026-11-22).108 var model: String109 var testDescription: String { kind.rawValue }110 }111 static let targets: [Target] = [112 .init(kind: .openAI, keyVariable: "OPENAI_API_KEY", model: "gpt-6-luna"),113 .init(kind: .anthropic, keyVariable: "ANTHROPIC_API_KEY", model: "claude-haiku-5-5"),114 .init(kind: .google, keyVariable: "GEMINI_API_KEY", model: "gemini-3.1-flash-lite"),115 .init(kind: .xAI, keyVariable: "XAI_API_KEY", model: "grok-4.3"),116 .init(kind: .mistral, keyVariable: "MISTRAL_API_KEY", model: "ministral-3b-latest"),117 .init(kind: .deepSeek, keyVariable: "DEEPSEEK_API_KEY", model: "deepseek-v4-pro"),118 .init(kind: .moonshot, keyVariable: "MOONSHOT_API_KEY", model: "kimi-k2.6"),119 .init(kind: .cerebras, keyVariable: "CEREBRAS_API_KEY", model: "qwen-3.8-27b"),120 .init(kind: .deepInfra, keyVariable: "DEEPINFRA_API_KEY", model: "meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo"),121 .init(kind: .openRouter, keyVariable: "OPENROUTER_API_KEY", model: "openai/gpt-6-luna"),122 ]123 static func key(_ t: Target) -> String? { env[t.keyVariable].flatMap { $0.isEmpty ? nil : $0 } }124 /// A DeepInfra variable holding a Cerebras key (`csk-…`) is not a DeepInfra key: reported, not run (ORIX Astra's live tests do the same).125 static func keyIsForeign(_ t: Target) -> Bool {126 guard t.kind == .deepInfra, let k = key(t) else { return false }127 return k.hasPrefix("csk-") || k == env["CEREBRAS_API_KEY"]128 }129 static var available: [Target] { on ? targets.filter { key($0) != nil } : [] }130131 /// One line per provider, no secret: collected for the report file (`ORIXDOCS_LIVE_REPORT=<path>`).132 struct Row: Codable, Sendable {133 var provider: String; var model: String134 var verify: String; var modelCount: Int?135 var stream: String; var text: String?; var inputTokens: Int?; var outputTokens: Int?; var timeToFirstToken: Double?; var totalTime: Double?; var costUSD: Double?136 var tool: String; var toolArguments: String?137 }138 actor Report {139 static let shared = Report()140 private var rows: [Row] = []141 func add(_ row: Row) {142 rows.append(row)143 guard let path = LiveHub.env["ORIXDOCS_LIVE_REPORT"], !path.isEmpty else { return }144 let encoder = JSONEncoder(); encoder.outputFormatting = [.prettyPrinted, .sortedKeys]145 try? encoder.encode(rows.sorted { $0.provider < $1.provider }).write(to: URL(fileURLWithPath: path), options: .atomic)146 }147 }148149 /// Runs a generation, waiting and trying again when the provider is transiently unavailable and produced nothing.150 static func generate(_ hub: ProviderHub, _ request: GenerationRequest) async -> GenerationOutcome {151 var outcome = await hub.generate(request, containsDocumentContent: false)152 for delay in [10, 30] {153 guard let error = outcome.error, error.isTransient, outcome.text.isEmpty, outcome.toolCalls.isEmpty else { break }154 try? await Task.sleep(nanoseconds: UInt64(delay) * 1_000_000_000)155 outcome = await hub.generate(request, containsDocumentContent: false)156 }157 return outcome158 }159}160161@Suite("Live provider hub", .enabled(if: LiveHub.on), .serialized)162struct LiveHubSmokeTests {163 @Test(arguments: LiveHub.available)164 func verifyStreamAndToolCallThroughTheHub(_ target: LiveHub.Target) async throws {165 let id = ProviderID(target.kind)166 var row = LiveHub.Row(provider: target.kind.rawValue, model: target.model, verify: "not run", stream: "not run", tool: "not run")167 if LiveHub.keyIsForeign(target) {168 row.verify = "not run: \(target.keyVariable) holds another provider's key"169 await LiveHub.Report.shared.add(row)170 print("LIVE \(target.kind.rawValue): \(row.verify)")171 return172 }173 let store = InMemoryCredentialStore()174 let hub = ProviderHub(configuration: .init(credentials: store, storageDirectory: nil))175 try await hub.setKey(try #require(LiveHub.key(target)), for: id)176177 // 1. Connection test.178 let checked = try await hub.verify(id)179 row.verify = checked.state == .verified ? "ok" : "failed: \(checked.errorTitle ?? "?")"180 row.modelCount = checked.modelCount181 #expect(checked.state == .verified, "\(checked.errorTitle ?? ""): \(checked.detail ?? "")")182 guard checked.state == .verified else { await LiveHub.Report.shared.add(row); return }183 let models = try await hub.models(for: id)184 row.modelCount = models.count185 #expect(!models.isEmpty)186 let ref = ModelRef(provider: target.kind, modelID: target.model)187188 // 2. One tiny streamed completion.189 let ask = GenerationRequest(model: ref, messages: [.user("Reply with exactly: ORIX-OK")], parameters: GenerationParameters(maxOutputTokens: 64, reasoning: .off))190 let answer = await LiveHub.generate(hub, ask)191 row.stream = answer.error.map { "failed: \($0.title)" } ?? (answer.text.contains("ORIX-OK") ? "ok" : "unexpected text")192 row.text = String(answer.text.prefix(40)); row.inputTokens = answer.usage?.inputTokens; row.outputTokens = answer.usage?.outputTokens193 row.timeToFirstToken = answer.timing.timeToFirstToken; row.totalTime = answer.timing.totalTime194 row.costUSD = await hub.cost(of: answer, model: ref).amountUSD195 #expect(answer.error == nil, "\(answer.error?.title ?? ""): \(answer.error?.message ?? "")")196 #expect(answer.text.contains("ORIX-OK"))197 #expect(answer.stopReason == .endOfTurn)198 #expect(answer.usage?.outputTokens != nil)199200 // 3. One tool call.201 let tool = ToolDefinition(name: "get_weather", summary: "Get the current weather for a city.",202 parameters: ["type": "object", "properties": ["city": ["type": "string"]], "required": ["city"], "additionalProperties": false])203 let call = GenerationRequest(model: ref, system: "Use the get_weather tool to answer weather questions.", messages: [.user("What is the weather in Paris right now?")],204 parameters: GenerationParameters(maxOutputTokens: 256, reasoning: .off), tools: [tool])205 let called = await LiveHub.generate(hub, call)206 let weather = called.toolCalls.first { $0.name == "get_weather" }207 row.tool = called.error.map { "failed: \($0.title)" } ?? (weather != nil ? "ok" : "no tool call")208 row.toolArguments = weather?.arguments["city"]?.stringValue209 #expect(called.error == nil, "\(called.error?.title ?? ""): \(called.error?.message ?? "")")210 #expect(weather != nil)211 #expect(weather?.arguments["city"]?.stringValue?.lowercased().contains("paris") == true)212 #expect(called.stopReason == .toolCalls)213214 // The ledger saw both requests; nothing was persisted (no storage folder) and the key never left the in-memory store.215 let usage = await hub.usageSnapshot()216 #expect(usage.usage(for: ref)?.requests ?? 0 >= 2)217 await LiveHub.Report.shared.add(row)218 print("LIVE \(row.provider) model=\(row.model) verify=\(row.verify) models=\(row.modelCount ?? -1) stream=\(row.stream) in=\(row.inputTokens ?? -1) out=\(row.outputTokens ?? -1) "219 + "ttft=\(row.timeToFirstToken.map { String(format: "%.2fs", $0) } ?? "-") tool=\(row.tool) city=\(row.toolArguments ?? "-")")220 }221}222