From 81463873f62ba7f45fbc591e2f538809f70211e5 Mon Sep 17 00:00:00 2001 From: Oliver Drobnik Date: Fri, 30 Oct 2026 08:01:52 +0100 Subject: [PATCH 1/3] Add an Images API client and an imagegen CLI Generate, edit (multipart) and batch via the OpenAI Images API with open model names (gpt-image-2.5-sunburst/flare, gpt-image-2), size validation, the model/quality/transparency rules, usage, typed errors with x-request-id, and a header reader for pixel size and alpha. The imagegen executable mirrors Codex's image_gen.py. Co-Authored-By: Claude Sonnet 5.5 --- .swiftlint.yml | 1 + Examples/ImageGen/Commands.swift | 226 ++++++++ Examples/ImageGen/ImageGen.swift | 31 + Examples/ImageGen/Options.swift | 145 +++++ Examples/ImageGen/Output.swift | 119 ++++ Package.swift | 14 + .../Images API/ImageBatch.swift | 125 ++++ .../Images API/ImageInfo.swift | 117 ++++ .../Images API/ImageModel.swift | 128 +++++ .../Images API/ImageRequest.swift | 189 ++++++ .../Images API/ImageResult.swift | 78 +++ .../Images API/ImageSize.swift | 125 ++++ .../Images API/OpenAI+Images.swift | 81 +++ .../Model/ImageGenerationError.swift | 39 ++ .../Image Generation/OpenAI+ImageGen.swift | 5 + .../Extensions/MultipartFormData.swift | 64 +++ .../OpenAI/Images/ImagesAPITests.swift | 544 ++++++++++++++++++ .../OpenAI/Images/ImagesLiveTests.swift | 40 ++ readme.md | 2 + 19 files changed, 2073 insertions(+) create mode 100644 Examples/ImageGen/Commands.swift create mode 100644 Examples/ImageGen/ImageGen.swift create mode 100644 Examples/ImageGen/Options.swift create mode 100644 Examples/ImageGen/Output.swift create mode 100644 Sources/Providers/API/OpenAI/Image Generation/Images API/ImageBatch.swift create mode 100644 Sources/Providers/API/OpenAI/Image Generation/Images API/ImageInfo.swift create mode 100644 Sources/Providers/API/OpenAI/Image Generation/Images API/ImageModel.swift create mode 100644 Sources/Providers/API/OpenAI/Image Generation/Images API/ImageRequest.swift create mode 100644 Sources/Providers/API/OpenAI/Image Generation/Images API/ImageResult.swift create mode 100644 Sources/Providers/API/OpenAI/Image Generation/Images API/ImageSize.swift create mode 100644 Sources/Providers/API/OpenAI/Image Generation/Images API/OpenAI+Images.swift create mode 100644 Sources/Providers/Extensions/MultipartFormData.swift create mode 100644 Tests/ProvidersTests/OpenAI/Images/ImagesAPITests.swift create mode 100644 Tests/ProvidersTests/OpenAI/Images/ImagesLiveTests.swift diff --git a/.swiftlint.yml b/.swiftlint.yml index 3e12dc9..0925012 100644 --- a/.swiftlint.yml +++ b/.swiftlint.yml @@ -4,6 +4,7 @@ included: # Coder moved from Sources/Coder to Examples/Coder but is still a SPM # product — keep it under the same lint rules as the package sources. - Examples/Coder + - Examples/ImageGen excluded: # Test fixtures (JSON / PNG / text payloads bundled as test resources). diff --git a/Examples/ImageGen/Commands.swift b/Examples/ImageGen/Commands.swift new file mode 100644 index 0000000..acb314b --- /dev/null +++ b/Examples/ImageGen/Commands.swift @@ -0,0 +1,226 @@ +import ArgumentParser +import Foundation +import Providers + +/// The dry-run listing of one request. +private struct DryRun: Encodable { + var endpoint: String + var request: ImageRequest + var images: [String]? + var mask: String? + var outputs: [String] +} + +private func makeClient(_ run: RunOptions) throws -> OpenAI { + OpenAI(credential: Credential.bearer(try Credentials.apiKey(file: run.apiKeyFile))) +} + +private func printDryRun(_ dryRun: DryRun, json: Bool) throws { + if json { + try Output.printJSON(dryRun) + return + } + print(dryRun.endpoint) + if let images = dryRun.images { print("images: \(images.joined(separator: ", "))") } + if let mask = dryRun.mask { print("mask: \(mask)") } + print(String(data: try dryRun.request.jsonData(), encoding: .utf8) ?? "") + for path in dryRun.outputs { print("would write \(path)") } +} + +private func finish(_ result: ImageResult, paths: [String], json: Bool) throws { + let report = Output.report(result, files: try Output.write(result, to: paths)) + if json { try Output.printJSON(report) } else { Output.printSummary(report) } +} + +struct Generate: AsyncParsableCommand { + static let configuration = CommandConfiguration(abstract: "Generate images from a prompt.") + + @OptionGroup var prompt: PromptOptions + @OptionGroup var options: RequestOptions + @OptionGroup var run: RunOptions + + func run() async throws { + let request = try options.apply(to: ImageRequest(prompt: prompt.resolve(required: true))) + let notes = try request.validate() + let paths = Output.paths(base: run.out, n: request.n, format: request.outputFormat) + try Output.checkWritable(paths, force: run.force) + + if run.dryRun { + let plan = DryRun(endpoint: "POST /v1/images/generations", request: request, outputs: paths) + try printDryRun(plan, json: run.json) + return + } + var result = try await makeClient(run).generateImages(request) + result.notes = notes + try finish(result, paths: paths, json: run.json) + } +} + +struct Edit: AsyncParsableCommand { + static let configuration = CommandConfiguration( + abstract: "Edit images, or combine reference images, with a prompt." + ) + + @Option(name: .customLong("image"), help: "A reference image; repeat for several.") + var images: [String] = [] + + @Option(help: "A mask for the first image (prompt-guided).") + var mask: String? + + @OptionGroup var prompt: PromptOptions + @OptionGroup var options: RequestOptions + @OptionGroup var run: RunOptions + + func run() async throws { + guard !images.isEmpty else { throw ValidationError("Give at least one --image.") } + let request = try options.apply(to: ImageRequest(prompt: prompt.resolve(required: true))) + let notes = try request.validate() + let paths = Output.paths(base: run.out, n: request.n, format: request.outputFormat) + try Output.checkWritable(paths, force: run.force) + + if run.dryRun { + try printDryRun( + DryRun(endpoint: "POST /v1/images/edits", request: request, images: images, mask: mask, outputs: paths), + json: run.json + ) + return + } + let edit = try ImageEditRequest( + request: request, + images: images.map(Self.load), + mask: mask.map(Self.load) + ) + var result = try await makeClient(run).editImages(edit) + result.notes = notes + try finish(result, paths: paths, json: run.json) + } + + private static func load(_ path: String) throws -> ImageInput { + guard let data = FileManager.default.contents(atPath: path) else { + throw ValidationError("Cannot read image \(path).") + } + return ImageInput(data: data, filename: (path as NSString).lastPathComponent) + } +} + +/// The `--json` result of a batch. +private struct BatchReport: Encodable { + struct Job: Encodable { + var index: Int + var status: String + var report: RunReport? + var error: String? + } + + var jobs: [Job] +} + +struct GenerateBatch: AsyncParsableCommand { + static let configuration = CommandConfiguration( + commandName: "generate-batch", + abstract: "Run many generate jobs from a JSONL file.", + discussion: """ + Each line is a generate job: {"prompt": "…", "model": "…", "size": "…", "quality": "…", \ + "background": "…", "output_format": "…", "output_compression": 80, "moderation": "…", \ + "n": 1, "out": "path.png"}. Fields a line omits come from the command-line defaults. + """ + ) + + @Option(help: "The JSONL file of jobs.") + var jobs: String + + @Option(help: "How many jobs run at once.") + var concurrency = 4 + + @Option(name: .customLong("out-dir"), help: "Directory for jobs without an `out` (job-001.png, …).") + var outDir = Output.defaultDirectory + + @OptionGroup var prompt: PromptOptions + @OptionGroup var options: RequestOptions + @OptionGroup var run: RunOptions + + func run() async throws { + guard concurrency >= 1 else { throw ValidationError("--concurrency must be at least 1.") } + guard let text = try? String(contentsOfFile: jobs, encoding: .utf8) else { + throw ValidationError("Cannot read --jobs \(jobs).") + } + let defaults = try options.apply(to: ImageRequest(prompt: prompt.resolve(required: false))) + let parsed = try ImageBatchJob.parse(jsonl: text, defaults: defaults) + guard !parsed.isEmpty else { throw ValidationError("\(jobs) holds no jobs.") } + + var claimed = Set() + let plans: [Result<[String], any Error>] = parsed.enumerated().map { index, job in + let paths = Output.paths( + base: job.out, + directory: outDir, + stem: String(format: "job-%03d", index + 1), + n: job.request.n, + format: job.request.outputFormat + ) + return Result { + try Output.checkWritable(paths, force: run.force) + if let duplicate = paths.first(where: { !claimed.insert($0).inserted }) { + throw OutputError.exists("\(duplicate) (another job in this batch writes it)") + } + return paths + } + } + + if run.dryRun { + for (index, job) in parsed.enumerated() { + print("job \(index + 1):") + switch plans[index] { + case let .success(paths): + let plan = DryRun( + endpoint: "POST /v1/images/generations", + request: job.request, + outputs: paths + ) + try printDryRun(plan, json: false) + case let .failure(error): + print(" would fail: \(error.localizedDescription)") + } + } + return + } + + let client = try makeClient(run) + let reports = ReportBox() + let results = await client.generateImageBatch(parsed, concurrency: concurrency) { index, job in + let paths = try plans[index].get() + let result = try await client.generateImages(job.request) + await reports.set(index, Output.report(result, files: try Output.write(result, to: paths))) + return result + } + + var entries: [BatchReport.Job] = [] + for result in results { + switch result.outcome { + case .success: + let report = await reports.get(result.index) + entries.append(.init(index: result.index + 1, status: "ok", report: report, error: nil)) + if !run.json, let report { + print("job \(result.index + 1): ok") + Output.printSummary(report) + } + case let .failure(error): + entries.append(.init( + index: result.index + 1, status: "error", report: nil, error: error.localizedDescription + )) + if !run.json { print("job \(result.index + 1): failed: \(error.localizedDescription)") } + } + } + if run.json { try Output.printJSON(BatchReport(jobs: entries)) } + let failed = entries.filter { $0.status == "error" }.count + if failed > 0 { + FileHandle.standardError.write(Data("\(failed) of \(entries.count) jobs failed.\n".utf8)) + throw ExitCode.failure + } + } +} + +private actor ReportBox { + private var reports: [Int: RunReport] = [:] + func set(_ index: Int, _ report: RunReport) { reports[index] = report } + func get(_ index: Int) -> RunReport? { reports[index] } +} diff --git a/Examples/ImageGen/ImageGen.swift b/Examples/ImageGen/ImageGen.swift new file mode 100644 index 0000000..e3983f7 --- /dev/null +++ b/Examples/ImageGen/ImageGen.swift @@ -0,0 +1,31 @@ +import ArgumentParser +import Foundation +import Providers + +@main +struct ImageGen: AsyncParsableCommand { + static let configuration = CommandConfiguration( + commandName: "imagegen", + abstract: "Generate and edit images with the OpenAI Images API.", + discussion: """ + Calls the public Images API, which honours every setting (model, size, quality, \ + background, format). The ChatGPT-subscription Codex backend does not. + + Models (--model): + \(ImageModel.known.map { " \($0.model) \($0.guidance)" }.joined(separator: "\n")) + Any other name is passed through unchanged. + + Size: auto or WIDTHxHEIGHT. Recommended: 1024x1024, 1536x1024, 1024x1536. Custom \ + sizes need both sides to be multiples of 16, the longest side at most 3840, an aspect \ + ratio between 1:3 and 3:1, and 655,360 to 8,294,400 total pixels. Above 2560x1440 is \ + experimental. Presets: \(SizePreset.helpList). + + Quality: low, medium, high, auto; xhigh and max only on the 2.5 models. Transparent \ + backgrounds need a 2.5 model and --output-format png or webp. + + The API key is read from OPENAI_API_KEY, otherwise from --api-key-file. --dry-run \ + needs no key. + """, + subcommands: [Generate.self, Edit.self, GenerateBatch.self] + ) +} diff --git a/Examples/ImageGen/Options.swift b/Examples/ImageGen/Options.swift new file mode 100644 index 0000000..9733071 --- /dev/null +++ b/Examples/ImageGen/Options.swift @@ -0,0 +1,145 @@ +import ArgumentParser +import Foundation +import Providers + +/// The request settings shared by every subcommand. +struct RequestOptions: ParsableArguments { + @Option(help: "Model: gpt-image-2.5-sunburst (default), gpt-image-2.5-flare, gpt-image-2, or any model name.") + var model: String? + + @Option(help: "auto or WIDTHxHEIGHT, e.g. 2048x1152 (presets: \(SizePreset.helpList)).") + var size: String? + + @Option(help: "low, medium, high, auto; xhigh and max on the 2.5 models only.") + var quality: String? + + @Option(help: "auto, opaque or transparent (transparent: 2.5 models, png or webp).") + var background: String? + + @Option(name: .customLong("output-format"), help: "png (default), jpeg or webp.") + var outputFormat: String? + + @Option(name: .customLong("output-compression"), help: "0-100; jpeg and webp only.") + var outputCompression: Int? + + @Option(help: "auto or low.") + var moderation: String? + + @Option(help: "Number of images per request.") + var n: Int? + + /// A request carrying only the options that were given, on top of `base`. + func apply(to base: ImageRequest) throws -> ImageRequest { + var request = base + if let model { request.model = ImageModel(model) } + if let size { request.size = try SizePreset.resolve(size) } + if let quality { request.quality = ImageQuality(quality) } + if let background { + request.background = try Self.parse(background, as: ImageBackground.self, option: "--background") + } + if let outputFormat { + request.outputFormat = try Self.parse(outputFormat, as: ImageOutputFormat.self, option: "--output-format") + } + if let outputCompression { request.outputCompression = outputCompression } + if let moderation { + request.moderation = try Self.parse(moderation, as: ImageModeration.self, option: "--moderation") + } + if let n { request.n = n } + return request + } + + private static func parse( + _ text: String, + as _: Value.Type, + option: String + ) throws -> Value where Value.RawValue == String { + guard let value = Value(rawValue: text) else { + let allowed = Value.allCases.map(\.rawValue).joined(separator: ", ") + throw ValidationError("\(option) must be one of: \(allowed) (got '\(text)')") + } + return value + } +} + +/// Where the images go and how the command reports. +struct RunOptions: ParsableArguments { + @Option(help: "Output file. With --n > 1, name-1.png, name-2.png, … (default: output/imagegen/output.png).") + var out: String? + + @Flag(help: "Overwrite existing output files.") + var force = false + + @Flag( + name: .customLong("dry-run"), + help: "Print the request JSON and output paths without calling the API (no key needed)." + ) + var dryRun = false + + @Flag(help: "Print a machine-readable result: paths, sizes, resolved settings, usage.") + var json = false + + @Option(name: .customLong("api-key-file"), help: "File holding the API key, used when OPENAI_API_KEY is not set.") + var apiKeyFile: String? +} + +/// The prompt, from `--prompt` or `--prompt-file`. +struct PromptOptions: ParsableArguments { + @Option(help: "The prompt.") + var prompt: String? + + @Option(name: .customLong("prompt-file"), help: "Read the prompt from this file.") + var promptFile: String? + + func resolve(required: Bool) throws -> String { + if prompt != nil, promptFile != nil { + throw ValidationError("Give --prompt or --prompt-file, not both.") + } + if let prompt { return prompt } + if let promptFile { + do { + return try String(contentsOfFile: promptFile, encoding: .utf8) + .trimmingCharacters(in: .whitespacesAndNewlines) + } catch { + throw ValidationError("Cannot read --prompt-file \(promptFile): \(error.localizedDescription)") + } + } + if required { throw ValidationError("A prompt is required: --prompt or --prompt-file.") } + return "" + } +} + +/// Size presets: `1080p`, `1440p`, `4k` and their portrait forms. +enum SizePreset { + private static let presets: [String: String] = [ + // 1080 isn't a multiple of 16, so 1080p rounds up to 1088. + "1080p": "1920x1088", "1080p-portrait": "1088x1920", + "1440p": "2560x1440", "1440p-portrait": "1440x2560", + "4k": "3840x2160", "4k-portrait": "2160x3840" + ] + + static var helpList: String { "1080p, 1440p, 4k, each also -portrait" } + + static func resolve(_ text: String) throws -> ImageSize { + ImageSize(presets[text.lowercased()] ?? text) + } +} + +enum Credentials { + /// `OPENAI_API_KEY`, otherwise the contents of `--api-key-file`. + static func apiKey(file: String?) throws -> String { + if let key = ProcessInfo.processInfo.environment["OPENAI_API_KEY"], !key.isEmpty { + return key + } + guard let file else { + throw ValidationError("No API key: set OPENAI_API_KEY or pass --api-key-file.") + } + let key: String + do { + key = try String(contentsOfFile: file, encoding: .utf8).trimmingCharacters(in: .whitespacesAndNewlines) + } catch { + throw ValidationError("Cannot read --api-key-file \(file): \(error.localizedDescription)") + } + guard !key.isEmpty else { throw ValidationError("--api-key-file \(file) is empty.") } + return key + } +} diff --git a/Examples/ImageGen/Output.swift b/Examples/ImageGen/Output.swift new file mode 100644 index 0000000..c157086 --- /dev/null +++ b/Examples/ImageGen/Output.swift @@ -0,0 +1,119 @@ +import Foundation +import Providers + +/// A written image. +struct FileReport: Encodable { + var path: String + var width: Int? + var height: Int? + var bytes: Int +} + +/// The `--json` result of one request. +struct RunReport: Encodable { + var files: [FileReport] + var size: String? + var quality: String? + var background: String? + var outputFormat: String? + var usage: ImageUsage? + var notes: [String] + var requestId: String? +} + +enum Output { + static let defaultDirectory = "output/imagegen" + + /// The paths for `n` images: `name.png`, or `name-1.png`, `name-2.png`, … when `n > 1`. + static func paths( + base: String?, + directory: String = defaultDirectory, + stem: String = "output", + n: Int, + format: ImageOutputFormat? + ) -> [String] { + let fileExtension = (format ?? .png).fileExtension + var path = base ?? "\(directory)/\(stem)" + if (path as NSString).pathExtension.isEmpty { path += ".\(fileExtension)" } + guard n > 1 else { return [path] } + let nsPath = path as NSString + let ext = nsPath.pathExtension + let root = nsPath.deletingPathExtension + return (1...n).map { "\(root)-\($0).\(ext)" } + } + + /// Fails if any path exists and `force` is off. + static func checkWritable(_ paths: [String], force: Bool) throws { + guard !force else { return } + if let existing = paths.first(where: { FileManager.default.fileExists(atPath: $0) }) { + throw OutputError.exists(existing) + } + } + + /// Writes each generated image to its path, reading the real pixel size from the bytes. + static func write(_ result: ImageResult, to paths: [String]) throws -> [FileReport] { + guard result.images.count == paths.count else { + throw OutputError.countMismatch(expected: paths.count, got: result.images.count) + } + var reports: [FileReport] = [] + for (image, path) in zip(result.images, paths) { + let url = URL(fileURLWithPath: path) + try FileManager.default.createDirectory( + at: url.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + try image.data.write(to: url) + let info = ImageInfo(data: image.data) + reports.append(FileReport(path: path, width: info?.width, height: info?.height, bytes: image.data.count)) + } + return reports + } + + static func report(_ result: ImageResult, files: [FileReport]) -> RunReport { + RunReport( + files: files, + size: result.size, + quality: result.quality, + background: result.background, + outputFormat: result.outputFormat, + usage: result.usage, + notes: result.notes, + requestId: result.requestID + ) + } + + static func printJSON(_ value: some Encodable) throws { + let encoder = JSONEncoder() + encoder.keyEncodingStrategy = .convertToSnakeCase + encoder.outputFormatting = [.sortedKeys, .prettyPrinted, .withoutEscapingSlashes] + print(String(data: try encoder.encode(value), encoding: .utf8) ?? "") + } + + static func describe(_ file: FileReport) -> String { + let size = file.width.flatMap { width in file.height.map { "\(width)x\($0)" } } ?? "unknown size" + return "\(file.path) (\(size))" + } + + static func printSummary(_ report: RunReport) { + for file in report.files { print("wrote \(describe(file))") } + for note in report.notes { print("note: \(note)") } + if let usage = report.usage { + let parts = [("input", usage.inputTokens), ("output", usage.outputTokens), ("total", usage.totalTokens), + ("image input", usage.inputTokensDetails?.imageTokens)] + .compactMap { name, count in count.map { "\(name) \($0)" } } + if !parts.isEmpty { print("tokens: \(parts.joined(separator: ", "))") } + } + } +} + +enum OutputError: LocalizedError { + case exists(String) + case countMismatch(expected: Int, got: Int) + + var errorDescription: String? { + switch self { + case let .exists(path): return "\(path) already exists; pass --force to overwrite." + case let .countMismatch(expected, got): return "Expected \(expected) images but the API returned \(got)." + } + } +} diff --git a/Package.swift b/Package.swift index eee6671..7ee08f9 100644 --- a/Package.swift +++ b/Package.swift @@ -82,6 +82,12 @@ let package = Package( .executable( name: "Coder", targets: ["Coder"] + ), + // `imagegen` — command-line client for the OpenAI Images API + // (generate / edit / batch), a Swift port of Codex's image_gen.py. + .executable( + name: "imagegen", + targets: ["imagegen"] ) ], // Opt-in trait gating the SQLiteKit-backed `SQLiteVectorStore` @@ -232,6 +238,14 @@ let package = Package( ], path: "Examples/Coder" ), + .executableTarget( + name: "imagegen", + dependencies: [ + "Providers", + .product(name: "ArgumentParser", package: "swift-argument-parser") + ], + path: "Examples/ImageGen" + ), .testTarget( name: "ProvidersTests", dependencies: [ diff --git a/Sources/Providers/API/OpenAI/Image Generation/Images API/ImageBatch.swift b/Sources/Providers/API/OpenAI/Image Generation/Images API/ImageBatch.swift new file mode 100644 index 0000000..302cb7c --- /dev/null +++ b/Sources/Providers/API/OpenAI/Image Generation/Images API/ImageBatch.swift @@ -0,0 +1,125 @@ +// +// ImageBatch.swift +// +// Run many generate jobs from JSONL with bounded concurrency. +// + +import Foundation + +/// One generate job of a batch. +public struct ImageBatchJob: Sendable { + public var request: ImageRequest + /// The caller's output name for this job (opaque to the client). + public var out: String? + + public init(request: ImageRequest, out: String? = nil) { + self.request = request + self.out = out + } + + private struct Line: Decodable { + var prompt: String? + var model: ImageModel? + var size: ImageSize? + var quality: ImageQuality? + var background: ImageBackground? + var outputFormat: ImageOutputFormat? + var outputCompression: Int? + var moderation: ImageModeration? + var n: Int? + var user: String? + var out: String? + } + + /// Parses JSONL: one generate job per line, each with its own `prompt`, `model`, + /// `size`, `quality`, `background`, `output_format`, `output_compression`, + /// `moderation`, `n`, `user` and `out`. Anything a line omits comes from `defaults` + /// (whose `prompt` is used for lines without one). Blank lines and `#` comments are skipped. + public static func parse(jsonl: String, defaults: ImageRequest) throws -> [ImageBatchJob] { + let decoder = JSONDecoder() + decoder.keyDecodingStrategy = .convertFromSnakeCase + var jobs: [ImageBatchJob] = [] + for (index, rawLine) in jsonl.split(separator: "\n", omittingEmptySubsequences: false).enumerated() { + let line = rawLine.trimmingCharacters(in: .whitespacesAndNewlines) + if line.isEmpty || line.hasPrefix("#") { continue } + let number = index + 1 + let decoded: Line + do { + decoded = try decoder.decode(Line.self, from: Data(line.utf8)) + } catch { + throw ImageGenerationError.invalidParameter( + "jobs line \(number): not a valid job (\(error.localizedDescription))" + ) + } + var request = defaults + if let prompt = decoded.prompt { request.prompt = prompt } + guard !request.prompt.isEmpty else { + throw ImageGenerationError.invalidParameter("jobs line \(number): missing prompt") + } + if let model = decoded.model { request.model = model } + if let size = decoded.size { request.size = size } + if let quality = decoded.quality { request.quality = quality } + if let background = decoded.background { request.background = background } + if let format = decoded.outputFormat { request.outputFormat = format } + if let compression = decoded.outputCompression { request.outputCompression = compression } + if let moderation = decoded.moderation { request.moderation = moderation } + if let n = decoded.n { request.n = n } + if let user = decoded.user { request.user = user } + jobs.append(ImageBatchJob(request: request, out: decoded.out)) + } + return jobs + } +} + +/// The result of one batch job. +public struct ImageBatchResult: Sendable { + /// Position of the job in the input. + public var index: Int + public var job: ImageBatchJob + public var outcome: Result +} + +public extension OpenAI { + /// Runs generate jobs, at most `concurrency` at a time. A failing job does not stop + /// the others; every job gets a result, returned in input order. + func generateImageBatch(_ jobs: [ImageBatchJob], concurrency: Int = 4) async -> [ImageBatchResult] { + await generateImageBatch(jobs, concurrency: concurrency) { _, job in + try await self.generateImages(job.request) + } + } + + /// The scheduler behind ``generateImageBatch(_:concurrency:)`` with the per-job work + /// supplied by the caller, for example to write each image out as soon as it arrives. + func generateImageBatch( + _ jobs: [ImageBatchJob], + concurrency: Int, + run: @escaping @Sendable (_ index: Int, _ job: ImageBatchJob) async throws -> ImageResult + ) async -> [ImageBatchResult] { + let limit = max(1, concurrency) + return await withTaskGroup(of: ImageBatchResult.self) { group in + var results: [ImageBatchResult] = [] + var next = 0 + + func addNext() { + guard next < jobs.count else { return } + let index = next + let job = jobs[index] + next += 1 + group.addTask { + do { + return ImageBatchResult(index: index, job: job, outcome: .success(try await run(index, job))) + } catch { + return ImageBatchResult(index: index, job: job, outcome: .failure(error)) + } + } + } + + for _ in 0.. Int { + (Int(bytes[offset]) << 24) | (Int(bytes[offset + 1]) << 16) + | (Int(bytes[offset + 2]) << 8) | Int(bytes[offset + 3]) + } + + private static func be16(_ bytes: [UInt8], _ offset: Int) -> Int { + (Int(bytes[offset]) << 8) | Int(bytes[offset + 1]) + } + + private static func le16(_ bytes: [UInt8], _ offset: Int) -> Int { + Int(bytes[offset]) | (Int(bytes[offset + 1]) << 8) + } + + private static func le24(_ bytes: [UInt8], _ offset: Int) -> Int { + Int(bytes[offset]) | (Int(bytes[offset + 1]) << 8) | (Int(bytes[offset + 2]) << 16) + } + + private static func tag(_ bytes: [UInt8], _ offset: Int) -> String { + String(bytes: bytes[offset..<(offset + 4)], encoding: .ascii) ?? "" + } + + private static func png(_ bytes: [UInt8]) -> ImageInfo? { + let signature: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A] + guard bytes.count >= 33, Array(bytes[0..<8]) == signature, tag(bytes, 12) == "IHDR" else { return nil } + let width = be32(bytes, 16) + let height = be32(bytes, 20) + let colorType = bytes[25] + var hasAlpha = colorType == 4 || colorType == 6 + // A palette or grayscale image can carry transparency in a tRNS chunk. + var offset = 8 + while !hasAlpha, offset + 8 <= bytes.count { + let length = be32(bytes, offset) + let type = tag(bytes, offset + 4) + if type == "tRNS" { hasAlpha = true } + if type == "IDAT" || type == "IEND" { break } + offset += 12 + length + } + return ImageInfo(width: width, height: height, hasAlpha: hasAlpha) + } + + private static func jpeg(_ bytes: [UInt8]) -> ImageInfo? { + guard bytes.count > 4, bytes[0] == 0xFF, bytes[1] == 0xD8 else { return nil } + var offset = 2 + while offset + 4 <= bytes.count { + guard bytes[offset] == 0xFF else { return nil } + let marker = bytes[offset + 1] + if marker == 0xFF { offset += 1; continue } + if marker == 0xD8 || marker == 0x01 || (0xD0...0xD7).contains(marker) { offset += 2; continue } + let length = be16(bytes, offset + 2) + let isFrame = (0xC0...0xCF).contains(marker) && ![0xC4, 0xC8, 0xCC].contains(marker) + if isFrame { + guard offset + 9 <= bytes.count else { return nil } + return ImageInfo(width: be16(bytes, offset + 7), height: be16(bytes, offset + 5), hasAlpha: false) + } + offset += 2 + length + } + return nil + } + + private static func webp(_ bytes: [UInt8]) -> ImageInfo? { + guard bytes.count >= 30, tag(bytes, 0) == "RIFF", tag(bytes, 8) == "WEBP" else { return nil } + switch tag(bytes, 12) { + case "VP8X": + let hasAlpha = bytes[20] & 0x10 != 0 + return ImageInfo(width: le24(bytes, 24) + 1, height: le24(bytes, 27) + 1, hasAlpha: hasAlpha) + case "VP8L": + guard bytes[20] == 0x2F else { return nil } + let bits = Int(bytes[21]) | (Int(bytes[22]) << 8) | (Int(bytes[23]) << 16) | (Int(bytes[24]) << 24) + return ImageInfo( + width: (bits & 0x3FFF) + 1, + height: ((bits >> 14) & 0x3FFF) + 1, + hasAlpha: (bits >> 28) & 1 == 1 + ) + case "VP8 ": + guard bytes[23] == 0x9D, bytes[24] == 0x01, bytes[25] == 0x2A else { return nil } + return ImageInfo( + width: le16(bytes, 26) & 0x3FFF, + height: le16(bytes, 28) & 0x3FFF, + hasAlpha: false + ) + default: + return nil + } + } +} diff --git a/Sources/Providers/API/OpenAI/Image Generation/Images API/ImageModel.swift b/Sources/Providers/API/OpenAI/Image Generation/Images API/ImageModel.swift new file mode 100644 index 0000000..46bb829 --- /dev/null +++ b/Sources/Providers/API/OpenAI/Image Generation/Images API/ImageModel.swift @@ -0,0 +1,128 @@ +// +// ImageModel.swift +// +// Open model identifier for the OpenAI Images API. +// + +import Foundation + +/// An Images API model name. +/// +/// The type is an open string with named constants for the current GPT Image +/// models, so an unknown (new) model name passes through unchanged and needs no +/// library change. +public struct ImageModel: RawRepresentable, Hashable, Sendable, Codable, ExpressibleByStringLiteral, + CustomStringConvertible { + public let rawValue: String + + public init(rawValue: String) { + self.rawValue = rawValue + } + + public init(_ rawValue: String) { + self.rawValue = rawValue + } + + public init(stringLiteral value: String) { + rawValue = value + } + + public init(from decoder: Decoder) throws { + rawValue = try decoder.singleValueContainer().decode(String.self) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + try container.encode(rawValue) + } + + public var description: String { rawValue } + + /// The default: recommended where editing precision matters. + public static let sunburst = ImageModel("gpt-image-2.5-sunburst") + /// Fast, high-quality everyday generation. + public static let flare = ImageModel("gpt-image-2.5-flare") + /// The previous-generation GPT Image model (no `xhigh`/`max` quality, no transparency). + public static let gptImage2 = ImageModel("gpt-image-2") + + /// The model used when a request names none. + public static let `default` = ImageModel.sunburst + + /// The models with named constants, with the guide's one-line guidance. + public static let known: [(model: ImageModel, guidance: String)] = [ + (.sunburst, "default; recommended where editing precision matters"), + (.flare, "fast, high-quality everyday generation"), + (.gptImage2, "previous generation; no xhigh/max quality, no transparent background") + ] + + /// Whether this is one of the GPT Image 2.5 models (`xhigh`/`max` quality, transparency). + public var isGPTImage25: Bool { rawValue.hasPrefix("gpt-image-2.5") } + + /// Whether this is `gpt-image-2` (or a dated snapshot of it). + public var isGPTImage2: Bool { rawValue == "gpt-image-2" || rawValue.hasPrefix("gpt-image-2-") } +} + +/// An Images API `quality` value: an open string with the known values. +public struct ImageQuality: RawRepresentable, Hashable, Sendable, Codable, ExpressibleByStringLiteral, + CustomStringConvertible { + public let rawValue: String + + public init(rawValue: String) { + self.rawValue = rawValue + } + + public init(_ rawValue: String) { + self.rawValue = rawValue + } + + public init(stringLiteral value: String) { + rawValue = value + } + + public init(from decoder: Decoder) throws { + rawValue = try decoder.singleValueContainer().decode(String.self) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + try container.encode(rawValue) + } + + public var description: String { rawValue } + + public static let low = ImageQuality("low") + public static let medium = ImageQuality("medium") + public static let high = ImageQuality("high") + /// 2.5 models only. + public static let xhigh = ImageQuality("xhigh") + /// 2.5 models only. + public static let max = ImageQuality("max") + public static let auto = ImageQuality("auto") + + /// Every documented value. + public static let known: [ImageQuality] = [.low, .medium, .high, .xhigh, .max, .auto] + + /// Values that exist only on the GPT Image 2.5 models. + public var isExtended: Bool { self == .xhigh || self == .max } +} + +/// The `background` of a generated image. +public enum ImageBackground: String, Sendable, Codable, CaseIterable { + case auto, opaque, transparent +} + +/// The `output_format` of a generated image. +public enum ImageOutputFormat: String, Sendable, Codable, CaseIterable { + case png, jpeg, webp + + /// The usual file extension. + public var fileExtension: String { rawValue == "jpeg" ? "jpg" : rawValue } + + /// The MIME type. + public var mimeType: String { "image/\(rawValue)" } +} + +/// The `moderation` level. +public enum ImageModeration: String, Sendable, Codable, CaseIterable { + case auto, low +} diff --git a/Sources/Providers/API/OpenAI/Image Generation/Images API/ImageRequest.swift b/Sources/Providers/API/OpenAI/Image Generation/Images API/ImageRequest.swift new file mode 100644 index 0000000..810315c --- /dev/null +++ b/Sources/Providers/API/OpenAI/Image Generation/Images API/ImageRequest.swift @@ -0,0 +1,189 @@ +// +// ImageRequest.swift +// +// A text-to-image request for `/v1/images/generations`; also the shared +// fields of an edit. +// + +import Foundation + +/// The request fields shared by generate and edit. +/// +/// A `nil` field is not sent and the API default applies. +public struct ImageRequest: Sendable, Codable, Equatable { + public var prompt: String + public var model: ImageModel + public var size: ImageSize? + public var quality: ImageQuality? + public var background: ImageBackground? + public var outputFormat: ImageOutputFormat? + /// 0–100; `jpeg` and `webp` only. + public var outputCompression: Int? + public var moderation: ImageModeration? + /// The number of images (1–10). + public var n: Int + public var user: String? + + public init( + prompt: String, + model: ImageModel = .default, + size: ImageSize? = nil, + quality: ImageQuality? = nil, + background: ImageBackground? = nil, + outputFormat: ImageOutputFormat? = nil, + outputCompression: Int? = nil, + moderation: ImageModeration? = nil, + n: Int = 1, + user: String? = nil + ) { + self.prompt = prompt + self.model = model + self.size = size + self.quality = quality + self.background = background + self.outputFormat = outputFormat + self.outputCompression = outputCompression + self.moderation = moderation + self.n = n + self.user = user + } + + /// The longest prompt the GPT Image models accept. + public static let maxPromptLength = 32000 + + /// Checks the request before anything is sent. + /// + /// - Returns: Notes for the caller (for example, an experimental size). + /// - Throws: ``ImageGenerationError/invalidParameter(_:)`` naming the rule that is violated. + @discardableResult + public func validate() throws -> [String] { + guard !prompt.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + throw ImageGenerationError.invalidParameter("prompt must not be empty") + } + guard prompt.count <= Self.maxPromptLength else { + throw ImageGenerationError.invalidParameter("prompt exceeds \(Self.maxPromptLength) characters") + } + guard (1...10).contains(n) else { + throw ImageGenerationError.invalidParameter("n must be between 1 and 10 (n=\(n))") + } + + var notes: [String] = [] + if let size { + notes += try size.validate() + } + + if let quality, quality.isExtended, model.isGPTImage2 { + throw ImageGenerationError.invalidParameter( + "quality '\(quality)' is only available on the GPT Image 2.5 models " + + "(\(ImageModel.sunburst), \(ImageModel.flare)), not \(model)" + ) + } + + if background == .transparent { + if model.isGPTImage2 { + throw ImageGenerationError.invalidParameter( + "transparent backgrounds are not supported by \(model); use a GPT Image 2.5 model " + + "such as \(ImageModel.sunburst)" + ) + } + if outputFormat == .jpeg { + throw ImageGenerationError.invalidParameter( + "a transparent background needs output_format png or webp, not jpeg" + ) + } + } + + if let outputCompression { + guard (0...100).contains(outputCompression) else { + throw ImageGenerationError.invalidParameter("output_compression must be between 0 and 100") + } + guard outputFormat == .jpeg || outputFormat == .webp else { + throw ImageGenerationError.invalidParameter("output_compression applies to jpeg and webp output only") + } + } + return notes + } + + /// The JSON body for `/v1/images/generations` (snake_case, sorted keys). + public func jsonData() throws -> Data { + let encoder = JSONEncoder() + encoder.keyEncodingStrategy = .convertToSnakeCase + encoder.outputFormatting = [.sortedKeys, .prettyPrinted, .withoutEscapingSlashes] + return try encoder.encode(self) + } + + /// The text fields of the multipart edit body, in a stable order. + func formFields() -> [(name: String, value: String)] { + var fields: [(String, String)] = [("model", model.rawValue), ("prompt", prompt), ("n", String(n))] + if let size { fields.append(("size", size.rawValue)) } + if let quality { fields.append(("quality", quality.rawValue)) } + if let background { fields.append(("background", background.rawValue)) } + if let outputFormat { fields.append(("output_format", outputFormat.rawValue)) } + if let outputCompression { fields.append(("output_compression", String(outputCompression))) } + if let moderation { fields.append(("moderation", moderation.rawValue)) } + if let user { fields.append(("user", user)) } + return fields + } +} + +/// A reference image (or mask) for an edit. +public struct ImageInput: Sendable, Equatable { + public var data: Data + public var filename: String + public var mimeType: String + + public init(data: Data, filename: String, mimeType: String? = nil) { + self.data = data + self.filename = filename + self.mimeType = mimeType ?? Self.mimeType(forFilename: filename) + } + + /// `image/png`, `image/jpeg` or `image/webp` from the extension; PNG when unknown. + public static func mimeType(forFilename filename: String) -> String { + switch (filename as NSString).pathExtension.lowercased() { + case "jpg", "jpeg": return "image/jpeg" + case "webp": return "image/webp" + default: return "image/png" + } + } +} + +/// An edit request for `/v1/images/edits`. +public struct ImageEditRequest: Sendable { + public var request: ImageRequest + /// One or more reference images. + public var images: [ImageInput] + /// Applies to the first image; masking is prompt-guided. + public var mask: ImageInput? + + public init(request: ImageRequest, images: [ImageInput], mask: ImageInput? = nil) { + self.request = request + self.images = images + self.mask = mask + } + + /// Validates the shared fields and the image list. + @discardableResult + public func validate() throws -> [String] { + guard !images.isEmpty else { + throw ImageGenerationError.invalidParameter("an edit needs at least one image") + } + return try request.validate() + } + + /// The multipart body. `input_fidelity` is deliberately never sent: `gpt-image-2` + /// rejects it and the guide doesn't document it for the 2.5 models. + func multipartBody() -> MultipartFormData { + var form = MultipartFormData() + for field in request.formFields() { + form.addField(name: field.name, value: field.value) + } + for image in images { + form.addFile(name: "image[]", filename: image.filename, mimeType: image.mimeType, data: image.data) + } + if let mask { + form.addFile(name: "mask", filename: mask.filename, mimeType: mask.mimeType, data: mask.data) + } + return form + } +} diff --git a/Sources/Providers/API/OpenAI/Image Generation/Images API/ImageResult.swift b/Sources/Providers/API/OpenAI/Image Generation/Images API/ImageResult.swift new file mode 100644 index 0000000..2b86dc6 --- /dev/null +++ b/Sources/Providers/API/OpenAI/Image Generation/Images API/ImageResult.swift @@ -0,0 +1,78 @@ +// +// ImageResult.swift +// +// What `/v1/images/generations` and `/v1/images/edits` return. +// + +import Foundation + +/// Token usage of an image request. +public struct ImageUsage: Sendable, Codable, Equatable { + public struct Details: Sendable, Codable, Equatable { + public var textTokens: Int? + public var imageTokens: Int? + } + + public var inputTokens: Int? + public var outputTokens: Int? + public var totalTokens: Int? + public var inputTokensDetails: Details? + public var outputTokensDetails: Details? +} + +/// One generated image. +public struct GeneratedImage: Sendable, Equatable { + /// The decoded image bytes. + public var data: Data + public var revisedPrompt: String? +} + +/// The outcome of an image request. +public struct ImageResult: Sendable { + public var images: [GeneratedImage] + /// The resolved settings, as echoed by the API (falling back to what was requested). + public var size: String? + public var quality: String? + public var background: String? + public var outputFormat: String? + public var usage: ImageUsage? + /// Caveats for the caller, such as an experimental size. + public var notes: [String] + /// The `x-request-id` response header. + public var requestID: String? +} + +/// The wire shape of a successful response. +struct ImagesResponse: Decodable { + struct Item: Decodable { + let b64Json: String? + let revisedPrompt: String? + } + + let created: Int? + let data: [Item] + let size: String? + let quality: String? + let background: String? + let outputFormat: String? + let usage: ImageUsage? + + func result(for request: ImageRequest, notes: [String], requestID: String?) throws -> ImageResult { + let images = try data.map { item in + guard let encoded = item.b64Json, let bytes = Data(base64Encoded: encoded) else { + throw ImageGenerationError.invalidResponse("an image in the response has no b64_json data") + } + return GeneratedImage(data: bytes, revisedPrompt: item.revisedPrompt) + } + return ImageResult( + images: images, + size: size ?? request.size?.rawValue, + quality: quality ?? request.quality?.rawValue, + background: background ?? request.background?.rawValue, + outputFormat: outputFormat ?? request.outputFormat?.rawValue, + usage: usage, + notes: notes, + requestID: requestID + ) + } +} diff --git a/Sources/Providers/API/OpenAI/Image Generation/Images API/ImageSize.swift b/Sources/Providers/API/OpenAI/Image Generation/Images API/ImageSize.swift new file mode 100644 index 0000000..7e89a91 --- /dev/null +++ b/Sources/Providers/API/OpenAI/Image Generation/Images API/ImageSize.swift @@ -0,0 +1,125 @@ +// +// ImageSize.swift +// +// `auto` or `WxH`, validated against the documented GPT Image limits. +// + +import Foundation + +/// An Images API `size`: `auto` or `WxH`. +/// +/// Recommended sizes are `1024x1024`, `1536x1024` and `1024x1536`. Custom +/// sizes are checked by ``validate()`` against the limits shared by all GPT +/// Image models. +public struct ImageSize: RawRepresentable, Hashable, Sendable, Codable, ExpressibleByStringLiteral, + CustomStringConvertible { + public let rawValue: String + + public init(rawValue: String) { + self.rawValue = rawValue + } + + public init(_ rawValue: String) { + self.rawValue = rawValue + } + + public init(stringLiteral value: String) { + rawValue = value + } + + public init(width: Int, height: Int) { + rawValue = "\(width)x\(height)" + } + + public init(from decoder: Decoder) throws { + rawValue = try decoder.singleValueContainer().decode(String.self) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + try container.encode(rawValue) + } + + public var description: String { rawValue } + + public static let auto = ImageSize("auto") + public static let square = ImageSize("1024x1024") + public static let landscape = ImageSize("1536x1024") + public static let portrait = ImageSize("1024x1536") + + // MARK: - Limits + + /// Both sides must be a multiple of this. + public static let multiple = 16 + /// The longest side, in pixels. + public static let maxEdge = 3840 + /// The longest side may be at most this many times the shortest. + public static let maxAspectRatio = 3 + public static let minPixels = 655_360 + public static let maxPixels = 8_294_400 + /// Sizes with more pixels than 2560×1440 are experimental. + public static let experimentalPixels = 2560 * 1440 + + public var isAuto: Bool { rawValue == "auto" } + + /// The width and height, or `nil` for `auto` and anything that isn't `WxH`. + public var dimensions: (width: Int, height: Int)? { + let parts = rawValue.lowercased().split(separator: "x", omittingEmptySubsequences: false) + guard parts.count == 2, + let width = Int(parts[0]), let height = Int(parts[1]), + parts.allSatisfy({ $0.allSatisfy(\.isASCII) }) + else { return nil } + return (width, height) + } + + /// Whether the size is above 2560×1440 — allowed, but experimental. + public var isExperimental: Bool { + guard let (width, height) = dimensions else { return false } + return width * height > Self.experimentalPixels + } + + /// Checks the size against the documented limits. + /// + /// - Returns: Notes for the caller (an experimental size is allowed, with a note). + /// - Throws: ``ImageGenerationError/invalidParameter(_:)`` naming the violated rule. + @discardableResult + public func validate() throws -> [String] { + if isAuto { return [] } + guard let (width, height) = dimensions else { + throw ImageGenerationError.invalidParameter( + "size '\(rawValue)' must be 'auto' or WIDTHxHEIGHT, e.g. 1536x1024" + ) + } + guard width > 0, height > 0 else { + throw ImageGenerationError.invalidParameter("size \(rawValue): both sides must be positive") + } + guard width % Self.multiple == 0, height % Self.multiple == 0 else { + throw ImageGenerationError.invalidParameter( + "size \(rawValue): both sides must be multiples of \(Self.multiple)" + ) + } + let longest = max(width, height) + let shortest = min(width, height) + guard longest <= Self.maxEdge else { + throw ImageGenerationError.invalidParameter( + "size \(rawValue): the longest side must be at most \(Self.maxEdge) pixels" + ) + } + guard longest <= Self.maxAspectRatio * shortest else { + throw ImageGenerationError.invalidParameter( + "size \(rawValue): the aspect ratio must be between 1:\(Self.maxAspectRatio) " + + "and \(Self.maxAspectRatio):1" + ) + } + let pixels = width * height + guard pixels >= Self.minPixels, pixels <= Self.maxPixels else { + throw ImageGenerationError.invalidParameter( + "size \(rawValue): total pixels (\(pixels)) must be between \(Self.minPixels) and \(Self.maxPixels)" + ) + } + if pixels > Self.experimentalPixels { + return ["size \(rawValue) is above 2560x1440; sizes that large are experimental and results may vary"] + } + return [] + } +} diff --git a/Sources/Providers/API/OpenAI/Image Generation/Images API/OpenAI+Images.swift b/Sources/Providers/API/OpenAI/Image Generation/Images API/OpenAI+Images.swift new file mode 100644 index 0000000..4a28dc6 --- /dev/null +++ b/Sources/Providers/API/OpenAI/Image Generation/Images API/OpenAI+Images.swift @@ -0,0 +1,81 @@ +// +// OpenAI+Images.swift +// +// Generate and edit images through the Images API with exact control over +// model, size, quality, background and format. +// + +import Foundation +#if canImport(FoundationNetworking) +import FoundationNetworking +#endif + +public extension OpenAI { + /// Generates images via `/v1/images/generations`. + /// + /// The request is validated first; a violation throws and nothing is sent. + func generateImages(_ request: ImageRequest) async throws -> ImageResult { + let notes = try request.validate() + var urlRequest = try createUrlRequest(httpMethod: "POST", path: "/\(versionPath)/images/generations") + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + urlRequest.httpBody = try request.jsonData() + return try await performImageRequest(urlRequest, for: request, notes: notes) + } + + /// Edits images via `/v1/images/edits` (multipart), from one or more reference + /// images and an optional mask for the first. + func editImages(_ edit: ImageEditRequest) async throws -> ImageResult { + let notes = try edit.validate() + var urlRequest = try createUrlRequest(httpMethod: "POST", path: "/\(versionPath)/images/edits") + let form = edit.multipartBody() + urlRequest.setValue(form.contentType, forHTTPHeaderField: "Content-Type") + urlRequest.httpBody = form.encoded() + return try await performImageRequest(urlRequest, for: edit.request, notes: notes) + } + + private func performImageRequest( + _ urlRequest: URLRequest, + for request: ImageRequest, + notes: [String] + ) async throws -> ImageResult { + let data: Data + let response: URLResponse + do { + (data, response) = try await session.data(for: urlRequest) + } catch { + throw ImageGenerationError.networkError(error) + } + guard let http = response as? HTTPURLResponse else { + throw ImageGenerationError.invalidResponse("not an HTTP response") + } + let requestID = http.value(forHTTPHeaderField: "x-request-id") + + guard http.statusCode == 200 else { + let error = imageAPIError(data: data, statusCode: http.statusCode, requestID: requestID) + throw ImageGenerationError.api(error) + } + do { + let decoded = try decoder.decode(ImagesResponse.self, from: data) + return try decoded.result(for: request, notes: notes, requestID: requestID) + } catch let error as ImageGenerationError { + throw error + } catch { + throw ImageGenerationError.invalidResponse("could not decode the response: \(error.localizedDescription)") + } + } + + private func imageAPIError(data: Data, statusCode: Int, requestID: String?) -> ImageAPIError { + if let body = try? decoder.decode(ErrorResponse.self, from: data) { + return ImageAPIError( + statusCode: statusCode, + message: body.error.message, + type: body.error.type, + code: body.error.code, + param: body.error.param, + requestID: requestID + ) + } + let text = String(data: data, encoding: .utf8) ?? "" + return ImageAPIError(statusCode: statusCode, message: text, requestID: requestID) + } +} diff --git a/Sources/Providers/API/OpenAI/Image Generation/Model/ImageGenerationError.swift b/Sources/Providers/API/OpenAI/Image Generation/Model/ImageGenerationError.swift index 72340bc..22a212b 100644 --- a/Sources/Providers/API/OpenAI/Image Generation/Model/ImageGenerationError.swift +++ b/Sources/Providers/API/OpenAI/Image Generation/Model/ImageGenerationError.swift @@ -21,6 +21,8 @@ public enum ImageGenerationError: LocalizedError { case authenticationError /// Server error case serverError + /// An error reported by the Images API, with its `x-request-id` + case api(ImageAPIError) public var errorDescription: String? { switch self { @@ -36,6 +38,43 @@ public enum ImageGenerationError: LocalizedError { return "Authentication error" case .serverError: return "Server error" + case let .api(error): + return error.description } } } + +/// An error response from the Images API. +public struct ImageAPIError: Sendable, Equatable, CustomStringConvertible { + public var statusCode: Int + public var message: String + public var type: String? + public var code: String? + public var param: String? + /// The `x-request-id` response header, for support requests. + public var requestID: String? + + public init( + statusCode: Int, + message: String, + type: String? = nil, + code: String? = nil, + param: String? = nil, + requestID: String? = nil + ) { + self.statusCode = statusCode + self.message = message + self.type = type + self.code = code + self.param = param + self.requestID = requestID + } + + public var description: String { + var details = ["HTTP \(statusCode)"] + if let type { details.append(type) } + if let code { details.append(code) } + if let requestID { details.append("request id \(requestID)") } + return "OpenAI Images API error (\(details.joined(separator: ", "))): \(message)" + } +} diff --git a/Sources/Providers/API/OpenAI/Image Generation/OpenAI+ImageGen.swift b/Sources/Providers/API/OpenAI/Image Generation/OpenAI+ImageGen.swift index 6b26760..38451e1 100644 --- a/Sources/Providers/API/OpenAI/Image Generation/OpenAI+ImageGen.swift +++ b/Sources/Providers/API/OpenAI/Image Generation/OpenAI+ImageGen.swift @@ -22,6 +22,11 @@ public extension OpenAI { - Throws: An error if the image generation request fails or if the parameters are invalid for the selected model. */ + @available( + *, + deprecated, + message: "Use generateImages(_:) with an ImageRequest: open model names, any valid size, 2.5 models." + ) func generateImage( prompt: String, model: ImageGenerationModel diff --git a/Sources/Providers/Extensions/MultipartFormData.swift b/Sources/Providers/Extensions/MultipartFormData.swift new file mode 100644 index 0000000..808dff0 --- /dev/null +++ b/Sources/Providers/Extensions/MultipartFormData.swift @@ -0,0 +1,64 @@ +// +// MultipartFormData.swift +// +// A small `multipart/form-data` encoder. Foundation only. +// + +import Foundation + +/// Builds a `multipart/form-data` body from text fields and file parts. +public struct MultipartFormData: Sendable { + private enum Part: Sendable { + case field(name: String, value: String) + case file(name: String, filename: String, mimeType: String, data: Data) + } + + private var parts: [Part] = [] + + /// The boundary separating the parts. + public let boundary: String + + public init(boundary: String = "Boundary-\(UUID().uuidString)") { + self.boundary = boundary + } + + /// The `Content-Type` header value for the encoded body. + public var contentType: String { "multipart/form-data; boundary=\(boundary)" } + + public mutating func addField(name: String, value: String) { + parts.append(.field(name: name, value: value)) + } + + public mutating func addFile(name: String, filename: String, mimeType: String, data: Data) { + parts.append(.file(name: name, filename: filename, mimeType: mimeType, data: data)) + } + + /// The encoded body. + public func encoded() -> Data { + var body = Data() + for part in parts { + body.append("--\(boundary)\r\n") + switch part { + case let .field(name, value): + body.append("Content-Disposition: form-data; name=\"\(Self.escape(name))\"\r\n\r\n") + body.append("\(value)\r\n") + case let .file(name, filename, mimeType, data): + body.append( + "Content-Disposition: form-data; name=\"\(Self.escape(name))\"; " + + "filename=\"\(Self.escape(filename))\"\r\n" + ) + body.append("Content-Type: \(mimeType)\r\n\r\n") + body.append(data) + body.append("\r\n") + } + } + body.append("--\(boundary)--\r\n") + return body + } + + private static func escape(_ value: String) -> String { + value.replacingOccurrences(of: "\"", with: "%22") + .replacingOccurrences(of: "\r", with: "%0D") + .replacingOccurrences(of: "\n", with: "%0A") + } +} diff --git a/Tests/ProvidersTests/OpenAI/Images/ImagesAPITests.swift b/Tests/ProvidersTests/OpenAI/Images/ImagesAPITests.swift new file mode 100644 index 0000000..b6a3835 --- /dev/null +++ b/Tests/ProvidersTests/OpenAI/Images/ImagesAPITests.swift @@ -0,0 +1,544 @@ +// +// ImagesAPITests.swift +// +// Offline coverage of the Images API client: size validation, the +// model/quality/background matrix, request encoding (generate, edit, batch), +// response decoding, error mapping and header parsing. +// + +import Foundation +@testable import Providers +import Testing +#if canImport(FoundationNetworking) +import FoundationNetworking +#endif + +// MARK: - Size validation + +@Suite("Image size validation") +struct ImageSizeTests { + @Test("auto and the recommended sizes are valid", arguments: ["auto", "1024x1024", "1536x1024", "1024x1536"]) + func validSizes(size: String) throws { + #expect(try ImageSize(size).validate().isEmpty) + } + + @Test("a custom size inside every limit is valid in both orientations", arguments: [ + "2048x1152", "1152x2048", "1536x864" + ]) + func customSizes(size: String) throws { + #expect(try ImageSize(size).validate().isEmpty) + } + + @Test("each rule is named in the error", arguments: [ + ("1000x1000", "multiples of 16"), + ("1024x1000", "multiples of 16"), + ("4096x1024", "longest side"), + ("1024x4096", "longest side"), + ("3840x1024", "aspect ratio"), + ("1024x3840", "aspect ratio"), + ("256x256", "total pixels"), + ("3840x2400", "total pixels"), + ("wide", "WIDTHxHEIGHT"), + ("0x1024", "positive") + ]) + func violations(size: String, rule: String) { + do { + try ImageSize(size).validate() + Issue.record("\(size) should be rejected") + } catch let ImageGenerationError.invalidParameter(message) { + #expect(message.contains(rule), "\(message) should name '\(rule)'") + } catch { + Issue.record("unexpected error \(error)") + } + } + + @Test("exactly 3:1 is allowed") + func threeToOne() throws { + #expect(try ImageSize("2304x768").validate().isEmpty) + #expect(try ImageSize("768x2304").validate().isEmpty) + } + + @Test("above 2560x1440 is allowed with an experimental note, at or below it is not flagged") + func experimentalThreshold() throws { + #expect(try ImageSize("2560x1440").validate().isEmpty) + #expect(try ImageSize("1440x2560").validate().isEmpty) + for size in ["3840x2160", "2160x3840", "2576x1440"] { + let notes = try ImageSize(size).validate() + #expect(notes.count == 1 && notes[0].contains("experimental"), "\(size)") + } + } + + @Test("dimensions parse WxH only") + func dimensions() { + #expect(ImageSize("2048x1152").dimensions?.width == 2048) + #expect(ImageSize("2048X1152").dimensions?.height == 1152) + #expect(ImageSize.auto.dimensions == nil) + } +} + +// MARK: - Model / quality / background matrix + +@Suite("Image request validation") +struct ImageRequestValidationTests { + private func message(_ request: ImageRequest) -> String? { + do { + try request.validate() + return nil + } catch let ImageGenerationError.invalidParameter(message) { + return message + } catch { + return "unexpected \(error)" + } + } + + @Test("xhigh and max exist only on the 2.5 models", arguments: ["xhigh", "max"]) + func extendedQuality(quality: String) throws { + for model in [ImageModel.sunburst, .flare] { + try ImageRequest(prompt: "p", model: model, quality: ImageQuality(quality)).validate() + } + let text = try #require(message(ImageRequest(prompt: "p", model: .gptImage2, quality: ImageQuality(quality)))) + #expect(text.contains("2.5") && text.contains("gpt-image-2.5-sunburst")) + } + + @Test("the common qualities work on every model", arguments: ["low", "medium", "high", "auto"]) + func commonQuality(quality: String) throws { + for model in [ImageModel.sunburst, .flare, .gptImage2] { + try ImageRequest(prompt: "p", model: model, quality: ImageQuality(quality)).validate() + } + } + + @Test("an unknown model passes through unchanged") + func unknownModel() throws { + let request = ImageRequest(prompt: "p", model: "gpt-image-9", quality: .max) + try request.validate() + let text = String(data: try request.jsonData(), encoding: .utf8) ?? "" + #expect(text.contains("\"gpt-image-9\"")) + } + + @Test("transparent needs a 2.5 model and not jpeg") + func transparency() throws { + try ImageRequest(prompt: "p", model: .flare, background: .transparent, outputFormat: .png).validate() + try ImageRequest(prompt: "p", model: .sunburst, background: .transparent, outputFormat: .webp).validate() + try ImageRequest(prompt: "p", background: .transparent).validate() + + let jpeg = try #require(message(ImageRequest(prompt: "p", background: .transparent, outputFormat: .jpeg))) + #expect(jpeg.contains("jpeg")) + let legacy = try #require(message(ImageRequest(prompt: "p", model: .gptImage2, background: .transparent))) + #expect(legacy.contains("gpt-image-2.5-sunburst")) + } + + @Test("output_compression applies to jpeg and webp only, within 0-100") + func compression() throws { + try ImageRequest(prompt: "p", outputFormat: .jpeg, outputCompression: 80).validate() + try ImageRequest(prompt: "p", outputFormat: .webp, outputCompression: 0).validate() + #expect(message(ImageRequest(prompt: "p", outputFormat: .png, outputCompression: 80)) != nil) + #expect(message(ImageRequest(prompt: "p", outputCompression: 80)) != nil) + #expect(message(ImageRequest(prompt: "p", outputFormat: .jpeg, outputCompression: 101)) != nil) + } + + @Test("prompt and n are checked") + func promptAndCount() { + #expect(message(ImageRequest(prompt: " ")) != nil) + #expect(message(ImageRequest(prompt: "p", n: 0)) != nil) + #expect(message(ImageRequest(prompt: "p", n: 11)) != nil) + } + + @Test("a size violation or experimental size surfaces through the request") + func sizeThroughRequest() throws { + #expect(message(ImageRequest(prompt: "p", size: "1000x1000")) != nil) + #expect(try ImageRequest(prompt: "p", size: "3840x2160").validate().count == 1) + } +} + +// MARK: - Encoding + +@Suite("Image request encoding") +struct ImageEncodingTests { + private func object(_ data: Data) throws -> [String: Any] { + try #require(try JSONSerialization.jsonObject(with: data) as? [String: Any]) + } + + @Test("generate encodes snake_case and omits unset fields") + func generateBody() throws { + let request = ImageRequest( + prompt: "a fox", model: .flare, size: "2048x1152", quality: .low, background: .opaque, + outputFormat: .jpeg, outputCompression: 70, moderation: .low, n: 2 + ) + let json = try object(request.jsonData()) + #expect(json["model"] as? String == "gpt-image-2.5-flare") + #expect(json["size"] as? String == "2048x1152") + #expect(json["quality"] as? String == "low") + #expect(json["background"] as? String == "opaque") + #expect(json["output_format"] as? String == "jpeg") + #expect(json["output_compression"] as? Int == 70) + #expect(json["moderation"] as? String == "low") + #expect(json["n"] as? Int == 2) + + let minimal = try object(ImageRequest(prompt: "a fox").jsonData()) + #expect(minimal.keys.sorted() == ["model", "n", "prompt"]) + #expect(minimal["model"] as? String == "gpt-image-2.5-sunburst") + } + + @Test("edit is multipart with image[] parts, an optional mask and never input_fidelity") + func editBody() throws { + let edit = ImageEditRequest( + request: ImageRequest(prompt: "add a hat", model: .sunburst, size: "1024x1024", quality: .low), + images: [ + ImageInput(data: Data([1, 2, 3]), filename: "a.png"), + ImageInput(data: Data([4, 5]), filename: "b.jpg") + ], + mask: ImageInput(data: Data([9]), filename: "mask.png") + ) + let form = edit.multipartBody() + let body = String(data: form.encoded(), encoding: .utf8) ?? "" + + #expect(form.contentType == "multipart/form-data; boundary=\(form.boundary)") + #expect(body.hasPrefix("--\(form.boundary)\r\n")) + #expect(body.hasSuffix("--\(form.boundary)--\r\n")) + #expect(body.contains("name=\"model\"\r\n\r\ngpt-image-2.5-sunburst\r\n")) + #expect(body.contains("name=\"prompt\"\r\n\r\nadd a hat\r\n")) + #expect(body.contains("name=\"size\"\r\n\r\n1024x1024\r\n")) + #expect(body.contains("name=\"quality\"\r\n\r\nlow\r\n")) + #expect(body.components(separatedBy: "name=\"image[]\"").count == 3) + #expect(body.contains("filename=\"a.png\"\r\nContent-Type: image/png")) + #expect(body.contains("filename=\"b.jpg\"\r\nContent-Type: image/jpeg")) + #expect(body.contains("name=\"mask\"; filename=\"mask.png\"")) + #expect(!body.contains("input_fidelity")) + } + + @Test("an edit needs an image") + func editNeedsImage() { + #expect(throws: ImageGenerationError.self) { + try ImageEditRequest(request: ImageRequest(prompt: "p"), images: []).validate() + } + } + + @Test("batch lines override the defaults, blank lines and comments are skipped") + func batchParsing() throws { + let jsonl = """ + # first + {"prompt": "one", "size": "1536x1024", "out": "one.png"} + + {"prompt": "two", "model": "gpt-image-2", "quality": "high", "output_format": "webp", "n": 2} + {"out": "default-prompt.png"} + """ + let defaults = ImageRequest(prompt: "fallback", model: .flare, size: "1024x1024", quality: .low) + let jobs = try ImageBatchJob.parse(jsonl: jsonl, defaults: defaults) + + #expect(jobs.count == 3) + #expect(jobs[0].request.prompt == "one") + #expect(jobs[0].request.model == .flare) + #expect(jobs[0].request.size == "1536x1024") + #expect(jobs[0].request.quality == .low) + #expect(jobs[0].out == "one.png") + #expect(jobs[1].request.model == .gptImage2) + #expect(jobs[1].request.quality == .high) + #expect(jobs[1].request.outputFormat == .webp) + #expect(jobs[1].request.n == 2) + #expect(jobs[1].out == nil) + #expect(jobs[2].request.prompt == "fallback") + } + + @Test("a batch line without any prompt, or that is not JSON, names its line") + func batchErrors() { + for (jsonl, line) in [("{\"size\": \"auto\"}", "line 1"), ("{\"prompt\": \"a\"}\nnot json", "line 2")] { + do { + _ = try ImageBatchJob.parse(jsonl: jsonl, defaults: ImageRequest(prompt: "")) + Issue.record("expected an error") + } catch let ImageGenerationError.invalidParameter(message) { + #expect(message.contains(line)) + } catch { + Issue.record("unexpected error \(error)") + } + } + } +} + +// MARK: - Decoding + +@Suite("Image response decoding") +struct ImageDecodingTests { + private let openAI = OpenAI(credential: Credential.bearer("test-key")) + + @Test("b64_json, usage and the resolved settings decode") + func decodesResponse() throws { + let png = Data([0x89, 0x50, 0x4E, 0x47]) + let json = """ + {"created": 1700000000, + "data": [{"b64_json": "\(png.base64EncodedString())", "revised_prompt": "a red fox"}], + "size": "1536x864", "quality": "low", "background": "opaque", "output_format": "png", + "usage": {"input_tokens": 12, "output_tokens": 1056, "total_tokens": 1068, + "input_tokens_details": {"text_tokens": 12, "image_tokens": 0}}} + """ + let response = try openAI.decoder.decode(ImagesResponse.self, from: Data(json.utf8)) + let result = try response.result( + for: ImageRequest(prompt: "fox", size: "auto"), notes: ["n"], requestID: "req_1" + ) + + #expect(result.images.count == 1) + #expect(result.images[0].data == png) + #expect(result.images[0].revisedPrompt == "a red fox") + #expect(result.size == "1536x864") + #expect(result.quality == "low") + #expect(result.background == "opaque") + #expect(result.outputFormat == "png") + #expect(result.usage?.inputTokens == 12) + #expect(result.usage?.outputTokens == 1056) + #expect(result.usage?.totalTokens == 1068) + #expect(result.usage?.inputTokensDetails?.textTokens == 12) + #expect(result.usage?.inputTokensDetails?.imageTokens == 0) + #expect(result.notes == ["n"]) + #expect(result.requestID == "req_1") + } + + @Test("settings the API doesn't echo fall back to the request") + func fallsBackToRequest() throws { + let json = "{\"data\": [{\"b64_json\": \"AAEC\"}]}" + let response = try openAI.decoder.decode(ImagesResponse.self, from: Data(json.utf8)) + let result = try response.result( + for: ImageRequest(prompt: "p", size: "1024x1024", quality: .high, outputFormat: .webp), + notes: [], requestID: nil + ) + #expect(result.size == "1024x1024") + #expect(result.quality == "high") + #expect(result.outputFormat == "webp") + #expect(result.usage == nil) + } + + @Test("an item without b64_json is an invalid response") + func missingImage() throws { + let response = try openAI.decoder.decode(ImagesResponse.self, from: Data("{\"data\": [{}]}".utf8)) + #expect(throws: ImageGenerationError.self) { + try response.result(for: ImageRequest(prompt: "p"), notes: [], requestID: nil) + } + } +} + +// MARK: - Image headers + +@Suite("Image header parsing") +struct ImageInfoTests { + private func beBytes(_ value: Int) -> [UInt8] { + [UInt8(value >> 24 & 0xFF), UInt8(value >> 16 & 0xFF), UInt8(value >> 8 & 0xFF), UInt8(value & 0xFF)] + } + + private func png(width: Int, height: Int, colorType: UInt8, trns: Bool = false) -> Data { + var bytes: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A] + bytes += beBytes(13) + Array("IHDR".utf8) + beBytes(width) + beBytes(height) + [8, colorType, 0, 0, 0] + bytes += [0, 0, 0, 0] + if trns { bytes += beBytes(1) + Array("tRNS".utf8) + [0, 0, 0, 0, 0] } + bytes += beBytes(0) + Array("IDAT".utf8) + [0, 0, 0, 0] + return Data(bytes) + } + + @Test("PNG size and alpha") + func pngInfo() throws { + let rgba = try #require(ImageInfo(data: png(width: 2048, height: 1152, colorType: 6))) + #expect(rgba == ImageInfo(data: png(width: 2048, height: 1152, colorType: 6))) + #expect(rgba.width == 2048 && rgba.height == 1152 && rgba.hasAlpha) + #expect(try #require(ImageInfo(data: png(width: 4, height: 2, colorType: 2))).hasAlpha == false) + #expect(try #require(ImageInfo(data: png(width: 4, height: 2, colorType: 3, trns: true))).hasAlpha) + } + + @Test("JPEG size") + func jpegInfo() throws { + let bytes: [UInt8] = [ + 0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x04, 0, 0, 0xFF, 0xC0, 0x00, 0x11, 8, 0x04, 0x00, 0x06, 0x00 + ] + let info = try #require(ImageInfo(data: Data(bytes))) + #expect(info.width == 1536 && info.height == 1024 && !info.hasAlpha) + } + + @Test("WebP size and alpha (VP8X)") + func webpInfo() throws { + var bytes = Array("RIFF".utf8) + [0, 0, 0, 0] + Array("WEBP".utf8) + Array("VP8X".utf8) + [10, 0, 0, 0] + bytes += [0x10, 0, 0, 0, 0xFF, 0x03, 0, 0xFF, 0x01, 0] + let info = try #require(ImageInfo(data: Data(bytes))) + #expect(info.width == 1024 && info.height == 512 && info.hasAlpha) + } + + @Test("anything else is nil") + func unknown() { + #expect(ImageInfo(data: Data([1, 2, 3])) == nil) + } +} + +// MARK: - Client (stubbed transport) + +/// Records the request and answers with a scripted response. +private final class ImagesStub: URLProtocol { + struct Reply { + var status: Int + var headers: [String: String] + var body: Data + } + + private static let lock = NSLock() + nonisolated(unsafe) private static var reply = Reply(status: 200, headers: [:], body: Data()) + nonisolated(unsafe) private static var seen: [Seen] = [] + + struct Seen { + var url: URL + var contentType: String? + var auth: String? + var body: Data + } + + static func script(_ reply: Reply) { + lock.lock() + defer { lock.unlock() } + self.reply = reply + seen = [] + } + + static var requests: [Seen] { + lock.lock() + defer { lock.unlock() } + return seen + } + + override static func canInit(with _: URLRequest) -> Bool { true } + override static func canonicalRequest(for request: URLRequest) -> URLRequest { request } + + override func startLoading() { + var body = request.httpBody ?? Data() + if let stream = request.httpBodyStream { + stream.open() + var buffer = [UInt8](repeating: 0, count: 4096) + while stream.hasBytesAvailable { + let count = stream.read(&buffer, maxLength: buffer.count) + if count <= 0 { break } + body.append(buffer, count: count) + } + stream.close() + } + Self.lock.lock() + Self.seen.append(Seen( + url: request.url!, + contentType: request.value(forHTTPHeaderField: "Content-Type"), + auth: request.value(forHTTPHeaderField: "Authorization"), + body: body + )) + let reply = Self.reply + Self.lock.unlock() + + let response = HTTPURLResponse( + url: request.url!, statusCode: reply.status, httpVersion: "HTTP/1.1", headerFields: reply.headers + )! + client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) + client?.urlProtocol(self, didLoad: reply.body) + client?.urlProtocolDidFinishLoading(self) + } + + override func stopLoading() {} +} + +@Suite("Images API client", .serialized) +struct ImagesClientTests { + private func makeClient() -> OpenAI { + let api = OpenAI(credential: Credential.bearer("sk-test")) + let configuration = URLSessionConfiguration.ephemeral + configuration.protocolClasses = [ImagesStub.self] + api.session = URLSession(configuration: configuration) + return api + } + + private let okBody = Data( + "{\"data\": [{\"b64_json\": \"AAEC\"}], \"size\": \"1536x864\", \"quality\": \"low\"}".utf8 + ) + + @Test("generate posts JSON to /v1/images/generations with the bearer key and reports the request id") + func generate() async throws { + ImagesStub.script(.init(status: 200, headers: ["x-request-id": "req_ok"], body: okBody)) + let result = try await makeClient().generateImages( + ImageRequest(prompt: "a fox", model: .flare, size: "1536x864", quality: .low) + ) + + let sent = try #require(ImagesStub.requests.first) + #expect(sent.url.path == "/v1/images/generations") + #expect(sent.contentType == "application/json") + #expect(sent.auth == "Bearer sk-test") + let json = try #require(try JSONSerialization.jsonObject(with: sent.body) as? [String: Any]) + #expect(json["model"] as? String == "gpt-image-2.5-flare") + #expect(json["size"] as? String == "1536x864") + #expect(result.images.first?.data == Data([0, 1, 2])) + #expect(result.requestID == "req_ok") + #expect(result.size == "1536x864") + } + + @Test("edit posts multipart to /v1/images/edits") + func edit() async throws { + ImagesStub.script(.init(status: 200, headers: [:], body: okBody)) + _ = try await makeClient().editImages(ImageEditRequest( + request: ImageRequest(prompt: "hat"), images: [ImageInput(data: Data([7]), filename: "a.png")] + )) + let sent = try #require(ImagesStub.requests.first) + #expect(sent.url.path == "/v1/images/edits") + #expect(sent.contentType?.hasPrefix("multipart/form-data; boundary=") == true) + let text = String(data: sent.body, encoding: .utf8) ?? "" + #expect(text.contains("name=\"image[]\"; filename=\"a.png\"")) + } + + @Test("an invalid request is rejected before anything is sent") + func invalidSendsNothing() async { + ImagesStub.script(.init(status: 200, headers: [:], body: okBody)) + await #expect(throws: ImageGenerationError.self) { + _ = try await makeClient().generateImages(ImageRequest(prompt: "p", size: "1000x1000")) + } + #expect(ImagesStub.requests.isEmpty) + } + + @Test("an API error maps to a typed error carrying x-request-id") + func apiError() async throws { + let body = Data( + ("{\"error\": {\"message\": \"bad size\", \"type\": \"invalid_request_error\", " + + "\"param\": \"size\", \"code\": \"invalid_size\"}}").utf8 + ) + ImagesStub.script(.init(status: 400, headers: ["x-request-id": "req_bad"], body: body)) + do { + _ = try await makeClient().generateImages(ImageRequest(prompt: "p")) + Issue.record("expected an error") + } catch let ImageGenerationError.api(error) { + #expect(error.statusCode == 400) + #expect(error.message == "bad size") + #expect(error.type == "invalid_request_error") + #expect(error.code == "invalid_size") + #expect(error.param == "size") + #expect(error.requestID == "req_bad") + #expect(error.description.contains("req_bad")) + } + } + + @Test("a batch runs every job, reports each result in order and bounds concurrency") + func batch() async { + let jobs = (0..<6).map { ImageBatchJob(request: ImageRequest(prompt: "p\($0)"), out: "\($0).png") } + let tracker = ConcurrencyTracker() + let results = await makeClient().generateImageBatch(jobs, concurrency: 2) { index, job in + await tracker.enter() + try await Task.sleep(nanoseconds: 20_000_000) + await tracker.leave() + if index == 3 { throw ImageGenerationError.serverError } + return ImageResult(images: [], size: job.out, quality: nil, background: nil, outputFormat: nil, + usage: nil, notes: [], requestID: nil) + } + #expect(results.map(\.index) == [0, 1, 2, 3, 4, 5]) + #expect(await tracker.peak <= 2) + for result in results { + switch result.outcome { + case let .success(value): #expect(result.index != 3 && value.size == "\(result.index).png") + case .failure: #expect(result.index == 3) + } + } + } +} + +private actor ConcurrencyTracker { + private var running = 0 + private(set) var peak = 0 + func enter() { + running += 1 + peak = max(peak, running) + } + + func leave() { running -= 1 } +} diff --git a/Tests/ProvidersTests/OpenAI/Images/ImagesLiveTests.swift b/Tests/ProvidersTests/OpenAI/Images/ImagesLiveTests.swift new file mode 100644 index 0000000..7ae3957 --- /dev/null +++ b/Tests/ProvidersTests/OpenAI/Images/ImagesLiveTests.swift @@ -0,0 +1,40 @@ +// +// ImagesLiveTests.swift +// +// Live checks against the real Images API, gated on OPENAI_API_KEY (never +// runs in CI). Three `low` images in total. The key is never printed. +// + +import Foundation +@testable import Providers +import Testing + +@Suite("Images API (live)", .enabled(if: APIKey.hasOpenAI), .serialized) +struct ImagesLiveTests { + private func makeClient() throws -> OpenAI { + OpenAI(credential: Credential.bearer(try #require(APIKey.openAI))) + } + + @Test("a low-quality generate at 1536x864 returns the exact pixel size", arguments: [ImageModel.flare, .sunburst]) + func generateAtCustomSize(model: ImageModel) async throws { + let result = try await makeClient().generateImages( + ImageRequest(prompt: "A flat red circle on white", model: model, size: "1536x864", quality: .low) + ) + let image = try #require(result.images.first) + let info = try #require(ImageInfo(data: image.data)) + #expect(info.width == 1536 && info.height == 864) + #expect(result.usage != nil) + } + + @Test("a transparent png has an alpha channel") + func transparentPNG() async throws { + let result = try await makeClient().generateImages(ImageRequest( + prompt: "A single red circle, nothing else", model: .flare, size: "1024x1024", + quality: .low, background: .transparent, outputFormat: .png + )) + let image = try #require(result.images.first) + let info = try #require(ImageInfo(data: image.data)) + #expect(info.width == 1024 && info.height == 1024) + #expect(info.hasAlpha) + } +} diff --git a/readme.md b/readme.md index d5e0d67..0909ba7 100644 --- a/readme.md +++ b/readme.md @@ -15,6 +15,7 @@ Early. Split out from the private AgentCorp project so the public agent surface - **`SemanticStore`** — semantic-search stores behind one `SemanticStore` protocol: the in-memory `LocalVectorStore`, the hosted `OpenAIVectorStore`, and the persistent `SQLiteVectorStore` (opt-in via the `SQLiteVectorStore` package trait). See [Docs/SemanticStore.md](Docs/SemanticStore.md). - **`TerminalUI`** — ANSI colours, slash-command parser, terminal handler. Used by the bundled CLI; reusable by other tools. - **`Coder`** — an in-process coding-agent CLI (executable target). Tool surface: `bash`, `read`, `write`, `edit`, `ls`, `grep`, `find`, plus `apply_patch` for models that support it. Also runs as an ACP agent: `swift run Coder acp` serves the [Agent Client Protocol](https://agentclientprotocol.com) on stdio (via [SwiftACP](https://github.com/Cocoanetics/SwiftACP)), so editors like Zed can drive it — including the client's per-session MCP servers and per-session model switching (`--model`, `/model`, or the native `session/set_model`). Reference implementation of an `Agent` against the Responses API. +- **`imagegen`** — a command-line client for the OpenAI Images API (a Swift port of Codex's `image_gen.py`): `generate`, `edit` and `generate-batch` with exact control over model (`gpt-image-2.5-sunburst`, `gpt-image-2.5-flare`, `gpt-image-2`), size, quality, background and format. The same client is available to any Swift program as `OpenAI.generateImages(_:)`, `editImages(_:)` and `generateImageBatch(_:)` in `Providers`. ## Usage @@ -95,6 +96,7 @@ swift test # full suite (integration tests need key swift test --filter LocalVectorStore # offline-only swift run Coder --help # the Coder CLI swift run Coder acp # serve Coder over ACP on stdio +swift run imagegen generate --prompt "…" --dry-run # the Images API CLI ``` ## Provenance From b7077e9e98152ee26a1f198520900ebe04c406a8 Mon Sep 17 00:00:00 2001 From: Oliver Drobnik Date: Fri, 30 Oct 2026 09:15:56 +0100 Subject: [PATCH 2/3] Validate batch jobs in dry runs, fix path claims, cap edits at 16 images Co-Authored-By: Claude Sonnet 5.5 --- Examples/ImageGen/Commands.swift | 33 ++++++++++++++++--- .../Images API/ImageRequest.swift | 8 +++++ .../OpenAI/Images/ImagesAPITests.swift | 10 ++++++ 3 files changed, 47 insertions(+), 4 deletions(-) diff --git a/Examples/ImageGen/Commands.swift b/Examples/ImageGen/Commands.swift index acb314b..5ac9bd4 100644 --- a/Examples/ImageGen/Commands.swift +++ b/Examples/ImageGen/Commands.swift @@ -103,6 +103,17 @@ struct Edit: AsyncParsableCommand { } } +/// The `--dry-run --json` plan of a batch. +private struct BatchDryRun: Encodable { + struct Job: Encodable { + var index: Int + var plan: DryRun? + var error: String? + } + + var jobs: [Job] +} + /// The `--json` result of a batch. private struct BatchReport: Encodable { struct Job: Encodable { @@ -158,17 +169,19 @@ struct GenerateBatch: AsyncParsableCommand { format: job.request.outputFormat ) return Result { + try job.request.validate() try Output.checkWritable(paths, force: run.force) - if let duplicate = paths.first(where: { !claimed.insert($0).inserted }) { + if let duplicate = paths.first(where: { claimed.contains($0) }) { throw OutputError.exists("\(duplicate) (another job in this batch writes it)") } + claimed.formUnion(paths) return paths } } if run.dryRun { + var planned: [BatchDryRun.Job] = [] for (index, job) in parsed.enumerated() { - print("job \(index + 1):") switch plans[index] { case let .success(paths): let plan = DryRun( @@ -176,9 +189,21 @@ struct GenerateBatch: AsyncParsableCommand { request: job.request, outputs: paths ) - try printDryRun(plan, json: false) + planned.append(.init(index: index + 1, plan: plan, error: nil)) case let .failure(error): - print(" would fail: \(error.localizedDescription)") + planned.append(.init(index: index + 1, plan: nil, error: error.localizedDescription)) + } + } + if run.json { + try Output.printJSON(BatchDryRun(jobs: planned)) + } else { + for job in planned { + print("job \(job.index):") + if let plan = job.plan { + try printDryRun(plan, json: false) + } else if let error = job.error { + print(" would fail: \(error)") + } } } return diff --git a/Sources/Providers/API/OpenAI/Image Generation/Images API/ImageRequest.swift b/Sources/Providers/API/OpenAI/Image Generation/Images API/ImageRequest.swift index 810315c..78088e7 100644 --- a/Sources/Providers/API/OpenAI/Image Generation/Images API/ImageRequest.swift +++ b/Sources/Providers/API/OpenAI/Image Generation/Images API/ImageRequest.swift @@ -168,9 +168,17 @@ public struct ImageEditRequest: Sendable { guard !images.isEmpty else { throw ImageGenerationError.invalidParameter("an edit needs at least one image") } + guard images.count <= Self.maxImages else { + throw ImageGenerationError.invalidParameter( + "an edit takes at most \(Self.maxImages) images (got \(images.count))" + ) + } return try request.validate() } + /// The Images API accepts at most this many input images per edit. + public static let maxImages = 16 + /// The multipart body. `input_fidelity` is deliberately never sent: `gpt-image-2` /// rejects it and the guide doesn't document it for the 2.5 models. func multipartBody() -> MultipartFormData { diff --git a/Tests/ProvidersTests/OpenAI/Images/ImagesAPITests.swift b/Tests/ProvidersTests/OpenAI/Images/ImagesAPITests.swift index b6a3835..9578541 100644 --- a/Tests/ProvidersTests/OpenAI/Images/ImagesAPITests.swift +++ b/Tests/ProvidersTests/OpenAI/Images/ImagesAPITests.swift @@ -213,6 +213,16 @@ struct ImageEncodingTests { } } + @Test("an edit takes at most 16 images") + func editImageLimit() throws { + let image = ImageInput(data: Data([1]), filename: "a.png") + let request = ImageRequest(prompt: "p") + try ImageEditRequest(request: request, images: Array(repeating: image, count: 16)).validate() + #expect(throws: ImageGenerationError.self) { + try ImageEditRequest(request: request, images: Array(repeating: image, count: 17)).validate() + } + } + @Test("batch lines override the defaults, blank lines and comments are skipped") func batchParsing() throws { let jsonl = """ From 6806ff54b246a408c3ca6d18fe46cc3d98106767 Mon Sep 17 00:00:00 2001 From: Oliver Drobnik Date: Fri, 30 Oct 2026 09:33:47 +0100 Subject: [PATCH 3/3] Accept only canonical WxH sizes Co-Authored-By: Claude Sonnet 5.5 --- .../API/OpenAI/Image Generation/Images API/ImageSize.swift | 7 ++++--- Tests/ProvidersTests/OpenAI/Images/ImagesAPITests.swift | 4 +++- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/Sources/Providers/API/OpenAI/Image Generation/Images API/ImageSize.swift b/Sources/Providers/API/OpenAI/Image Generation/Images API/ImageSize.swift index 7e89a91..45e6999 100644 --- a/Sources/Providers/API/OpenAI/Image Generation/Images API/ImageSize.swift +++ b/Sources/Providers/API/OpenAI/Image Generation/Images API/ImageSize.swift @@ -64,10 +64,11 @@ public struct ImageSize: RawRepresentable, Hashable, Sendable, Codable, Expressi /// The width and height, or `nil` for `auto` and anything that isn't `WxH`. public var dimensions: (width: Int, height: Int)? { - let parts = rawValue.lowercased().split(separator: "x", omittingEmptySubsequences: false) + // Exactly the wire form: ASCII digits, a lowercase `x`, digits. + let parts = rawValue.split(separator: "x", omittingEmptySubsequences: false) guard parts.count == 2, - let width = Int(parts[0]), let height = Int(parts[1]), - parts.allSatisfy({ $0.allSatisfy(\.isASCII) }) + parts.allSatisfy({ !$0.isEmpty && $0.allSatisfy { ("0"..."9").contains($0) } }), + let width = Int(parts[0]), let height = Int(parts[1]) else { return nil } return (width, height) } diff --git a/Tests/ProvidersTests/OpenAI/Images/ImagesAPITests.swift b/Tests/ProvidersTests/OpenAI/Images/ImagesAPITests.swift index 9578541..31cef70 100644 --- a/Tests/ProvidersTests/OpenAI/Images/ImagesAPITests.swift +++ b/Tests/ProvidersTests/OpenAI/Images/ImagesAPITests.swift @@ -71,7 +71,9 @@ struct ImageSizeTests { @Test("dimensions parse WxH only") func dimensions() { #expect(ImageSize("2048x1152").dimensions?.width == 2048) - #expect(ImageSize("2048X1152").dimensions?.height == 1152) + #expect(ImageSize("2048X1152").dimensions == nil) + #expect(ImageSize("+1024x+1024").dimensions == nil) + #expect(ImageSize("1024x1024x2").dimensions == nil) #expect(ImageSize.auto.dimensions == nil) } }