SPB Git

Repository Public

Support.swift 9.8 KB 203 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Docs9// File             : Packages/ORIXDocsAI/Tests/DocAITests/Support.swift10// Description      : Test support for the AI infrastructure: a fake HTTP11//                    transport that answers by URL and records what it was12//                    asked (the pattern of ORIX Astra's FixtureTransport),13//                    access to Astra's recorded provider fixtures, and small14//                    helpers.15// Module           : DocAITests16// Repository       : https://git.spboucher.ai/orix-docs17// Created          : 2026-11-2218// Last Modified    : 2026-11-2219//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author           : Simon-Pierre Boucher25// Position         : Professor of Finance26// Institution      : Université du Québec en Outaouais (UQO)27// Department       : Département des sciences administratives28// Organization     : SP Boucher29//30// Website          : https://spboucher.ai31// Git              : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General          : info@spboucher.ai38// Professional     : contact@spboucher.ai39// Direct           : simon@spboucher.ai40// Research         : research@spboucher.ai41// Development      : dev@spboucher.ai42// Support          : support@spboucher.ai43// Security/Admin   : admin@spboucher.ai44// Notifications    : notifications@spboucher.ai45//46// Preferred Contact: support@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification   : Public71// Distribution     : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License          : None specified (no license file in this repository)85// Maintainer       : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import AstraCore93import Foundation94@testable import DocAI9596/// Answers requests whose URL contains a registered fragment; records every request. Replies of one route are served in order,97/// the last one repeating. `@unchecked Sendable`: all mutable state is read and written under `lock`.98final class FakeTransport: HTTPTransport, @unchecked Sendable {99    struct Reply: Sendable {100        var status = 200101        var headers: [String: String] = ["Content-Type": "application/json"]102        var body = ""103        var failure: AstraError?104        /// Keep the stream open after the body, to observe cancellation.105        var hangs = false106        static func json(_ status: Int = 200, _ body: String) -> Reply { Reply(status: status, body: body) }107        static func sse(_ body: String) -> Reply { Reply(headers: ["Content-Type": "text/event-stream"], body: body) }108        static func fail(_ error: AstraError) -> Reply { Reply(failure: error) }109    }110111    private let lock = NSLock()112    private var routes: [(fragment: String, replies: [Reply])] = []113    private var recorded: [URLRequest] = []114    private var terminated = 0115116    func on(_ fragment: String, _ replies: Reply...) {117        lock.withLock { routes.removeAll { $0.fragment == fragment }; routes.append((fragment, replies)) }118    }119    var requests: [URLRequest] { lock.withLock { recorded } }120    var cancelledStreams: Int { lock.withLock { terminated } }121    func requests(containing fragment: String) -> [URLRequest] { requests.filter { $0.url?.absoluteString.contains(fragment) == true } }122123    private func next(_ request: URLRequest) throws -> Reply {124        try lock.withLock {125            recorded.append(request)126            let url = request.url?.absoluteString ?? ""127            // The longest matching fragment wins, so "/public/v1/models" can be told from "/v1/models".128            guard let i = routes.indices.filter({ url.contains(routes[$0].fragment) }).max(by: { routes[$0].fragment.count < routes[$1].fragment.count }) else {129                throw AstraError.network("no fake route for \(url)")130            }131            let reply = routes[i].replies.count > 1 ? routes[i].replies.removeFirst() : routes[i].replies[0]132            if let failure = reply.failure { throw failure }133            return reply134        }135    }136    private func response(_ request: URLRequest, _ reply: Reply) -> HTTPURLResponse {137        HTTPURLResponse(url: request.url!, statusCode: reply.status, httpVersion: "HTTP/1.1", headerFields: reply.headers)!138    }139140    func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {141        let reply = try next(request)142        return (Data(reply.body.utf8), response(request, reply))143    }144145    func stream(_ request: URLRequest) async throws -> (HTTPURLResponse, AsyncThrowingStream<String, Error>) {146        let reply = try next(request)147        let (stream, continuation) = AsyncThrowingStream<String, Error>.makeStream()148        var lines = reply.body.components(separatedBy: "\n")149        if lines.last == "" { lines.removeLast() }150        for line in lines { continuation.yield(line) }151        if reply.hangs {152            continuation.onTermination = { [weak self] reason in153                if case .cancelled = reason { self?.lock.withLock { self?.terminated += 1 } }154            }155        } else { continuation.finish() }156        return (response(request, reply), stream)157    }158}159160/// ORIX Astra's recorded provider responses, read from the vendored test folder (they are that test target's resources).161enum AstraFixtures {162    static let directory = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()163        .appendingPathComponent("Vendor/Tests/AstraProvidersTests/Fixtures", isDirectory: true)164    static func text(_ name: String) -> String {165        guard let text = try? String(contentsOf: directory.appendingPathComponent(name), encoding: .utf8) else { fatalError("missing Astra fixture \(name)") }166        return text167    }168}169170/// A folder removed when the object goes away. `@unchecked Sendable`: immutable after init.171final class TempFolder: @unchecked Sendable {172    let url: URL173    init() {174        url = FileManager.default.temporaryDirectory.appendingPathComponent("orixdocs-ai-tests-" + UUID().uuidString, isDirectory: true)175        try? FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)176    }177    deinit { try? FileManager.default.removeItem(at: url) }178}179180let fakeKey = "csk-FAKEKEY0123456789abcdefghijklmnop"181let weatherTool = ToolDefinition(name: "get_weather", summary: "Get the current weather for a city.",182                                 parameters: ["type": "object", "properties": ["city": ["type": "string"]], "required": ["city"], "additionalProperties": false])183184/// A transport that knows Cerebras (models with prices, text stream) and Mistral (models, text stream), from Astra's fixtures.185func standardTransport() -> FakeTransport {186    let t = FakeTransport()187    t.on("api.cerebras.ai/v1/models", .json(200, AstraFixtures.text("cerebras_models.json")))188    t.on("api.cerebras.ai/public/v1/models", .json(200, AstraFixtures.text("cerebras_public_models.json")))189    t.on("api.cerebras.ai/v1/chat/completions", .sse(AstraFixtures.text("cerebras_text.sse")))190    t.on("api.mistral.ai/v1/models", .json(200, AstraFixtures.text("mistral_models.json")))191    t.on("api.mistral.ai/v1/chat/completions", .sse(AstraFixtures.text("mistral_text.sse")))192    return t193}194195func makeHub(_ transport: FakeTransport = standardTransport(), credentials: any CredentialStore = InMemoryCredentialStore(), storage: URL? = nil,196             now: @escaping @Sendable () -> Date = { Date(timeIntervalSince1970: 1_795_000_000) }) -> ProviderHub {197    ProviderHub(configuration: .init(credentials: credentials, transport: transport, storageDirectory: storage, now: now, maxRetries: 0))198}199200func cerebrasRequest(_ text: String = "Reply with exactly: ASTRA-OK", tools: [ToolDefinition] = []) -> GenerationRequest {201    GenerationRequest(model: ModelRef(provider: .cerebras, modelID: "qwen-3.8-27b"), messages: [.user(text)], tools: tools)202}203
Files main
Menu

Theme