ChatCompletionsTestUtilities.swift 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. //===----------------------------------------------------------------------===//
  2. //
  3. // This source file is part of the Foundation Models open source project.
  4. //
  5. // Copyright © 2024-2027 Apple Inc. and the Foundation Models project authors.
  6. //
  7. // Licensed under the Apache License v2.0
  8. //
  9. // See LICENSE.txt for license information
  10. //
  11. //===----------------------------------------------------------------------===//
  12. import Foundation
  13. #if canImport(FoundationNetworking)
  14. import FoundationNetworking
  15. #endif
  16. import FoundationModels
  17. @testable import FoundationModelsUtilities
  18. import Testing
  19. func makeMockModel(
  20. name: String = "test-model",
  21. headers: [String: String] = [:],
  22. supportsGuidedGeneration: Bool = true
  23. ) -> ChatCompletionsLanguageModel {
  24. let config = URLSessionConfiguration.ephemeral
  25. config.protocolClasses = [MockSSEProtocol.self]
  26. var model = ChatCompletionsLanguageModel(
  27. name: name,
  28. url: URL(string: "https://mock-llm.test/v1")!,
  29. additionalHeaders: headers,
  30. supportsGuidedGeneration: supportsGuidedGeneration
  31. )
  32. model.urlSession = URLSession(configuration: config)
  33. return model
  34. }
  35. func capturedRequest() throws -> URLRequest {
  36. try #require(MockSSEProtocol.lastRequest)
  37. }
  38. func requestBody() throws -> [String: Any] {
  39. let request = try capturedRequest()
  40. let body = try #require(request.httpBody)
  41. return try JSONSerialization.jsonObject(with: body) as! [String: Any]
  42. }
  43. extension Transcript {
  44. var responseText: String {
  45. compactMap(\.response)
  46. .flatMap(\.segments)
  47. .compactMap { segment -> String? in
  48. if case .text(let text) = segment { return text.content }
  49. return nil
  50. }
  51. .joined()
  52. }
  53. }