Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Astra9// File : Tests/AstraProvidersTests/LiveSmokeTests.swift10// Module : AstraProvidersTests11// 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 CoreGraphics90import Foundation91import ImageIO92import Testing93@testable import AstraProviders9495/// Live checks against the real providers. Disabled unless `ASTRA_LIVE_TESTS=1` and the provider's key variable is set96/// (`source Scripts/smoke-env.sh`). Requests are tiny and bounded; no key is ever printed, logged or written.97enum Live {98 static let env = ProcessInfo.processInfo.environment99 static let on = env["ASTRA_LIVE_TESTS"] == "1"100 static func has(_ name: String) -> Bool { on && !(env[name] ?? "").isEmpty }101 /// `ASTRA_LIVE_MATRIX=1` additionally sends one tiny request to every model each provider lists.102 static let matrix = on && env["ASTRA_LIVE_MATRIX"] == "1"103104 static let keyVariable: [Adapter: String] = [.openAI: "OPENAI_API_KEY", .anthropic: "ANTHROPIC_API_KEY", .openRouter: "OPENROUTER_API_KEY",105 .xAI: "XAI_API_KEY", .google: "GEMINI_API_KEY", .custom: "ASTRA_CUSTOM_KEY",106 .mistral: "MISTRAL_API_KEY", .deepSeek: "DEEPSEEK_API_KEY", .moonshot: "MOONSHOT_API_KEY",107 .cerebras: "CEREBRAS_API_KEY", .deepInfra: "DEEPINFRA_API_KEY"]108 /// The cheapest current chat model of each provider on 2026-11-21 (2026-11-22 for Mistral, DeepSeek, Moonshot, Cerebras, DeepInfra).109 /// Each of the five answers without reasoning when asked to (`reasoning: .off`) and takes tools.110 /// DeepSeek: `deepseek-flash` is cheaper, but on 2026-11-22 it corrupted verbatim answers whenever a system message was present111 /// ("ASTRA-@OK", "ASTRA-###", also without streaming), so the exact-echo test runs on `deepseek-v4-pro`, which did not.112 static let model: [Adapter: String] = [.openAI: "gpt-6-luna", .anthropic: "claude-haiku-5-5", .openRouter: "openai/gpt-6-luna",113 .xAI: "grok-4.3", .google: "gemini-3.1-flash-lite",114 .mistral: "ministral-3b-latest", .deepSeek: "deepseek-v4-pro", .moonshot: "kimi-k2.6",115 .cerebras: "qwen-3.8-27b", .deepInfra: "meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo"]116 /// Where the basic model does not reason, the model the reasoning test uses instead.117 static let reasoningModel: [Adapter: String] = [.mistral: "mistral-small-latest", .moonshot: "kimi-k3", .cerebras: "gpt-oss-120b", .deepInfra: "openai/gpt-oss-120b"]118 /// Where the basic model does not take images, the model the image test uses instead.119 static let visionModel: [Adapter: String] = [.deepSeek: "deepseek-flash", .deepInfra: "google/gemma-3-4b-it"]120 /// The adapters added on 2026-11-22: their reasoning models must return the reasoning in a dedicated field.121 static let keyed: [Adapter] = [.mistral, .deepSeek, .moonshot, .cerebras, .deepInfra]122123 /// A key that plainly belongs to another provider is not a usable key: DeepInfra tokens have no `csk-` prefix (that is Cerebras).124 /// The supplied DEEPINFRA_API_KEY was such a key on 2026-11-22 and DeepInfra answered 401 to it, so its live tests are not run.125 static func keyIsForeign(_ adapter: Adapter) -> Bool {126 guard adapter == .deepInfra, let key = env[keyVariable[adapter] ?? ""] else { return false }127 return key.hasPrefix("csk-") || key == env["CEREBRAS_API_KEY"]128 }129130 /// `ASTRA_LIVE_ONLY=mistral,deepSeek` restricts a live run (and its spend) to the named adapters.131 static let only: Set<String>? = env["ASTRA_LIVE_ONLY"].flatMap { $0.isEmpty ? nil : Set($0.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }) }132133 static func available(_ adapter: Adapter) -> Bool {134 if let only, !only.contains(adapter.rawValue) { return false }135 guard let variable = keyVariable[adapter], has(variable) else { return false }136 if keyIsForeign(adapter) {137 print("LIVE \(adapter.rawValue) not run: no valid key (\(variable) holds another provider's key)")138 return false139 }140 return adapter != .custom || !(env["ASTRA_CUSTOM_BASE_URL"] ?? "").isEmpty141 }142143 static func provider(_ adapter: Adapter, label: String = "") -> any ChatProvider {144 let key = env[keyVariable[adapter] ?? ""] ?? ""145 let transport = TeeTransport(label: label.isEmpty ? nil : "\(adapter.rawValue)_\(label)")146 switch adapter {147 case .openAI: return OpenAIProvider(transport: transport, apiKey: { key })148 case .anthropic: return AnthropicProvider(transport: transport, apiKey: { key })149 case .openRouter: return OpenRouterProvider(transport: transport, apiKey: { key })150 case .xAI: return XAIProvider(transport: transport, apiKey: { key })151 case .google: return GeminiProvider(transport: transport, apiKey: { key })152 case .mistral: return MistralProvider(transport: transport, apiKey: { key })153 case .deepSeek: return DeepSeekProvider(transport: transport, apiKey: { key })154 case .moonshot: return MoonshotProvider(transport: transport, apiKey: { key })155 case .cerebras: return CerebrasProvider(transport: transport, apiKey: { key })156 case .deepInfra: return DeepInfraProvider(transport: transport, apiKey: { key })157 case .custom:158 let profile = EndpointProfile(id: "live", name: "Live", baseURL: env["ASTRA_CUSTOM_BASE_URL"] ?? "")159 return OpenAICompatibleProvider(profile: profile, transport: transport, apiKey: { key })160 }161 }162163 static func modelRef(_ adapter: Adapter, provider: any ChatProvider) async throws -> ModelRef {164 if let id = model[adapter] { return ModelRef(provider: adapter.kind, modelID: id) }165 // Custom endpoint: use whatever it reports.166 let models = try await provider.listModels()167 return try #require(models.first?.ref)168 }169170 /// Collects a live stream, retrying a transient failure (capacity, rate limit, overload) that produced nothing, as the app's orchestrator does.171 static func collect(_ provider: any ChatProvider, _ request: GenerationRequest) async -> Collected {172 var result = await AstraProvidersTests.collect(provider.stream(request))173 for delay in [10, 30, 60] {174 guard let error = result.error, error.isTransient, result.events.isEmpty else { break }175 print("LIVE retry \(request.model.modelID) after \(error.title)")176 try? await Task.sleep(nanoseconds: UInt64(delay) * 1_000_000_000)177 result = await AstraProvidersTests.collect(provider.stream(request))178 }179 return result180 }181182 static func describe(_ usage: TokenUsage?) -> String {183 guard let u = usage else { return "usage: none" }184 return "in \(u.inputTokens.map(String.init) ?? "-") out \(u.outputTokens.map(String.init) ?? "-") cached \(u.cachedInputTokens.map(String.init) ?? "-") reasoning \(u.reasoningTokens.map(String.init) ?? "-")"185 + (u.reportedCostUSD.map { " cost $\($0)" } ?? "")186 }187}188189/// Counts what the live transport saw, without keeping any content: requests that replayed provider state and190/// responses in which Anthropic reported a replayed thinking block as dropped.191final class ReplayObserver: @unchecked Sendable {192 static let shared = ReplayObserver()193 private let lock = NSLock()194 private var dropped = 0, replayed = 0195 func reset() { lock.withLock { dropped = 0; replayed = 0 } }196 func noteRequest(_ body: Data?) {197 guard let body, let text = String(data: body, encoding: .utf8) else { return }198 let markers = [#""type":"thinking""#, #""type":"redacted_thinking""#, #""type":"reasoning""#, #""reasoning_content":""#, #""reasoning":""#, #""reasoning_details":["#, "thoughtSignature"]199 if markers.contains(where: text.contains), !text.contains(#""reasoning_content":"","#) || text.contains(#""type":"thinking""#) { lock.withLock { replayed += 1 } }200 }201 func noteLine(_ line: String) { if line.contains("thinking_dropped") { lock.withLock { dropped += 1 } } }202 var droppedBlocks: Int { lock.withLock { dropped } }203 var replayingRequests: Int { lock.withLock { replayed } }204}205206/// The real network transport; when `ASTRA_RECORD_DIR` is set it also writes the raw stream lines it received, for fixtures.207struct TeeTransport: HTTPTransport {208 let inner = URLSessionTransport()209 var label: String?210211 func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) { try await inner.send(request) }212213 func stream(_ request: URLRequest) async throws -> (HTTPURLResponse, AsyncThrowingStream<String, Error>) {214 ReplayObserver.shared.noteRequest(request.httpBody)215 let (response, raw) = try await inner.stream(request)216 let (lines, observed) = AsyncThrowingStream<String, Error>.makeStream()217 let watcher = Task {218 do { for try await line in raw { ReplayObserver.shared.noteLine(line); observed.yield(line) }; observed.finish() } catch { observed.finish(throwing: error) }219 }220 observed.onTermination = { _ in watcher.cancel() }221 guard let label, let directory = Live.env["ASTRA_RECORD_DIR"], !directory.isEmpty else { return (response, lines) }222 let url = URL(fileURLWithPath: directory).appendingPathComponent("\(label).sse")223 let (out, continuation) = AsyncThrowingStream<String, Error>.makeStream()224 let task = Task {225 var text = ""226 do {227 for try await line in lines { text += line + "\n"; continuation.yield(line) }228 try? text.write(to: url, atomically: true, encoding: .utf8) // response body only: no request, no headers, no key229 continuation.finish()230 } catch { continuation.finish(throwing: error) }231 }232 continuation.onTermination = { _ in task.cancel() }233 return (response, out)234 }235}236237@Suite("Live smoke tests", .enabled(if: Live.on), .serialized)238struct LiveSmokeTests {239 /// DeepInfra's catalogue is public: it is read live even without a valid key, and the key that was supplied is shown to be rejected.240 @Test func deepInfraPublicCatalogueAndRejectedKey() async throws {241 guard Live.on else { return }242 let models = try await DeepInfraProvider(transport: URLSessionTransport(), apiKey: { nil }).listModels()243 #expect(models.count > 20)244 #expect(models.contains { $0.ref.modelID == Live.model[.deepInfra] }, "\(Live.model[.deepInfra] ?? "") is no longer listed")245 for model in models {246 #expect(model.ref.modelID.contains("/"))247 #expect(model.vendor == ModelInfo.owner(of: model.ref.modelID))248 if let pricing = model.pricing { #expect(pricing.inputPerMTok >= 0 && pricing.inputPerMTok < 100) }249 }250 let priced = models.filter { $0.pricing != nil }.count, vision = models.filter { $0.capabilities.contains(.vision) }.count251 print("LIVE deepInfra public catalogue (no key): \(models.count) chat models, \(priced) priced, \(vision) with vision, \(Set(models.compactMap(\.vendor)).count) publishers")252 guard Live.has("DEEPINFRA_API_KEY"), Live.keyIsForeign(.deepInfra) else { return }253 do {254 _ = try await Live.provider(.deepInfra).verify()255 Issue.record("DeepInfra accepted a key that is not a DeepInfra key")256 } catch let error as AstraError {257 guard case .unauthorized = error else { Issue.record("expected unauthorized, got \(error.title)"); return }258 print("LIVE deepInfra supplied key rejected: HTTP 401 unauthorized; generation, tools, reasoning and image tests not run")259 }260 }261262 @Test(arguments: Adapter.allCases)263 func verifyAndListModels(adapter: Adapter) async throws {264 guard Live.available(adapter) else { return }265 let provider = Live.provider(adapter)266 let status = try await provider.verify()267 #expect(status.ok)268 let models = try await provider.listModels()269 #expect(!models.isEmpty)270 if let expected = Live.model[adapter] { #expect(models.contains { $0.ref.modelID == expected }, "\(expected) is no longer listed") }271 if let expected = Live.reasoningModel[adapter] { #expect(models.contains { $0.ref.modelID == expected && $0.capabilities.contains(.reasoning) }, "\(expected) is no longer listed as a reasoning model") }272 for model in models {273 #expect(model.ref.provider == adapter.kind)274 #expect(model.capabilities.contains(.text))275 if let pricing = model.pricing { #expect(!pricing.asOf.isEmpty); #expect(pricing.inputPerMTok >= 0) }276 }277 let summary = "\(models.filter { $0.contextLength != nil }.count) with context, \(models.filter { $0.pricing != nil }.count) priced, \(models.filter { $0.capabilities.contains(.vision) }.count) vision, \(models.filter { $0.capabilities.contains(.reasoning) }.count) reasoning, \(models.filter { $0.capabilities.contains(.tools) }.count) tools"278 print("LIVE \(adapter.rawValue) verify ok, \(models.count) models (\(summary))" + (status.remainingCreditUSD.map { _ in ", credit reported" } ?? ""))279 }280281 @Test(arguments: Adapter.allCases)282 func streamedGeneration(adapter: Adapter) async throws {283 guard Live.available(adapter) else { return }284 let provider = Live.provider(adapter, label: "text")285 let ref = try await Live.modelRef(adapter, provider: provider)286 let request = GenerationRequest(model: ref, system: "You follow instructions exactly.", messages: [.user("Reply with exactly: ASTRA-OK")],287 parameters: GenerationParameters(maxOutputTokens: 32, reasoning: .off))288 let c = await Live.collect(provider, request)289 expectWellFormed(c)290 #expect(c.text.contains("ASTRA-OK"))291 let reported = try #require(c.starts.first?.reportedModel)292 #expect(!reported.isEmpty)293 // The provider may answer with a dated snapshot or a vendor-prefixed id of the model that was asked for.294 let asked = ref.modelID.split(separator: "/").last.map(String.init) ?? ref.modelID295 #expect(reported.contains(asked) || asked.contains(reported), "asked for \(ref.modelID), provider reported \(reported)")296 #expect((c.outcome.usage?.inputTokens ?? 0) > 0)297 #expect((c.outcome.usage?.outputTokens ?? 0) > 0)298 #expect(c.completions == [.endOfTurn])299 print("LIVE \(adapter.rawValue) text: asked \(ref.modelID), reported \(reported), served by \(c.starts.first?.servedBy ?? "-"), \(Live.describe(c.outcome.usage))")300 }301302 @Test(arguments: Adapter.allCases)303 func toolCallRoundTrip(adapter: Adapter) async throws {304 guard Live.available(adapter) else { return }305 let provider = Live.provider(adapter, label: "tool")306 try await roundTrip(adapter, provider: provider, ref: try await Live.modelRef(adapter, provider: provider), reasoning: .off)307 }308309 /// The same round trip with reasoning on, on the models whose tool cycles have special rules: OpenAI reasoning items,310 /// Anthropic thinking blocks (never replayed), Sonnet 5.5 `between_tools`, Gemini thought signatures, models without call ids.311 static let toolCycleModels: [(Adapter, String, ReasoningEffort?)] = [312 (.openAI, "gpt-6.2-sol", .low), (.openAI, "gpt-4.1-mini", nil),313 (.anthropic, "claude-sonnet-5-5", .low), (.anthropic, "claude-sonnet-5-5", .off), (.anthropic, "claude-opus-5-5", .off), (.anthropic, "claude-haiku-4-5", .low), (.anthropic, "claude-haiku-5-5", .medium),314 (.google, "gemini-4-hydrogen", .low), (.google, "gemini-2.5-flash-lite", .low), (.google, "gemini-3.1-flash-lite", .medium),315 (.xAI, "grok-4.7", .low), (.xAI, "grok-4.20-0309-non-reasoning", nil),316 (.openRouter, "anthropic/claude-haiku-5.5", .low), (.openRouter, "google/gemini-3.1-flash-lite", .low),317 // Mistral thinking chunks; DeepSeek thinking mode (history must carry `reasoning_content`); Kimi thinking; Cerebras `reasoning`.318 // `mistral-small-latest` / `mistral-medium-latest` at effort `high` have their own test below (`mistralHighEffortToolCycleEndsWithAnAnswer`).319 (.mistral, "mistral-large-latest", .high), (.mistral, "mistral-large-latest", .low), (.mistral, "mistral-small-latest", .off), (.mistral, "mistral-medium-latest", nil),320 (.openAI, "gpt-6-luna", .medium), (.xAI, "grok-4.3", .low), (.anthropic, "claude-opus-5-5", .medium), (.openRouter, "openai/gpt-6-luna", .medium),321 (.deepSeek, "deepseek-flash", .low), (.deepSeek, "deepseek-flash", nil), (.deepSeek, "deepseek-v4-pro", .medium),322 (.moonshot, "kimi-k3", .low), (.moonshot, "kimi-k3", .off), (.moonshot, "kimi-k3.1-pro", .low), (.moonshot, "kimi-k2.7-code", .off), (.moonshot, "kimi-k2.6", nil),323 (.moonshot, "kimi-k3.1-pro-highspeed", .low), (.moonshot, "kimi-k2.7-code-highspeed", nil),324 (.cerebras, "gpt-oss-120b", .low), (.cerebras, "gpt-oss-120b", .off), (.cerebras, "qwen-3.8-27b", .medium),325 ]326327 @Test(.enabled(if: Live.matrix), arguments: 0..<LiveSmokeTests.toolCycleModels.count)328 func toolCallRoundTripWithReasoning(index: Int) async throws {329 let (adapter, model, effort) = Self.toolCycleModels[index]330 guard Live.available(adapter) else { return }331 try await roundTrip(adapter, provider: Live.provider(adapter), ref: ModelRef(provider: adapter.kind, modelID: model), reasoning: effort)332 }333334 /// Without their thinking chunks in the history these two models called the tool again instead of answering in about 4 of335 /// 5 live tries on 2026-11-22. With the chunks replayed from `ToolCall.providerState` every try must end with an answer.336 @Test(.enabled(if: Live.matrix), arguments: ["mistral-small-latest", "mistral-medium-latest"])337 func mistralHighEffortToolCycleEndsWithAnAnswer(model: String) async throws {338 guard Live.available(.mistral) else { return }339 for attempt in 1...5 {340 try await roundTrip(.mistral, provider: Live.provider(.mistral), ref: ModelRef(provider: .mistral, modelID: model), reasoning: .high, expectState: true, note: "try \(attempt) of 5")341 }342 }343344 /// What the app does between the two legs: the tool calls are stored and read back (here through their `Codable` form),345 /// so anything a provider needs again must survive that, not live in this process's memory.346 static func persisted(_ calls: [ToolCall]) throws -> [ToolCall] { try JSONDecoder().decode([ToolCall].self, from: JSONEncoder().encode(calls)) }347348 /// Tool cycles in which the model has to reason before it can choose the call, so that there is reasoning to carry back:349 /// OpenAI / xAI encrypted reasoning items, Anthropic signed thinking blocks (adaptive models, with the binding control),350 /// OpenRouter `reasoning_details`, DeepSeek `reasoning_content`.351 static let replayModels: [(Adapter, String, ReasoningEffort)] = [352 (.openAI, "gpt-6.2-sol", .high), (.openAI, "gpt-6-luna", .high), (.xAI, "grok-4.7", .medium),353 (.anthropic, "claude-sonnet-5-5", .high), (.anthropic, "claude-opus-5-5", .medium), (.anthropic, "claude-haiku-5-5", .high), (.anthropic, "claude-haiku-4-5", .medium),354 (.google, "gemini-3.1-flash-lite", .medium),355 (.openRouter, "anthropic/claude-haiku-5.5", .high), (.openRouter, "openai/gpt-6-luna", .high), (.openRouter, "google/gemini-3.1-flash-lite", .medium),356 (.deepSeek, "deepseek-flash", .medium), (.deepSeek, "deepseek-v4-pro", .medium), (.moonshot, "kimi-k3", .medium),357 (.cerebras, "gpt-oss-120b", .medium), (.mistral, "mistral-large-latest", .medium),358 ]359 static let reasonedQuestion = "Work out 17 x 23 in your head. If the result is odd, call the get_weather tool for Paris; if it is even, call it for Rome. Then tell me the weather in one short sentence."360361 @Test(.enabled(if: Live.matrix), arguments: 0..<LiveSmokeTests.replayModels.count)362 func toolCycleReplaysReasoning(index: Int) async throws {363 let (adapter, model, effort) = Self.replayModels[index]364 guard Live.available(adapter) else { return }365 try await roundTrip(adapter, provider: Live.provider(adapter), ref: ModelRef(provider: adapter.kind, modelID: model), reasoning: effort, note: "reasoned", question: Self.reasonedQuestion)366 }367368 func roundTrip(_ adapter: Adapter, provider: any ChatProvider, ref: ModelRef, reasoning: ReasoningEffort?, expectState: Bool = false, note: String = "",369 question text: String = "What is the weather in Paris right now? Call the get_weather tool, then answer in one short sentence.") async throws {370 ReplayObserver.shared.reset()371 let question = PromptMessage.user(text)372 let budget = reasoning == .off || reasoning == nil ? 256 : 3000373 let first = await Live.collect(provider, GenerationRequest(model: ref, messages: [question], parameters: GenerationParameters(maxOutputTokens: budget, reasoning: reasoning), tools: [weatherTool]))374 expectWellFormed(first)375 #expect(first.completions == [.toolCalls], "\(ref.modelID): \(String(describing: first.error))")376 let call = try #require(first.outcome.toolCalls.first)377 #expect(call.name == "get_weather")378 #expect(call.arguments["city"]?.stringValue?.contains("Paris") == true)379 #expect(first.toolStarts.contains(call.id))380381 // Second leg: replay the call and its result exactly as the app would.382 let calls = try Self.persisted(first.outcome.toolCalls)383 #expect(calls == first.outcome.toolCalls)384 let stateBytes = calls.compactMap { $0.providerState?.serialized().utf8.count }.reduce(0, +)385 #expect(stateBytes <= 256 * 1024 * max(calls.count, 1))386 if expectState { #expect(stateBytes > 0, "\(ref.modelID): no provider state on the tool call") }387 let history = [question, .assistant(first.text, toolCalls: calls)]388 + calls.map { PromptMessage.tool("18 C, cloudy", callID: $0.id, name: $0.name) }389 let second = await Live.collect(provider, GenerationRequest(model: ref, messages: history, parameters: GenerationParameters(maxOutputTokens: budget, reasoning: reasoning), tools: [weatherTool]))390 expectWellFormed(second)391 #expect(second.text.contains("18"), "\(ref.modelID): \(String(describing: second.error))")392 #expect(second.completions == [.endOfTurn])393 // Anthropic reports a replayed thinking block it had to drop; none may be dropped when the history is replayed faithfully.394 #expect(ReplayObserver.shared.droppedBlocks == 0, "\(ref.modelID): replayed thinking was dropped")395 if stateBytes > 0 { #expect(ReplayObserver.shared.replayingRequests >= 1, "\(ref.modelID): state was not sent back") }396 print("LIVE \(adapter.rawValue) tool: \(ref.modelID) reasoning \(reasoning?.rawValue ?? "default") called \(call.name)(\(call.arguments.serialized())), then \(second.completions == [.endOfTurn] ? "answered" : "DID NOT ANSWER"); first leg reasoning \(first.outcome.usage?.reasoningTokens.map(String.init) ?? "-") tokens, state \(stateBytes) bytes, replayed in \(ReplayObserver.shared.replayingRequests) request(s), dropped \(ReplayObserver.shared.droppedBlocks); \(Live.describe(second.outcome.usage))\(note.isEmpty ? "" : " [\(note)]")")397 }398399 @Test(arguments: [Adapter.openAI, .anthropic, .xAI, .google, .openRouter] + Live.keyed)400 func reasoningSummary(adapter: Adapter) async throws {401 guard Live.available(adapter) else { return }402 let provider = Live.provider(adapter, label: "reasoning")403 var ref = try await Live.modelRef(adapter, provider: provider)404 if let id = Live.reasoningModel[adapter] { ref.modelID = id }405 let request = GenerationRequest(model: ref, messages: [.user("A farmer has chickens and rabbits: 35 heads and 94 legs. How many of each? Answer in one line.")],406 parameters: GenerationParameters(maxOutputTokens: 1500, reasoning: .medium))407 let c = await Live.collect(provider, request)408 expectWellFormed(c)409 #expect(c.text.contains("23"))410 #expect(c.text.contains("12"))411 // A summary is shown when the provider returns one; whether it does for a small problem is the provider's choice.412 // The five keyed providers return the reasoning itself in a dedicated field, so it must be there.413 if Live.keyed.contains(adapter) {414 #expect(!c.reasoning.isEmpty, "\(ref.modelID) returned no reasoning")415 #expect((c.outcome.usage?.reasoningTokens ?? 0) > 0)416 #expect(!c.text.contains("<think>"))417 }418 print("LIVE \(adapter.rawValue) reasoning: \(ref.modelID) summary \(c.reasoning.count) chars, \(Live.describe(c.outcome.usage))")419 }420421 /// A solid red 64 x 64 PNG, drawn here so no image file ships with the tests.422 static func redPNG() throws -> ImageInput {423 let side = 64424 let context = try #require(CGContext(data: nil, width: side, height: side, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(),425 bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue))426 context.setFillColor(red: 1, green: 0, blue: 0, alpha: 1)427 context.fill(CGRect(x: 0, y: 0, width: side, height: side))428 let image = try #require(context.makeImage())429 let data = NSMutableData()430 let destination = try #require(CGImageDestinationCreateWithData(data, "public.png" as CFString, 1, nil))431 CGImageDestinationAddImage(destination, image, nil)432 #expect(CGImageDestinationFinalize(destination))433 return ImageInput(data: data as Data, mimeType: "image/png")434 }435436 @Test(arguments: [Adapter.openAI, .anthropic, .xAI, .google, .openRouter] + Live.keyed)437 func imageInput(adapter: Adapter) async throws {438 guard Live.available(adapter) else { return }439 let provider = Live.provider(adapter)440 var ref = try await Live.modelRef(adapter, provider: provider)441 if let id = Live.visionModel[adapter] { ref.modelID = id }442 let request = GenerationRequest(model: ref, messages: [.user("What single colour fills this image? Answer with one word.", images: [try Self.redPNG()])],443 parameters: GenerationParameters(maxOutputTokens: 64, reasoning: .off))444 let c = await Live.collect(provider, request)445 expectWellFormed(c)446 #expect(c.text.lowercased().contains("red"), "\(adapter.rawValue) answered: \(c.text.prefix(60))")447 print("LIVE \(adapter.rawValue) image: \(ref.modelID) answered \(c.text.trimmingCharacters(in: .whitespacesAndNewlines).prefix(20)), \(Live.describe(c.outcome.usage))")448 }449450 @Test(arguments: [Adapter.openAI, .anthropic, .xAI, .google, .openRouter] + Live.keyed)451 func badKeyIsReportedAsUnauthorized(adapter: Adapter) async {452 // DeepInfra needs no valid key to show how it answers an invalid one.453 guard Live.available(adapter) || (adapter == .deepInfra && Live.on) else { return }454 let bad = adapter.key // a syntactically plausible key that no provider issued455 let transport = URLSessionTransport()456 let provider: any ChatProvider = switch adapter {457 case .openAI: OpenAIProvider(transport: transport, apiKey: { bad })458 case .anthropic: AnthropicProvider(transport: transport, apiKey: { bad })459 case .openRouter: OpenRouterProvider(transport: transport, apiKey: { bad })460 case .xAI: XAIProvider(transport: transport, apiKey: { bad })461 case .mistral: MistralProvider(transport: transport, apiKey: { bad })462 case .deepSeek: DeepSeekProvider(transport: transport, apiKey: { bad })463 case .moonshot: MoonshotProvider(transport: transport, apiKey: { bad })464 case .cerebras: CerebrasProvider(transport: transport, apiKey: { bad })465 case .deepInfra: DeepInfraProvider(transport: transport, apiKey: { bad })466 default: GeminiProvider(transport: transport, apiKey: { bad })467 }468 let c = await collect(provider.stream(request(adapter.kind, Live.model[adapter] ?? "")))469 guard case .unauthorized = c.error else { Issue.record("\(adapter.rawValue): expected unauthorized, got \(String(describing: c.error))"); return }470 #expect(c.error?.message.contains(bad) == false)471 if Live.keyed.contains(adapter) {472 #expect(c.error?.message.contains(String(bad.suffix(4))) == false) // DeepSeek echoes the last characters of a rejected key473 // The same key is refused by the model list too.474 do { _ = try await provider.verify(); Issue.record("\(adapter.rawValue): verify accepted a bad key") }475 catch { if case .unauthorized = AstraError.wrap(error) {} else { Issue.record("\(adapter.rawValue): verify gave \(AstraError.wrap(error).title)") } }476 print("LIVE \(adapter.rawValue) bad key: unauthorized (stream and verify)")477 }478 }479480 /// One tiny request to every chat model each provider lists, with a temperature and a reasoning effort set, so the481 /// parameter fallbacks are exercised against the real APIs. Opt-in: `ASTRA_LIVE_MATRIX=1`.482 @Test(.enabled(if: Live.matrix), arguments: Adapter.allCases)483 func everyListedModelAnswers(adapter: Adapter) async throws {484 guard Live.available(adapter) else { return }485 let provider = Live.provider(adapter)486 var refs = try await provider.listModels().map(\.ref)487 if adapter == .openRouter {488 // The catalogue has hundreds of models: sample one per major upstream.489 let sample = ["anthropic/claude-haiku-5.5", "google/gemini-3.1-flash-lite", "x-ai/grok-4.3", "openai/gpt-6-luna"]490 refs = refs.filter { sample.contains($0.modelID) }491 }492 if adapter == .openAI { refs = refs.filter { !$0.modelID.contains("-pro") } } // the pro tier is priced out of a smoke test493 // Mistral lists speech-understanding chat models (Voxtral) that want audio; they are not text chat models.494 if adapter == .mistral { refs = refs.filter { !$0.modelID.hasPrefix("voxtral") } }495 var failures: [String] = []496 await withTaskGroup(of: (String, Collected).self) { group in497 var pending = refs[...]498 func add(_ group: inout TaskGroup<(String, Collected)>) {499 guard let ref = pending.popFirst() else { return }500 group.addTask {501 let request = GenerationRequest(model: ref, messages: [.user("Reply with exactly: ASTRA-OK")],502 parameters: GenerationParameters(temperature: 0.5, maxOutputTokens: 200, reasoning: .low))503 return (ref.modelID, await Live.collect(provider, request))504 }505 }506 for _ in 0..<4 { add(&group) }507 for await (id, c) in group {508 add(&group)509 let ok = c.error == nil && c.contractViolation == nil && c.completions.count == 1510 let line = "LIVE-MATRIX \(adapter.rawValue) \(id): " + (ok ? "ok" : "FAILED") + " reported \(c.starts.first?.reportedModel ?? "-") stop \(c.completions.first?.rawValue ?? "-") text \(c.text.contains("ASTRA-OK") ? "match" : "\(c.text.count) chars") \(Live.describe(c.outcome.usage))"511 + (c.error.map { " error: \($0.title): \($0.message.prefix(160))" } ?? "")512 print(line)513 if !ok { failures.append(line) }514 }515 }516 print("LIVE-MATRIX \(adapter.rawValue) total: \(refs.count - failures.count) of \(refs.count) completed")517 #expect(failures.isEmpty, "\(failures.count) of \(refs.count) models failed")518 }519}520