Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Astra9// File : Tests/AstraProvidersTests/KeyedChatCompletionsProviderTests.swift10// Module : AstraProvidersTests11// Repository : https://git.spboucher.ai/orix-astra12// Created : 2026-11-2213// Last Modified : 2026-11-2214//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 Foundation90import Testing91@testable import AstraProviders9293// Mistral, DeepSeek, Moonshot (Kimi), Cerebras and DeepInfra: Chat Completions dialects on the shared codec.94// Transcripts named `<provider>_*.sse` were captured from the live APIs on 2026-11-22 (response ids replaced), except the95// DeepInfra ones, which are synthetic and say so in their first line: no valid DeepInfra key was available that day.9697private let fullParameters = GenerationParameters(temperature: 0.4, topP: 0.8, maxOutputTokens: 50, reasoning: .off, seed: 7, stop: ["END"])9899/// A request that exercises everything the encoder writes: system text, an image, a full tool cycle, every parameter.100private func fullRequest(_ adapter: Adapter, parameters: GenerationParameters = fullParameters) -> GenerationRequest {101 GenerationRequest(model: ModelRef(provider: adapter.kind, modelID: adapter.model), system: "Be brief.",102 messages: [.user("Look", images: [tinyPNG])] + toolCycle(), parameters: parameters, tools: [weatherTool])103}104105private func sse(_ chunks: [String]) -> FixtureTransport.Reply {106 FixtureTransport.Reply(headers: ["Content-Type": "text/event-stream"], body: chunks.map { "data: \($0)\n\n" }.joined())107}108109/// The message layout every one of these dialects shares.110private func expectSharedMessageLayout(_ body: JSONValue, sourceLocation: SourceLocation = #_sourceLocation) {111 let messages = body["messages"]?.arrayValue ?? []112 #expect(body["stream"] == true, sourceLocation: sourceLocation)113 #expect(messages.count == 5, sourceLocation: sourceLocation)114 #expect(messages.first == ["role": "system", "content": "Be brief."], sourceLocation: sourceLocation)115 #expect(messages[safe: 1]?["content"]?[0] == ["type": "text", "text": "Look"], sourceLocation: sourceLocation)116 #expect(messages[safe: 1]?["content"]?[1] == ["type": "image_url", "image_url": ["url": .string("data:image/png;base64,\(tinyPNG.data.base64EncodedString())")]], sourceLocation: sourceLocation)117 #expect(messages[safe: 3]?["tool_calls"]?[0] == ["id": "call_abc123", "type": "function", "function": ["name": "get_weather", "arguments": "{\"city\":\"Paris\"}"]], sourceLocation: sourceLocation)118 #expect(messages[safe: 4] == ["role": "tool", "tool_call_id": "call_abc123", "content": "18 C, cloudy"], sourceLocation: sourceLocation)119 #expect(body["tools"]?[0] == ["type": "function", "function": ["name": "get_weather", "description": "Get the current weather for a city.", "parameters": weatherTool.parameters]], sourceLocation: sourceLocation)120 #expect(body["tool_choice"] == nil, sourceLocation: sourceLocation) // the provider default ("auto") is what the app wants121 #expect(body["provider"] == nil, sourceLocation: sourceLocation)122}123124private extension Array {125 subscript(safe index: Int) -> Element? { indices.contains(index) ? self[index] : nil }126}127128private let keyedAdapters: [Adapter] = [.mistral, .deepSeek, .moonshot, .cerebras, .deepInfra]129130// MARK: - Shared behaviour131132@Suite("Keyed Chat Completions providers: shared behaviour")133struct KeyedChatCompletionsSharedTests {134 @Test(arguments: keyedAdapters)135 func keyTravelsOnlyInTheAuthorizationHeader(adapter: Adapter) async {136 let transport = FixtureTransport(.sse(adapter.textFixture))137 _ = await collect(adapter.make(transport).stream(fullRequest(adapter)))138 let r = transport.requests[0]139 #expect(r.httpMethod == "POST")140 #expect(r.value(forHTTPHeaderField: "Authorization") == "Bearer \(adapter.key)")141 #expect(r.value(forHTTPHeaderField: "Content-Type") == "application/json")142 #expect(r.value(forHTTPHeaderField: "Accept") == "text/event-stream")143 for (name, value) in r.allHTTPHeaderFields ?? [:] where name != "Authorization" { #expect(!value.contains(adapter.key)) }144 #expect(r.url?.absoluteString.contains(adapter.key) == false)145 #expect(String(decoding: r.httpBody ?? Data(), as: UTF8.self).contains(adapter.key) == false)146 expectSharedMessageLayout(transport.body())147 }148149 @Test(arguments: keyedAdapters)150 func baseURLCanBeOverridden(adapter: Adapter) async {151 let transport = FixtureTransport(.sse(adapter.textFixture))152 let base = URL(string: "https://proxy.example.com/x/v9")!153 let provider: any ChatProvider = switch adapter {154 case .mistral: MistralProvider(transport: transport, apiKey: { "k-0123456789" }, baseURL: base)155 case .deepSeek: DeepSeekProvider(transport: transport, apiKey: { "k-0123456789" }, baseURL: base)156 case .moonshot: MoonshotProvider(transport: transport, apiKey: { "k-0123456789" }, baseURL: base)157 case .cerebras: CerebrasProvider(transport: transport, apiKey: { "k-0123456789" }, baseURL: base)158 default: DeepInfraProvider(transport: transport, apiKey: { "k-0123456789" }, baseURL: base)159 }160 _ = await collect(provider.stream(adapter.request))161 #expect(transport.requests.first?.url?.absoluteString == "https://proxy.example.com/x/v9/chat/completions")162 }163164 @Test(arguments: keyedAdapters)165 func midStreamErrorAfterTextIsATypedError(adapter: Adapter) async {166 let model = adapter.model167 let reply = sse([#"{"id":"r1","model":"\#(model)","choices":[{"index":0,"delta":{"role":"assistant","content":"Partial "},"finish_reason":null}]}"#,168 #"{"error":{"message":"The engine is overloaded, try again.","type":"server_error","code":"overloaded"}}"#])169 let c = await collect(adapter.make(FixtureTransport(reply)).stream(adapter.request))170 #expect(c.text == "Partial ") // what was already delivered stays valid171 #expect(c.error == .overloaded("The engine is overloaded, try again."))172 #expect(c.completions.isEmpty)173 #expect(c.starts.count == 1)174 }175176 @Test(arguments: keyedAdapters)177 func connectionClosedBeforeTheEndIsANetworkError(adapter: Adapter) async {178 let reply = sse([#"{"id":"r1","model":"\#(adapter.model)","choices":[{"index":0,"delta":{"role":"assistant","content":"Half"},"finish_reason":null}]}"#])179 let c = await collect(adapter.make(FixtureTransport(reply)).stream(adapter.request))180 #expect(c.text == "Half")181 if case .network = c.error {} else { Issue.record("expected a network error, got \(String(describing: c.error))") }182 }183184 @Test(arguments: keyedAdapters)185 func lengthAndFilterFinishReasons(adapter: Adapter) async {186 for (reason, expected) in [("length", StopReason.maxTokens), ("content_filter", .contentFilter), ("stop", .endOfTurn), ("tool_calls", .toolCalls)] {187 let reply = sse([#"{"id":"r1","model":"m","choices":[{"index":0,"delta":{"role":"assistant","content":"x"},"finish_reason":null}]}"#,188 #"{"id":"r1","model":"m","choices":[{"index":0,"delta":{},"finish_reason":"\#(reason)"}],"usage":{"prompt_tokens":3,"completion_tokens":1}}"#, "[DONE]"])189 let c = await collect(adapter.make(FixtureTransport(reply)).stream(adapter.request))190 expectWellFormed(c)191 #expect(c.completions == [expected])192 }193 }194195 @Test(arguments: keyedAdapters)196 func thinkTagsInsideContentAreAnswerTextNotReasoning(adapter: Adapter) async {197 // A hosted open model may put its thinking inline. It is not in a dedicated field, so it is passed through untouched.198 let reply = sse([#"{"id":"r1","model":"m","choices":[{"index":0,"delta":{"role":"assistant","content":"<think>\nc + r = 35"},"finish_reason":null}]}"#,199 #"{"id":"r1","model":"m","choices":[{"index":0,"delta":{"content":"\n</think>\n\n23 and 12"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":9}}"#, "[DONE]"])200 let c = await collect(adapter.make(FixtureTransport(reply)).stream(adapter.request))201 expectWellFormed(c)202 #expect(c.text == "<think>\nc + r = 35\n</think>\n\n23 and 12")203 #expect(c.reasoning.isEmpty)204 }205206 @Test(arguments: keyedAdapters)207 func rateLimitHonoursRetryAfter(adapter: Adapter) async {208 let transport = FixtureTransport(.json(429, adapter.errorBody(type: "rate_limit_error", message: "Slow down."), headers: ["Retry-After": "12", "x-ratelimit-remaining-requests-minute": "0"]))209 let c = await collect(adapter.make(transport).stream(adapter.request))210 #expect(c.error == .rateLimited(retryAfter: 12, message: "Slow down."))211 }212213 @Test func effortFallbackReadsTheValuesAProviderLists() {214 let mistral = "reasoning_effort='medium' is not supported for this model. Must be one of (<ReasoningEffort.none: 'none'>, <ReasoningEffort.high: 'high'>)"215 #expect(EffortFallback.allowed(in: mistral) == ["none", "high"])216 #expect(EffortFallback.nearest(to: "medium", allowed: ["none", "high"]) == "high")217 #expect(EffortFallback.nearest(to: "low", allowed: ["none", "high"]) == "high") // equally close: reasoning that was asked for is kept on218 let large = "reasoning_effort none is not supported for this model, supported values: [<ReasoningEffort.high: 'high'>, <ReasoningEffort.low: 'low'>, <ReasoningEffort.medium: 'medium'>]"219 #expect(EffortFallback.allowed(in: large) == ["low", "medium", "high"])220 #expect(EffortFallback.nearest(to: "none", allowed: ["low", "medium", "high"]) == "low")221 let cerebras = "Failed to apply chat template to messages due to error: Unsupported reasoning effort: none. Supported values are 'low', 'medium', and 'high'."222 #expect(EffortFallback.allowed(in: cerebras) == ["low", "medium", "high"])223 #expect(EffortFallback.allowed(in: "reasoning_effort is not enabled for this model").isEmpty)224 #expect(EffortFallback.nearest(to: "medium", allowed: ["medium"]) == nil)225 #expect(EffortFallback.nearest(to: "medium", allowed: ["low", "high", "max"]) == "high")226 // Not about the effort: untouched.227 var body: [String: JSONValue] = ["reasoning_effort": "none", "temperature": 0.2]228 let other = ProviderHTTP.Failure(status: 400, body: ProviderErrorBody(code: nil, message: "messages: field required"), retryAfter: nil)229 #expect(!EffortFallback.adjust(other, &body))230 #expect(body["reasoning_effort"] == "none")231 }232233 @Test func validationListsAndFlatErrorBodies() {234 // Mistral: the list sits inside `message`. `input` (what the client sent) is never copied into the message.235 let mistral = ProviderErrorBody.parse(Data(#"{"object":"error","message":{"detail":[{"type":"extra_forbidden","loc":["body","seed"],"msg":"Extra inputs are not permitted","input":"PRIVATE-PROMPT"}]},"type":"invalid_request_error","param":null,"code":null,"raw_status_code":422}"#.utf8))236 #expect(mistral == ProviderErrorBody(code: "invalid_request_error", message: "seed: Extra inputs are not permitted", param: "seed"))237 // FastAPI / DeepInfra: the list is `detail` itself.238 let fastAPI = ProviderErrorBody.parse(Data(#"{"detail":[{"loc":["body","messages",0,"role"],"msg":"Input should be 'system', 'user' or 'assistant'","type":"enum"},{"loc":["body","top_k"],"msg":"Input should be less than 1000","type":"less_than"}]}"#.utf8))239 #expect(fastAPI.message == "messages.0.role: Input should be 'system', 'user' or 'assistant'; top_k: Input should be less than 1000")240 #expect(fastAPI.param == "messages")241 #expect(ProviderErrorBody.parse(Data(#"{"detail":"Invalid API Key"}"#.utf8)).message == "Invalid API Key")242 // Cerebras: no `error` wrapper.243 #expect(ProviderErrorBody.parse(Data(#"{"message":"Wrong API Key","type":"invalid_request_error","param":"api_key","code":"wrong_api_key"}"#.utf8))244 == ProviderErrorBody(code: "wrong_api_key invalid_request_error", message: "Wrong API Key", param: "api_key"))245 }246247 @Test func hostedModelPublisherComesFromTheOwnerSegment() {248 #expect(ModelInfo.owner(of: "meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo") == "meta-llama")249 #expect(ModelInfo.owner(of: "openai/gpt-oss-120b") == "openai")250 #expect(ModelInfo.owner(of: "gpt-oss-120b") == nil)251 #expect(ModelInfo.owner(of: "/odd") == nil)252 }253}254255// MARK: - Mistral256257@Suite("Mistral provider")258struct MistralProviderTests {259 func provider(_ transport: FixtureTransport, diagnostics: RecordingDiagnostics? = nil) -> any ChatProvider { Adapter.mistral.make(transport, diagnostics: diagnostics) }260 static func rejection(_ message: String, code: String = "3051") -> FixtureTransport.Reply {261 .json(400, #"{"object":"error","message":\#(JSONValue.string(message).serialized()),"type":"invalid_request_invalid_args","param":null,"code":"\#(code)","raw_status_code":400}"#)262 }263264 @Test func requestEncoding() async {265 let transport = FixtureTransport(.sse("mistral_text.sse"))266 _ = await collect(provider(transport).stream(fullRequest(.mistral)))267 #expect(transport.requests[0].url?.absoluteString == "https://api.mistral.ai/v1/chat/completions")268 let body = transport.body()269 #expect(body["model"] == "ministral-3b-latest")270 #expect(body["max_tokens"] == 50)271 #expect(body["temperature"] == 0.4)272 #expect(body["top_p"] == 0.8)273 #expect(body["random_seed"] == 7)274 #expect(body["seed"] == nil) // Mistral answers 422 "Extra inputs are not permitted" to `seed`275 #expect(body["stop"] == ["END"])276 #expect(body["reasoning_effort"] == "none")277 #expect(body["stream_options"] == nil) // usage always arrives on the finishing chunk278 }279280 @Test func reasoningEffortIsOmittedUnlessAsked() async {281 let transport = FixtureTransport(.sse("mistral_text.sse"))282 _ = await collect(provider(transport).stream(request(.mistral, "mistral-small-latest")))283 #expect(transport.body()["reasoning_effort"] == nil)284 _ = await collect(provider(transport).stream(request(.mistral, "mistral-small-latest", parameters: GenerationParameters(reasoning: .high))))285 #expect(transport.body(1)["reasoning_effort"] == "high")286 }287288 @Test func text() async {289 let diagnostics = RecordingDiagnostics()290 let transport = FixtureTransport(.sse("mistral_text.sse", headers: ["Content-Type": "text/event-stream", "x-kong-request-id": "kong-fixture"]))291 let c = await collect(provider(transport, diagnostics: diagnostics).stream(request(.mistral, "ministral-3b-latest")))292 expectWellFormed(c)293 #expect(c.text == "ASTRA-OK")294 #expect(c.starts.first == MessageStart(responseID: "resp_fixture", reportedModel: "ministral-3b-latest"))295 #expect(c.completions == [.endOfTurn])296 #expect(c.outcome.usage == TokenUsage(inputTokens: 11, outputTokens: 5, cachedInputTokens: 0, reasoningTokens: 0))297 #expect(diagnostics.records.first?.requestID == "kong-fixture")298 }299300 @Test func toolCallInOneFragment() async {301 let c = await collect(provider(FixtureTransport(.sse("mistral_tool.sse"))).stream(request(.mistral, "ministral-3b-latest", tools: [weatherTool])))302 expectWellFormed(c)303 #expect(c.outcome.toolCalls == [ToolCall(id: "UbtVXGGSM", name: "get_weather", arguments: ["city": "Paris"])]) // Mistral's 9-character id304 #expect(c.deltas(for: "UbtVXGGSM") == [#"{"city": "Paris"}"#])305 #expect(c.completions == [.toolCalls])306 #expect(c.outcome.usage?.inputTokens == 93)307 }308309 @Test func toolCallWithFragmentedArguments() async {310 // Mistral sent the whole call in one chunk in every live capture; the index-keyed continuation form is exercised with a synthetic stream.311 let reply = sse([#"{"id":"r1","model":"m","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}"#,312 #"{"id":"r1","model":"m","choices":[{"index":0,"delta":{"tool_calls":[{"id":"D681PevKs","type":"function","function":{"name":"get_weather","arguments":"{\"ci"},"index":0}]},"finish_reason":null}]}"#,313 #"{"id":"r1","model":"m","choices":[{"index":0,"delta":{"tool_calls":[{"function":{"arguments":"ty\": \"Paris\"}"},"index":0}]},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":9,"completion_tokens":4}}"#, "[DONE]"])314 let c = await collect(provider(FixtureTransport(reply)).stream(request(.mistral, "m", tools: [weatherTool])))315 expectWellFormed(c)316 #expect(c.outcome.toolCalls == [ToolCall(id: "D681PevKs", name: "get_weather", arguments: ["city": "Paris"])])317 #expect(c.deltas(for: "D681PevKs") == [#"{"ci"#, #"ty": "Paris"}"#])318 }319320 @Test func foreignToolCallIDsAreReplayedUnchanged() async {321 // Live on 2026-11-22: ids that are not Mistral's 9 alphanumeric characters were accepted in history, so none is rewritten.322 let transport = FixtureTransport(.sse("mistral_text.sse"))323 let id = "call_00_ET_Pmcb7ieKHymmsq2KrWSm0170"324 _ = await collect(provider(transport).stream(GenerationRequest(model: ModelRef(provider: .mistral, modelID: "m"), messages: toolCycle(callID: id), tools: [weatherTool])))325 let messages = transport.body()["messages"]?.arrayValue ?? []326 #expect(messages[safe: 1]?["tool_calls"]?[0]?["id"] == .string(id))327 #expect(messages[safe: 2]?["tool_call_id"] == .string(id))328 }329330 @Test func reasoningArrivesAsThinkingChunksInsideContent() async {331 let c = await collect(provider(FixtureTransport(.sse("mistral_reasoning.sse"))).stream(request(.mistral, "mistral-large-latest", parameters: GenerationParameters(reasoning: .low))))332 expectWellFormed(c)333 #expect(c.text == "391") // the transition chunk carries the last thinking text and the first answer text334 #expect(c.reasoning.hasPrefix("The user is asking"))335 #expect(c.reasoning.hasSuffix("391."))336 #expect(!c.reasoning.contains("thinking")) // chunk wrappers never leak into the text337 #expect(c.outcome.usage?.reasoningTokens == 69)338 #expect(c.outcome.usage?.outputTokens == 73)339 // Reasoning first, then the answer.340 let kinds = c.events.compactMap { event -> String? in341 switch event { case .reasoningSummaryDelta: "r"; case .textDelta: "t"; default: nil }342 }343 #expect(kinds.last == "t")344 #expect(kinds.dropLast().allSatisfy { $0 == "r" })345 }346347 @Test func effortTheModelRefusesIsReplacedByTheNearestItLists() async {348 let transport = FixtureTransport(Self.rejection("reasoning_effort='medium' is not supported for this model. Must be one of (<ReasoningEffort.none: 'none'>, <ReasoningEffort.high: 'high'>)"),349 .sse("mistral_text.sse"))350 let diagnostics = RecordingDiagnostics()351 let c = await collect(provider(transport, diagnostics: diagnostics).stream(request(.mistral, "mistral-small-latest", parameters: GenerationParameters(reasoning: .medium))))352 expectWellFormed(c)353 #expect(transport.body(0)["reasoning_effort"] == "medium")354 #expect(transport.body(1)["reasoning_effort"] == "high")355 #expect(diagnostics.records.map(\.status) == [400, 200])356 #expect(diagnostics.records.map(\.retryCount) == [0, 1])357 }358359 @Test func offOnAModelWithoutNoneFallsBackToItsLowestEffort() async {360 let transport = FixtureTransport(Self.rejection("reasoning_effort none is not supported for this model, supported values: [<ReasoningEffort.high: 'high'>, <ReasoningEffort.low: 'low'>, <ReasoningEffort.medium: 'medium'>]"),361 .sse("mistral_text.sse"))362 let c = await collect(provider(transport).stream(request(.mistral, "mistral-large-latest", parameters: GenerationParameters(reasoning: .off))))363 expectWellFormed(c)364 #expect(transport.body(1)["reasoning_effort"] == "low")365 }366367 @Test func effortIsDroppedForAModelThatDoesNotReason() async {368 let transport = FixtureTransport(Self.rejection("reasoning_effort is not enabled for this model"), .sse("mistral_text.sse"))369 let c = await collect(provider(transport).stream(request(.mistral, "ministral-3b-latest", parameters: GenerationParameters(temperature: 0.3, reasoning: .off))))370 expectWellFormed(c)371 #expect(transport.requests.count == 2)372 #expect(transport.body(1)["reasoning_effort"] == nil)373 #expect(transport.body(1)["temperature"] == 0.3)374 }375376 @Test func rejectedExtraFieldIsDroppedAndOthersAreReported() async {377 let seed = FixtureTransport.Reply.json(422, #"{"object":"error","message":{"detail":[{"type":"extra_forbidden","loc":["body","random_seed"],"msg":"Extra inputs are not permitted","input":7}]},"type":"invalid_request_error","param":null,"code":null,"raw_status_code":422}"#)378 var transport = FixtureTransport(seed, .sse("mistral_text.sse"))379 var c = await collect(provider(transport).stream(request(.mistral, "m", parameters: GenerationParameters(seed: 7))))380 expectWellFormed(c)381 #expect(transport.body(1)["random_seed"] == nil)382 let other = FixtureTransport.Reply.json(422, #"{"object":"error","message":{"detail":[{"type":"extra_forbidden","loc":["body","bogus_param_zzz"],"msg":"Extra inputs are not permitted","input":1}]},"type":"invalid_request_error","param":null,"code":null,"raw_status_code":422}"#)383 transport = FixtureTransport(other)384 c = await collect(provider(transport).stream(request(.mistral, "m", parameters: GenerationParameters(seed: 7))))385 #expect(c.error == .invalidRequest("bogus_param_zzz: Extra inputs are not permitted"))386 #expect(transport.requests.count == 1)387 }388389 @Test func errorShapes() async {390 var c = await collect(provider(FixtureTransport(.json(400, #"{"object":"error","message":"Invalid model: nonexistent-model-zzz","type":"invalid_model","param":null,"code":"1500","raw_status_code":400}"#))).stream(request(.mistral, "nonexistent-model-zzz")))391 #expect(c.error == .modelNotFound("nonexistent-model-zzz"))392 c = await collect(provider(FixtureTransport(.json(401, #"{"detail":"Invalid API Key"}"#))).stream(request(.mistral, "m")))393 #expect(c.error == .unauthorized("Invalid API Key"))394 c = await collect(provider(FixtureTransport(Self.rejection("Image input is not enabled for this model"))).stream(request(.mistral, "codestral-latest")))395 #expect(c.error == .invalidRequest("Image input is not enabled for this model"))396 }397398 @Test func modelList() async throws {399 let transport = FixtureTransport(.file(200, "mistral_models.json"))400 let models = try await provider(transport).listModels()401 #expect(transport.requests[0].url?.absoluteString == "https://api.mistral.ai/v1/models")402 #expect(transport.requests[0].value(forHTTPHeaderField: "Authorization") == "Bearer \(Adapter.mistral.key)")403 // Embedding, moderation, OCR and transcription models are not chat models.404 #expect(Set(models.map(\.ref.modelID)) == ["ministral-3b-latest", "mistral-small-latest", "mistral-large-latest", "codestral-latest", "zai-glm-5-3-flash", "voxtral-small-latest"])405 let small = try #require(models.first { $0.ref.modelID == "mistral-small-latest" })406 #expect(small.capabilities == [.text, .tools, .vision, .reasoning])407 #expect(small.contextLength == 262_144)408 #expect(small.vendor == "mistralai")409 #expect(small.pricing == nil) // the API has no prices and none was readable in the documentation410 #expect(small.createdAt == nil)411 if case .providerAPI = small.source {} else { Issue.record("expected providerAPI") }412 #expect(models.first { $0.ref.modelID == "codestral-latest" }?.capabilities == [.text, .tools])413 #expect(models.first { $0.ref.modelID == "voxtral-small-latest" }?.capabilities == [.text, .tools, .audioInput])414 #expect(models.first { $0.ref.modelID == "mistral-large-latest" }?.contextLength == 1_048_576)415 let status = try await provider(FixtureTransport(.file(200, "mistral_models.json"))).verify()416 #expect(status.ok && status.modelCount == 6)417 }418}419420// MARK: - DeepSeek421422@Suite("DeepSeek provider")423struct DeepSeekProviderTests {424 func provider(_ transport: FixtureTransport) -> any ChatProvider { Adapter.deepSeek.make(transport) }425426 @Test func requestEncoding() async {427 let transport = FixtureTransport(.sse("deepseek_text.sse"))428 _ = await collect(provider(transport).stream(fullRequest(.deepSeek)))429 #expect(transport.requests[0].url?.absoluteString == "https://api.deepseek.com/chat/completions") // the documented base URL has no /v1430 let body = transport.body()431 #expect(body["model"] == "deepseek-flash")432 #expect(body["max_tokens"] == 50)433 #expect(body["temperature"] == 0.4)434 #expect(body["top_p"] == 0.8)435 #expect(body["seed"] == 7)436 #expect(body["stop"] == ["END"])437 #expect(body["stream_options"] == ["include_usage": true])438 #expect(body["thinking"] == ["type": "disabled"])439 #expect(body["reasoning_effort"] == nil)440 // Thinking is off: nothing to replay.441 #expect(body["messages"]?[3]?["reasoning_content"] == nil)442 }443444 @Test func thinkingAndEffortMapping() async {445 let transport = FixtureTransport(.sse("deepseek_text.sse"))446 for effort in [ReasoningEffort?.none, .low, .medium, .high] {447 _ = await collect(provider(transport).stream(request(.deepSeek, "deepseek-flash", parameters: GenerationParameters(reasoning: effort))))448 }449 #expect(transport.body(0)["thinking"] == nil) // provider default: thinking enabled450 #expect(transport.body(0)["reasoning_effort"] == nil)451 #expect(transport.body(1)["thinking"] == ["type": "enabled"])452 #expect((1...3).map { transport.body($0)["reasoning_effort"]?.stringValue } == ["low", "high", "max"])453 #expect(transport.body(1)["messages"]?[0]?["reasoning_content"] == nil)454 }455456 @Test func thinkingModeToolHistoryCarriesReasoningContent() async {457 // Live on 2026-11-22: 400 "The `reasoning_content` in the thinking mode must be passed back to the API." without it;458 // an empty string is accepted. The core message model keeps no reasoning text, so the empty string is what is sent.459 let transport = FixtureTransport(.sse("deepseek_text.sse"))460 let history = toolCycle() + [.assistant("It is 18 C."), .user("And tomorrow?")]461 for effort in [ReasoningEffort?.none, .medium, .off] {462 _ = await collect(provider(transport).stream(GenerationRequest(model: ModelRef(provider: .deepSeek, modelID: "deepseek-flash"), messages: history,463 parameters: GenerationParameters(reasoning: effort), tools: [weatherTool])))464 }465 for index in 0...1 {466 let messages = transport.body(index)["messages"]?.arrayValue ?? []467 #expect(messages.filter { $0["role"] == "assistant" }.count == 2)468 #expect(messages.filter { $0["role"] == "assistant" }.allSatisfy { $0["reasoning_content"] == "" })469 #expect(messages.filter { $0["role"] != "assistant" }.allSatisfy { $0["reasoning_content"] == nil })470 }471 #expect((transport.body(2)["messages"]?.arrayValue ?? []).allSatisfy { $0["reasoning_content"] == nil })472 }473474 @Test func text() async {475 let c = await collect(provider(FixtureTransport(.sse("deepseek_text.sse"))).stream(request(.deepSeek, "deepseek-flash")))476 expectWellFormed(c)477 #expect(c.text == "ASTRA-OK")478 #expect(c.reasoning.isEmpty)479 #expect(c.starts.first?.reportedModel == "deepseek-flash")480 #expect(c.outcome.usage == TokenUsage(inputTokens: 12, outputTokens: 4, cachedInputTokens: 0))481 #expect(c.completions == [.endOfTurn])482 }483484 @Test func toolCallWithFragmentedArguments() async throws {485 let c = await collect(provider(FixtureTransport(.sse("deepseek_tool.sse"))).stream(request(.deepSeek, "deepseek-flash", tools: [weatherTool])))486 expectWellFormed(c)487 #expect(c.text == "I'll check that for you.") // DeepSeek spoke before calling488 let call = try #require(c.outcome.toolCalls.first)489 #expect(call == ToolCall(id: "call_00_ET_Pmcb7ieKHymmsq2KrWSm0170", name: "get_weather", arguments: ["city": "Paris"]))490 #expect(c.deltas(for: call.id).count >= 4)491 #expect(c.deltas(for: call.id).joined() == #"{"city": "Paris"}"#)492 #expect(c.completions == [.toolCalls])493 #expect(c.outcome.usage?.inputTokens == 318)494 #expect(c.outcome.usage?.outputTokens == 45)495 }496497 @Test func reasoningContent() async {498 let c = await collect(provider(FixtureTransport(.sse("deepseek_reasoning.sse"))).stream(request(.deepSeek, "deepseek-flash")))499 expectWellFormed(c)500 #expect(c.text == "ASTRA-OK")501 #expect(c.reasoning.hasPrefix("The user asks to reply exactly"))502 #expect(c.outcome.usage?.reasoningTokens == 19)503 #expect(c.outcome.usage?.outputTokens == 24) // reasoning tokens are part of the output count504 }505506 @Test func errorShapes() async {507 var c = await collect(provider(FixtureTransport(.json(400, #"{"error":{"message":"The supported API model names are deepseek-flash, deepseek-v4-pro, but you passed nonexistent-model-zzz. (request_id: 940e0eb2)","type":"invalid_request_error","param":null,"code":"invalid_request_error"}}"#))).stream(request(.deepSeek, "nonexistent-model-zzz")))508 #expect(c.error == .modelNotFound("nonexistent-model-zzz"))509 // A rejected key is echoed with its last four characters: they are masked too.510 c = await collect(provider(FixtureTransport(.json(401, #"{"error":{"message":"Authentication Fails, Your api key: ****CKds is invalid (request_id: 691a9de6)","type":"authentication_error","param":null,"code":"invalid_request_error"}}"#))).stream(request(.deepSeek, "deepseek-flash")))511 #expect(c.error == .unauthorized("Authentication Fails, Your api key: ••• is invalid (request_id: 691a9de6)"))512 c = await collect(provider(FixtureTransport(.json(402, #"{"error":{"message":"Insufficient Balance","type":"unknown_error","param":null,"code":"invalid_request_error"}}"#))).stream(request(.deepSeek, "deepseek-flash")))513 #expect(c.error == .quotaExceeded("Insufficient Balance"))514 c = await collect(provider(FixtureTransport(.json(400, #"{"error":{"message":"The `reasoning_content` in the thinking mode must be passed back to the API. (request_id: 1074c489)","type":"invalid_request_error","param":null,"code":"invalid_request_error"}}"#))).stream(request(.deepSeek, "deepseek-flash")))515 if case .invalidRequest = c.error {} else { Issue.record("expected invalidRequest, got \(String(describing: c.error))") }516 }517518 @Test func modelListMergesAPILimitsWithDocumentedPrices() async throws {519 let transport = FixtureTransport(.file(200, "deepseek_models.json"))520 let models = try await provider(transport).listModels()521 #expect(transport.requests[0].url?.absoluteString == "https://api.deepseek.com/models")522 #expect(models.map(\.ref.modelID) == ["deepseek-flash", "deepseek-v4-pro"])523 let flash = models[0], pro = models[1]524 #expect(flash.displayName == "DeepSeek-V4.1-Flash")525 #expect(flash.contextLength == 1_048_576)526 #expect(flash.maxOutputTokens == 393_216)527 #expect(flash.capabilities == [.text, .vision, .tools, .reasoning, .promptCaching])528 #expect(pro.capabilities == [.text, .tools, .reasoning, .promptCaching]) // text-only input per the API529 #expect(flash.pricing == Pricing(inputPerMTok: 0.30, outputPerMTok: 1.20, cachedInputPerMTok: 0.006, asOf: "2026-11-22", sourceURL: "https://api-docs.deepseek.com/quick_start/pricing"))530 #expect(pro.pricing?.inputPerMTok == 1.32)531 #expect(pro.pricing?.outputPerMTok == 3.96)532 #expect(flash.vendor == "deepseek")533 let curated = try #require(CuratedCatalog.info(for: ModelRef(provider: .deepSeek, modelID: "deepseek-flash")))534 #expect(curated.source == .documentation(asOf: "2026-11-22", url: "https://api-docs.deepseek.com/quick_start/pricing"))535 #expect(CuratedCatalog.info(for: ModelRef(provider: .deepSeek, modelID: "deepseek-unknown")) == nil)536 }537}538539// MARK: - Moonshot540541@Suite("Moonshot (Kimi) provider")542struct MoonshotProviderTests {543 func provider(_ transport: FixtureTransport, diagnostics: RecordingDiagnostics? = nil) -> any ChatProvider { Adapter.moonshot.make(transport, diagnostics: diagnostics) }544 static func rejection(_ message: String) -> FixtureTransport.Reply {545 .json(400, #"{"error":{"message":\#(JSONValue.string(message).serialized()),"type":"invalid_request_error"}}"#)546 }547548 @Test func requestEncoding() async {549 let transport = FixtureTransport(.sse("moonshot_text.sse"))550 _ = await collect(provider(transport).stream(fullRequest(.moonshot)))551 #expect(transport.requests[0].url?.absoluteString == "https://api.moonshot.ai/v1/chat/completions")552 let body = transport.body()553 #expect(body["model"] == "kimi-k2.6")554 #expect(body["max_completion_tokens"] == 50) // `max_tokens` is documented as deprecated555 #expect(body["max_tokens"] == nil)556 #expect(body["temperature"] == 0.4)557 #expect(body["seed"] == 7)558 #expect(body["stop"] == ["END"])559 #expect(body["thinking"] == ["type": "disabled"])560 #expect(body["reasoning_effort"] == nil)561 #expect(body["stream_options"] == nil) // usage arrives inside the finishing choice without it562 }563564 @Test func effortMappingAndPlatforms() async {565 let transport = FixtureTransport(.sse("moonshot_text.sse"))566 for effort in [ReasoningEffort?.none, .low, .medium, .high] {567 _ = await collect(provider(transport).stream(request(.moonshot, "kimi-k3", parameters: GenerationParameters(reasoning: effort))))568 }569 #expect(transport.body(0)["reasoning_effort"] == nil)570 #expect((1...3).map { transport.body($0)["reasoning_effort"]?.stringValue } == ["low", "high", "max"])571 #expect((0...3).allSatisfy { transport.body($0)["thinking"] == nil })572 // The two platforms issue separate keys; the international one is the default.573 #expect(MoonshotProvider.defaultBaseURL.absoluteString == "https://api.moonshot.ai/v1")574 let china = MoonshotProvider(transport: transport, apiKey: { "sk-cn-0123456789" }, baseURL: MoonshotProvider.chinaBaseURL)575 _ = await collect(china.stream(request(.moonshot, "kimi-k3")))576 #expect(transport.requests.last?.url?.absoluteString == "https://api.moonshot.cn/v1/chat/completions")577 }578579 @Test func fixedSamplingParametersAreDroppedOneByOne() async {580 let transport = FixtureTransport(Self.rejection("invalid temperature: only 0.6 is allowed for this model"), Self.rejection("invalid top_p: only 0.95 is allowed for this model"),581 .sse("moonshot_text.sse"))582 let diagnostics = RecordingDiagnostics()583 let c = await collect(provider(transport, diagnostics: diagnostics).stream(request(.moonshot, "kimi-k2.6", parameters: GenerationParameters(temperature: 0.3, topP: 0.5, maxOutputTokens: 32, reasoning: .off))))584 expectWellFormed(c)585 #expect(c.text == "ASTRA-OK")586 #expect(transport.requests.count == 3)587 #expect(transport.body(1)["temperature"] == nil)588 #expect(transport.body(1)["top_p"] == 0.5)589 #expect(transport.body(2)["top_p"] == nil)590 #expect(transport.body(2)["max_completion_tokens"] == 32)591 #expect(transport.body(2)["thinking"] == ["type": "disabled"])592 #expect(diagnostics.records.map(\.retryCount) == [0, 1, 2])593 }594595 @Test func thinkingIsDroppedForAModelThatCannotSwitchItOff() async {596 // The 400 `kimi-k2.7-code` returned live on 2026-11-22 to `thinking: {"type": "disabled"}`.597 let transport = FixtureTransport(Self.rejection("invalid thinking: only type=enabled is allowed for this model"), .sse("moonshot_text.sse"))598 let c = await collect(provider(transport).stream(request(.moonshot, "kimi-k2.7-code", parameters: GenerationParameters(reasoning: .off))))599 expectWellFormed(c)600 #expect(transport.body(1)["thinking"] == nil)601 // An unrelated 400 is not retried.602 let other = FixtureTransport(Self.rejection("Invalid request: messages is empty"))603 let failed = await collect(provider(other).stream(request(.moonshot, "kimi-k3", parameters: GenerationParameters(temperature: 0.3, reasoning: .off))))604 #expect(failed.error == .invalidRequest("Invalid request: messages is empty"))605 #expect(other.requests.count == 1)606 }607608 @Test func usageArrivesInsideTheFinishingChoice() async {609 let diagnostics = RecordingDiagnostics()610 let transport = FixtureTransport(.sse("moonshot_text.sse", headers: ["Content-Type": "text/event-stream", "msh-request-id": "msh-fixture"]))611 let c = await collect(provider(transport, diagnostics: diagnostics).stream(request(.moonshot, "kimi-k2.6")))612 expectWellFormed(c)613 #expect(c.text == "ASTRA-OK")614 #expect(c.starts.first?.reportedModel == "kimi-k2.6")615 #expect(c.outcome.usage == TokenUsage(inputTokens: 16, outputTokens: 8, reasoningTokens: 1))616 #expect(c.completions == [.endOfTurn])617 #expect(diagnostics.records.first?.requestID == "msh-fixture")618 }619620 @Test func thinkingThenToolCallWithFragmentedArguments() async throws {621 let c = await collect(provider(FixtureTransport(.sse("moonshot_tool.sse"))).stream(request(.moonshot, "kimi-k2.6", tools: [weatherTool])))622 expectWellFormed(c)623 #expect(c.reasoning.hasPrefix("The user wants to know the weather in Paris"))624 let call = try #require(c.outcome.toolCalls.first)625 #expect(call.name == "get_weather")626 #expect(call.arguments == ["city": "Paris"])627 #expect(c.deltas(for: call.id).count >= 3)628 #expect(c.completions == [.toolCalls])629 // Usage is reported twice in this capture (finishing choice, then the include_usage chunk): the totals are not doubled.630 #expect(c.outcome.usage == TokenUsage(inputTokens: 80, outputTokens: 91, reasoningTokens: 74))631 }632633 @Test func reasoningContent() async {634 let c = await collect(provider(FixtureTransport(.sse("moonshot_reasoning.sse"))).stream(request(.moonshot, "kimi-k3", parameters: GenerationParameters(reasoning: .low))))635 expectWellFormed(c)636 #expect(c.text == "23 chickens and 12 rabbits.")637 #expect(c.reasoning.contains("r=12"))638 #expect(c.outcome.usage?.reasoningTokens == 44)639 #expect(c.outcome.usage?.cacheWriteTokens == 0)640 }641642 @Test func errorShapes() async {643 var c = await collect(provider(FixtureTransport(.json(401, #"{"error":{"message":"Invalid Authentication","type":"invalid_authentication_error"}}"#))).stream(request(.moonshot, "kimi-k3")))644 #expect(c.error == .unauthorized("Invalid Authentication"))645 c = await collect(provider(FixtureTransport(.json(404, #"{"error":{"message":"Not found the model nonexistent-model-zzz or Permission denied","type":"resource_not_found_error"}}"#))).stream(request(.moonshot, "nonexistent-model-zzz")))646 #expect(c.error == .modelNotFound("nonexistent-model-zzz"))647 }648649 @Test func modelList() async throws {650 let transport = FixtureTransport(.file(200, "moonshot_models.json"))651 let models = try await provider(transport).listModels()652 #expect(transport.requests[0].url?.absoluteString == "https://api.moonshot.ai/v1/models")653 #expect(models.map(\.ref.modelID) == ["kimi-k3.1-pro", "kimi-k3.1-pro-highspeed", "kimi-k2.7-code", "kimi-k2.7-code-highspeed", "kimi-k2.6", "kimi-k3"])654 let k3 = try #require(models.last)655 #expect(k3.contextLength == 1_048_576)656 #expect(k3.capabilities == [.text, .vision, .reasoning, .tools]) // tools: exercised live on every listed id, see CuratedCatalog657 #expect(models.allSatisfy { $0.capabilities.contains(.tools) })658 #expect(CuratedCatalog.info(for: ModelRef(provider: .moonshot, modelID: "kimi-k3"))?.source == .documentation(asOf: "2026-11-22", url: "https://platform.kimi.ai/docs/api/chat"))659 #expect(k3.vendor == "moonshot")660 #expect(k3.pricing == nil) // the pricing page showed no figures on 2026-11-22661 #expect(models.first { $0.ref.modelID == "kimi-k2.6" }?.contextLength == 262_144)662 }663}664665// MARK: - Cerebras666667@Suite("Cerebras provider")668struct CerebrasProviderTests {669 func provider(_ transport: FixtureTransport) -> any ChatProvider { Adapter.cerebras.make(transport) }670671 @Test func requestEncoding() async {672 let transport = FixtureTransport(.sse("cerebras_text.sse"))673 _ = await collect(provider(transport).stream(fullRequest(.cerebras)))674 #expect(transport.requests[0].url?.absoluteString == "https://api.cerebras.ai/v1/chat/completions")675 let body = transport.body()676 #expect(body["model"] == "qwen-3.8-27b")677 #expect(body["max_completion_tokens"] == 50)678 #expect(body["max_tokens"] == nil)679 #expect(body["temperature"] == 0.4)680 #expect(body["top_p"] == 0.8)681 #expect(body["seed"] == 7)682 #expect(body["stop"] == ["END"])683 #expect(body["reasoning_effort"] == "none")684 #expect(body["reasoning_format"] == nil) // the default ("parsed") keeps reasoning in its own field685 #expect(body["stream_options"] == nil)686 }687688 @Test func text() async {689 let diagnostics = RecordingDiagnostics()690 let transport = FixtureTransport(.sse("cerebras_text.sse", headers: ["Content-Type": "text/event-stream", "x-request-id": "cb-fixture"]))691 let c = await collect(Adapter.cerebras.make(transport, diagnostics: diagnostics).stream(request(.cerebras, "qwen-3.8-27b")))692 expectWellFormed(c)693 #expect(c.text == "ASTRA-OK")694 #expect(c.starts.first?.reportedModel == "qwen-3.8-27b")695 #expect(c.outcome.usage == TokenUsage(inputTokens: 20, outputTokens: 5, cachedInputTokens: 0, reasoningTokens: 0))696 #expect(c.completions == [.endOfTurn])697 #expect(diagnostics.records.first?.requestID == "cb-fixture")698 }699700 @Test func twoParallelToolCalls() async {701 let c = await collect(provider(FixtureTransport(.sse("cerebras_tool.sse"))).stream(request(.cerebras, "qwen-3.8-27b", tools: [weatherTool])))702 expectWellFormed(c)703 #expect(c.outcome.toolCalls == [ToolCall(id: "9af6582c3", name: "get_weather", arguments: ["city": "Paris"]),704 ToolCall(id: "eae2065b7", name: "get_weather", arguments: ["city": "Tokyo"])])705 #expect(c.toolStarts == ["9af6582c3", "eae2065b7"])706 #expect(c.completions == [.toolCalls])707 }708709 @Test func toolCallWithFragmentedArguments() async {710 // The shape gpt-oss-120b streamed live on 2026-11-22: name and id first with empty arguments, then the arguments without an id.711 let reply = sse([#"{"id":"r1","choices":[{"delta":{"role":"assistant"},"index":0}],"model":"gpt-oss-120b"}"#,712 #"{"id":"r1","choices":[{"delta":{"reasoning":"Need to call get_weather."},"index":0}],"model":"gpt-oss-120b"}"#,713 #"{"id":"r1","choices":[{"delta":{"tool_calls":[{"function":{"name":"get_weather","arguments":""},"type":"function","id":"c18448516","index":0}]},"index":0}],"model":"gpt-oss-120b"}"#,714 #"{"id":"r1","choices":[{"delta":{"tool_calls":[{"function":{"arguments":"{\"city\":"},"type":"function","index":0}]},"index":0}],"model":"gpt-oss-120b"}"#,715 #"{"id":"r1","choices":[{"delta":{"tool_calls":[{"function":{"arguments":"\"Paris\"}"},"type":"function","index":0}]},"index":0}],"model":"gpt-oss-120b"}"#,716 #"{"id":"r1","choices":[{"delta":{},"finish_reason":"tool_calls","index":0}],"model":"gpt-oss-120b","usage":{"total_tokens":191,"completion_tokens":48,"completion_tokens_details":{"reasoning_tokens":24},"prompt_tokens":143},"time_info":{"queue_time":0.005}}"#, "[DONE]"])717 let c = await collect(provider(FixtureTransport(reply)).stream(request(.cerebras, "gpt-oss-120b", tools: [weatherTool])))718 expectWellFormed(c)719 #expect(c.reasoning == "Need to call get_weather.")720 #expect(c.outcome.toolCalls == [ToolCall(id: "c18448516", name: "get_weather", arguments: ["city": "Paris"],721 providerState: ["format": "cerebras.reasoning", "payload": "Need to call get_weather."])])722 #expect(c.deltas(for: "c18448516") == [#"{"city":"#, #""Paris"}"#])723 #expect(c.outcome.usage?.reasoningTokens == 24)724 }725726 @Test func reasoningField() async {727 let c = await collect(provider(FixtureTransport(.sse("cerebras_reasoning.sse"))).stream(request(.cerebras, "gpt-oss-120b", parameters: GenerationParameters(reasoning: .low))))728 expectWellFormed(c)729 #expect(c.text == "ASTRA-OK")730 #expect(c.reasoning == #"We need to output exactly "ASTRA-OK"."#)731 #expect(c.outcome.usage?.reasoningTokens == 11)732 #expect(c.outcome.usage?.outputTokens == 25)733 }734735 @Test func effortTheModelRefusesIsReplaced() async {736 let rejection = FixtureTransport.Reply.json(400, #"{"message":"Failed to apply chat template to messages due to error: Unsupported reasoning effort: none. Supported values are 'low', 'medium', and 'high'.","type":"invalid_request_error","param":"messages","code":"wrong_api_format","id":""}"#)737 let transport = FixtureTransport(rejection, .sse("cerebras_reasoning.sse"))738 let c = await collect(provider(transport).stream(request(.cerebras, "gpt-oss-120b", parameters: GenerationParameters(maxOutputTokens: 32, reasoning: .off))))739 expectWellFormed(c)740 #expect(transport.body(0)["reasoning_effort"] == "none")741 #expect(transport.body(1)["reasoning_effort"] == "low")742 #expect(transport.body(1)["max_completion_tokens"] == 32)743 }744745 @Test func flatErrorBodies() async {746 var c = await collect(provider(FixtureTransport(.json(401, #"{"message":"Wrong API Key","type":"invalid_request_error","param":"api_key","code":"wrong_api_key"}"#))).stream(request(.cerebras, "qwen-3.8-27b")))747 #expect(c.error == .unauthorized("Wrong API Key"))748 c = await collect(provider(FixtureTransport(.json(404, #"{"message":"Model does not exist or you do not have access to it.","type":"not_found_error","param":"model","code":"model_not_found"}"#))).stream(request(.cerebras, "nonexistent-model-zzz")))749 #expect(c.error == .modelNotFound("nonexistent-model-zzz"))750 c = await collect(provider(FixtureTransport(.json(400, #"{"message":"Content type 'image_url' is not supported by selected model. Only 'text' content type can be used.","type":"invalid_request_error","param":"prompt","code":"wrong_api_format","id":""}"#))).stream(request(.cerebras, "gpt-oss-120b")))751 if case .invalidRequest = c.error {} else { Issue.record("expected invalidRequest, got \(String(describing: c.error))") }752 // An unsupported sampling parameter is dropped and the request retried.753 let transport = FixtureTransport(.json(400, #"{"message":"seed: property 'seed' is unsupported","type":"invalid_request_error","param":"validation_error","code":"wrong_api_format"}"#), .sse("cerebras_text.sse"))754 c = await collect(provider(transport).stream(request(.cerebras, "qwen-3.8-27b", parameters: GenerationParameters(seed: 3))))755 expectWellFormed(c)756 #expect(transport.body(1)["seed"] == nil)757 }758759 @Test func modelListJoinsTheKeyedListWithThePublicCatalogue() async throws {760 let transport = FixtureTransport(.file(200, "cerebras_models.json"), .file(200, "cerebras_public_models.json"))761 let models = try await provider(transport).listModels()762 #expect(transport.requests.map { $0.url?.absoluteString } == ["https://api.cerebras.ai/v1/models", "https://api.cerebras.ai/public/v1/models"])763 #expect(transport.requests[0].value(forHTTPHeaderField: "Authorization") == "Bearer \(Adapter.cerebras.key)")764 #expect(transport.requests[1].value(forHTTPHeaderField: "Authorization") == nil) // the public catalogue needs no key, so none is sent765 #expect(models.map(\.ref.modelID) == ["qwen-3.8-27b", "gpt-oss-120b"])766 let qwen = models[0], oss = models[1]767 #expect(qwen.displayName == "Qwen 3.8 27B")768 #expect(qwen.capabilities == [.text, .tools, .vision, .reasoning, .structuredOutput])769 #expect(qwen.contextLength == 65_536)770 #expect(qwen.maxOutputTokens == 32_768)771 #expect(qwen.vendor == "Qwen") // the publisher, from the upstream Hugging Face id772 #expect(qwen.pricing?.inputPerMTok == 0.99)773 #expect(qwen.pricing?.outputPerMTok == 1.49)774 #expect(qwen.createdAt == nil)775 #expect(oss.vendor == "openai")776 #expect(oss.capabilities == [.text, .tools, .reasoning, .structuredOutput])777 #expect(oss.pricing?.inputPerMTok == 0.35)778 #expect(oss.pricing?.outputPerMTok == 0.75)779 #expect(oss.pricing?.sourceURL == "https://api.cerebras.ai/public/v1/models")780 #expect(oss.supportedParameters?.contains("temperature") == true)781 #expect(oss.supportedParameters?.contains("logprobs") == false)782 #expect(oss.createdAt == Date(timeIntervalSince1970: 1_754_438_400))783 }784785 @Test func modelListSurvivesWithoutThePublicCatalogue() async throws {786 let transport = FixtureTransport(.file(200, "cerebras_models.json"), .json(503, "{}"))787 let models = try await provider(transport).listModels()788 #expect(models.map(\.ref.modelID) == ["qwen-3.8-27b", "gpt-oss-120b"])789 #expect(models.allSatisfy { $0.capabilities == [.text] && $0.pricing == nil && $0.contextLength == nil })790 #expect(models[0].vendor == "Cerebras") // nothing better than `owned_by` without the catalogue791 }792}793794// MARK: - DeepInfra795796@Suite("DeepInfra provider")797struct DeepInfraProviderTests {798 func provider(_ transport: FixtureTransport, key: String?? = .none) -> any ChatProvider { Adapter.deepInfra.make(transport, key: key) }799800 @Test func requestEncoding() async {801 let transport = FixtureTransport(.sse("deepinfra_text.sse"))802 _ = await collect(provider(transport).stream(fullRequest(.deepInfra)))803 #expect(transport.requests[0].url?.absoluteString == "https://api.deepinfra.com/v1/openai/chat/completions")804 let body = transport.body()805 #expect(body["model"] == "meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo")806 #expect(body["max_tokens"] == 50)807 #expect(body["temperature"] == 0.4)808 #expect(body["top_p"] == 0.8)809 #expect(body["seed"] == 7)810 #expect(body["stop"] == ["END"])811 #expect(body["reasoning_effort"] == "none") // documented: "none" disables reasoning, and the field has no effect on other models812 #expect(body["stream_options"] == ["include_usage": true])813 }814815 @Test func textFromTheDocumentedShape() async {816 let c = await collect(provider(FixtureTransport(.sse("deepinfra_text.sse"))).stream(Adapter.deepInfra.request))817 expectWellFormed(c)818 #expect(c.text == "ASTRA-OK")819 #expect(c.starts.first?.reportedModel == "meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo")820 #expect(c.outcome.usage == TokenUsage(inputTokens: 21, outputTokens: 5))821 #expect(c.completions == [.endOfTurn])822 }823824 @Test func toolCallWithFragmentedArguments() async {825 let c = await collect(provider(FixtureTransport(.sse("deepinfra_tool.sse"))).stream(request(.deepInfra, Adapter.deepInfra.model, tools: [weatherTool])))826 expectWellFormed(c)827 #expect(c.outcome.toolCalls == [ToolCall(id: "call_fixture_1", name: "get_weather", arguments: ["city": "Paris"])])828 #expect(c.deltas(for: "call_fixture_1") == [#"{"ci"#, #"ty": "Par"#, #"is"}"#])829 #expect(c.completions == [.toolCalls])830 #expect(c.outcome.usage?.outputTokens == 19)831 }832833 @Test func reasoningInADedicatedFieldOnly() async {834 var c = await collect(provider(FixtureTransport(.sse("deepinfra_reasoning.sse"))).stream(request(.deepInfra, "openai/gpt-oss-120b", parameters: GenerationParameters(reasoning: .medium))))835 expectWellFormed(c)836 #expect(c.reasoning == "c + r = 35, 2c + 4r = 94, so r = 12 and c = 23.")837 #expect(c.text == "23 chickens and 12 rabbits.")838 #expect(c.outcome.usage?.reasoningTokens == 28)839 // The other dedicated spelling (`reasoning`) is read too.840 let reply = sse([#"{"id":"r1","model":"m","choices":[{"index":0,"delta":{"role":"assistant","reasoning":"Thinking."},"finish_reason":null}]}"#,841 #"{"id":"r1","model":"m","choices":[{"index":0,"delta":{"content":"Done."},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":4}}"#, "[DONE]"])842 c = await collect(provider(FixtureTransport(reply)).stream(Adapter.deepInfra.request))843 #expect(c.reasoning == "Thinking.")844 #expect(c.text == "Done.")845 }846847 @Test func errorShapes() async {848 // Both 401 bodies were returned by the live API on 2026-11-22 (chat completions and model list, with a key DeepInfra did not issue).849 var c = await collect(provider(FixtureTransport(.json(401, #"{"error":{"message":"User is not authorized to access this resource","type":"invalid_request_error","param":null,"code":"invalid_api_key"}}"#))).stream(Adapter.deepInfra.request))850 #expect(c.error == .unauthorized("User is not authorized to access this resource"))851 await #expect(throws: AstraError.unauthorized("User is not authorized to access this resource")) {852 _ = try await provider(FixtureTransport(.json(401, #"{"detail":"User is not authorized to access this resource"}"#))).verify()853 }854 // Documented: capacity rejections are 429 with code "engine_overloaded" and are not billed.855 c = await collect(provider(FixtureTransport(.json(429, #"{"error":{"message":"Model busy, retry later","type":"engine_overloaded","param":null,"code":"engine_overloaded"}}"#, headers: ["Retry-After": "5"]))).stream(Adapter.deepInfra.request))856 #expect(c.error == .rateLimited(retryAfter: 5, message: "Model busy, retry later"))857 #expect(c.error?.isTransient == true)858 // Documented: 422 with a validation list.859 c = await collect(provider(FixtureTransport(.json(422, #"{"detail":[{"loc":["body","top_k"],"msg":"Input should be less than 1000","type":"less_than"}]}"#))).stream(Adapter.deepInfra.request))860 #expect(c.error == .invalidRequest("top_k: Input should be less than 1000"))861 c = await collect(provider(FixtureTransport(.json(402, #"{"error":{"message":"Insufficient balance","type":"invalid_request_error","param":null,"code":"insufficient_balance"}}"#))).stream(Adapter.deepInfra.request))862 #expect(c.error == .quotaExceeded("Insufficient balance"))863 }864865 @Test func modelListIsPublicAndNamesThePublisher() async throws {866 // `deepinfra_models.json` is an excerpt of the real public list (2026-11-22, read without a key).867 var transport = FixtureTransport(.file(200, "deepinfra_models.json"))868 let models = try await provider(transport, key: .some(nil)).listModels()869 #expect(transport.requests[0].url?.absoluteString == "https://api.deepinfra.com/v1/openai/models")870 #expect(transport.requests[0].value(forHTTPHeaderField: "Authorization") == nil)871 // Image, embedding and speech models are not chat models.872 #expect(Set(models.map(\.ref.modelID)) == ["meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo", "openai/gpt-oss-120b", "google/gemma-3-4b-it", "deepseek-ai/DeepSeek-V4-Flash",873 "ByteDance/Seed-2.0-pro", "Qwen/Qwen3-235B-A22B-Instruct-2507"])874 let llama = try #require(models.first { $0.ref.modelID == "meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo" })875 #expect(llama.vendor == "meta-llama")876 #expect(llama.displayName == "Meta-Llama-3.1-8B-Instruct-Turbo")877 #expect(llama.capabilities == [.text]) // tool calling is not reported by the list, so it is not claimed878 #expect(llama.contextLength == 131_072)879 #expect(llama.maxOutputTokens == 131_072)880 #expect(llama.pricing?.inputPerMTok == 0.02)881 #expect(llama.pricing?.outputPerMTok == 0.04)882 #expect(llama.pricing?.cachedInputPerMTok == nil)883 #expect(llama.pricing?.sourceURL == "https://api.deepinfra.com/v1/openai/models")884 let seed = try #require(models.first { $0.ref.modelID == "ByteDance/Seed-2.0-pro" })885 #expect(seed.vendor == "ByteDance")886 #expect(seed.capabilities == [.text, .vision, .reasoning, .promptCaching])887 #expect(seed.pricing?.outputPerMTok == 3) // 2.9999999999999996 in the list888 #expect(seed.pricing?.cachedInputPerMTok == 0.1)889 #expect(models.first { $0.ref.modelID == "openai/gpt-oss-120b" }?.vendor == "openai")890 #expect(models.first { $0.ref.modelID == "google/gemma-3-4b-it" }?.capabilities == [.text, .vision])891 #expect(models.first { $0.ref.modelID == "Qwen/Qwen3-235B-A22B-Instruct-2507" }?.capabilities == [.text, .reasoning])892 // With a key stored, it is sent, so a bad key is reported.893 transport = FixtureTransport(.file(200, "deepinfra_models.json"))894 let status = try await provider(transport).verify()895 #expect(status.modelCount == 6)896 #expect(transport.requests[0].value(forHTTPHeaderField: "Authorization") == "Bearer \(Adapter.deepInfra.key)")897 // Verifying needs a key even though listing does not.898 await #expect(throws: AstraError.missingCredential(.deepInfra)) { _ = try await provider(FixtureTransport(.file(200, "deepinfra_models.json")), key: .some(nil)).verify() }899 }900}901