Open source CapCut alternative.
TypeScript
refactor(app): extract shared Gemini generateContent request helpers
David Ledefe1e5a67e5
diff --git a/apps/Donkey/Sources/DonkeyAI/GeminiGenerateContent.swift b/apps/Donkey/Sources/DonkeyAI/GeminiGenerateContent.swiftindex e55ecaa7..02df5da7 100644--- a/apps/Donkey/Sources/DonkeyAI/GeminiGenerateContent.swift+++ b/apps/Donkey/Sources/DonkeyAI/GeminiGenerateContent.swift@@ -21,6 +21,39 @@ public enum GeminiGenerateContent {return trimmedValue?.isEmpty == false ? trimmedValue : nil}+ /// Serialize a `generateContent` request body: a single user turn whose `parts`+ /// are supplied by the caller (text / inlineData), plus the caller's+ /// `generationConfig` (temperature, response schema, thinking level, …).+ public static func requestBody(+ parts: [[String: Any]],+ generationConfig: [String: Any]+ ) throws -> Data {+ let body: [String: Any] = [+ "contents": [[+ "role": "user",+ "parts": parts+ ]],+ "generationConfig": generationConfig+ ]+ return try JSONSerialization.data(withJSONObject: body)+ }++ /// A part carrying a base64 inline blob (image/audio) with its MIME type.+ public static func inlineDataPart(mimeType: String, base64: String) -> [String: Any] {+ ["inlineData": ["mimeType": mimeType, "data": base64]]+ }++ /// Build the Vertex `generateContent` POST request: bearer auth + JSON content+ /// type, body already serialized.+ public static func vertexRequest(url: URL, bearerToken: String, body: Data) -> URLRequest {+ var request = URLRequest(url: url)+ request.httpMethod = "POST"+ request.setValue("Bearer \(bearerToken)", forHTTPHeaderField: "Authorization")+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")+ request.httpBody = body+ return request+ }+/// The text of the first candidate, concatenating its content parts. Returns/// nil when the response has no candidate text.public static func candidateText(_ data: Data) -> String? {diff --git a/apps/Donkey/Sources/DonkeyAI/GeminiVertexVisionBoxPlanner.swift b/apps/Donkey/Sources/DonkeyAI/GeminiVertexVisionBoxPlanner.swiftindex cf8e3369..98a24b5f 100644--- a/apps/Donkey/Sources/DonkeyAI/GeminiVertexVisionBoxPlanner.swift+++ b/apps/Donkey/Sources/DonkeyAI/GeminiVertexVisionBoxPlanner.swift@@ -36,60 +36,36 @@ public enum GeminiVertexVisionBoxPlanner {window: WindowTargetBounds,urlSession: URLSession = .shared) async throws -> VisionBoxAction {- guard let url = GeminiGenerateContent.vertexURL(- project: auth.project,- location: auth.location,- model: model- ) else {- throw GeminiVertexVisionPlanner.PlannerError.requestFailed(status: -1, body: "bad url")- }-let width = Int(compressed.pixelSize.width.rounded())let height = Int(compressed.pixelSize.height.rounded())- let body: [String: Any] = [- "contents": [[- "role": "user",- "parts": [- ["text": prompt(goal: goal, app: appName, width: width, height: height, history: history, appGuidance: appGuidance)],- ["inlineData": ["mimeType": compressed.contentType, "data": compressed.data.base64EncodedString()]]- ]- ]],- "generationConfig": [- "temperature": 0,- "responseMimeType": "application/json",- // gemini-3.5-flash takes thinking_level (the integer thinkingBudget is ignored on 3.x).- // No maxOutputTokens is set, so the large default leaves ample room for medium thinking- // plus the small box JSON. Vertex takes the proto enum name (uppercase).- "thinkingConfig": ["thinkingLevel": "MEDIUM"],- "responseSchema": [- "type": "object",- "properties": [- "action": ["type": "string", "enum": ["click", "type", "key", "done"]],- "box": ["type": "array", "items": ["type": "number"]],- "text": ["type": "string"],- "reason": ["type": "string"]- ],- "required": ["action", "reason"]- ]+ let generationConfig: [String: Any] = [+ "temperature": 0,+ "responseMimeType": "application/json",+ // gemini-3.5-flash takes thinking_level (the integer thinkingBudget is ignored on 3.x).+ // No maxOutputTokens is set, so the large default leaves ample room for medium thinking+ // plus the small box JSON. Vertex takes the proto enum name (uppercase).+ "thinkingConfig": ["thinkingLevel": "MEDIUM"],+ "responseSchema": [+ "type": "object",+ "properties": [+ "action": ["type": "string", "enum": ["click", "type", "key", "done"]],+ "box": ["type": "array", "items": ["type": "number"]],+ "text": ["type": "string"],+ "reason": ["type": "string"]+ ],+ "required": ["action", "reason"]]]- var request = URLRequest(url: url)- request.httpMethod = "POST"- request.setValue("Bearer \(auth.token)", forHTTPHeaderField: "Authorization")- request.setValue("application/json", forHTTPHeaderField: "Content-Type")- request.httpBody = try JSONSerialization.data(withJSONObject: body)-- let (data, response) = try await urlSession.data(for: request)- let status = (response as? HTTPURLResponse)?.statusCode ?? -1- guard status == 200 else {- throw GeminiVertexVisionPlanner.PlannerError.requestFailed(status: status, body: String(data: data, encoding: .utf8) ?? "")- }- guard let text = GeminiGenerateContent.candidateText(data), !text.isEmpty else {- throw GeminiVertexVisionPlanner.PlannerError.noOutputText(body: String(data: data, encoding: .utf8) ?? "")- }- let json = DebugUIInspectionResponseDecoder.jsonObjectSubstring(text)- var action = try JSONDecoder().decode(VisionBoxAction.self, from: Data(json.utf8))+ var action = try await GeminiVertexVisionPlanner.generateAction(+ auth: auth,+ model: model,+ prompt: prompt(goal: goal, app: appName, width: width, height: height, history: history, appGuidance: appGuidance),+ compressed: compressed,+ generationConfig: generationConfig,+ urlSession: urlSession,+ decode: VisionBoxAction.self+ )if action.action == "click", let box = action.box {let points = VisionBoxGeometry.screenPoints(box, window: window)action.screenPoints = points.isEmpty ? nil : pointsdiff --git a/apps/Donkey/Sources/DonkeyAI/GeminiVertexVisionPlanner.swift b/apps/Donkey/Sources/DonkeyAI/GeminiVertexVisionPlanner.swiftindex c2f08445..4ac989a1 100644--- a/apps/Donkey/Sources/DonkeyAI/GeminiVertexVisionPlanner.swift+++ b/apps/Donkey/Sources/DonkeyAI/GeminiVertexVisionPlanner.swift@@ -59,51 +59,74 @@ public enum GeminiVertexVisionPlanner {window: WindowTargetBounds,urlSession: URLSession = .shared) async throws -> VisionActionPlanner.PlannedAction {- guard let url = GeminiGenerateContent.vertexURL(- project: auth.project,- location: auth.location,- model: model- ) else { throw PlannerError.requestFailed(status: -1, body: "bad url") }-let width = Int(compressed.pixelSize.width.rounded())let height = Int(compressed.pixelSize.height.rounded())let prompt = VisionActionPlanner.visionPrompt(goal: goal, app: appName, width: width, height: height, history: history, appGuidance: appGuidance)- let body: [String: Any] = [- "contents": [[- "role": "user",- "parts": [- ["text": prompt],- ["inlineData": ["mimeType": compressed.contentType, "data": compressed.data.base64EncodedString()]]- ]- ]],- "generationConfig": [- "temperature": 0,- "responseMimeType": "application/json",- // gemini-3.5-flash takes thinking_level (the integer thinkingBudget is ignored on 3.x).- // No maxOutputTokens is set, so the large default leaves ample room for medium thinking- // plus the small action JSON. Vertex takes the proto enum name (uppercase).- "thinkingConfig": ["thinkingLevel": "MEDIUM"],- "responseSchema": [- "type": "object",- "properties": [- "action": ["type": "string", "enum": ["click", "type", "key", "done"]],- "x": ["type": "number"],- "y": ["type": "number"],- "text": ["type": "string"],- "reason": ["type": "string"]- ],- "required": ["action", "x", "y", "reason"]- ]+ let generationConfig: [String: Any] = [+ "temperature": 0,+ "responseMimeType": "application/json",+ // gemini-3.5-flash takes thinking_level (the integer thinkingBudget is ignored on 3.x).+ // No maxOutputTokens is set, so the large default leaves ample room for medium thinking+ // plus the small action JSON. Vertex takes the proto enum name (uppercase).+ "thinkingConfig": ["thinkingLevel": "MEDIUM"],+ "responseSchema": [+ "type": "object",+ "properties": [+ "action": ["type": "string", "enum": ["click", "type", "key", "done"]],+ "x": ["type": "number"],+ "y": ["type": "number"],+ "text": ["type": "string"],+ "reason": ["type": "string"]+ ],+ "required": ["action", "x", "y", "reason"]]]- var request = URLRequest(url: url)- request.httpMethod = "POST"- request.setValue("Bearer \(auth.token)", forHTTPHeaderField: "Authorization")- request.setValue("application/json", forHTTPHeaderField: "Content-Type")- request.httpBody = try JSONSerialization.data(withJSONObject: body)+ var action = try await generateAction(+ auth: auth,+ model: model,+ prompt: prompt,+ compressed: compressed,+ generationConfig: generationConfig,+ urlSession: urlSession,+ decode: VisionActionPlanner.PlannedAction.self+ )+ action.screenPoint = VisionActionPlanner.screenPoint(action: action, window: window)+ return action+ }++ /// Shared Vertex vision turn: resolve the endpoint, post the prompt + screenshot+ /// with the caller's `generationConfig` (response schema, thinking level), guard+ /// status/candidate-text, then decode the JSON substring into `Output`. The two+ /// planners differ only in their schema and decoded shape, which are passed in.+ static func generateAction<Output: Decodable>(+ auth: VertexAuth,+ model: String,+ prompt: String,+ compressed: CompressedScreenshot,+ generationConfig: [String: Any],+ urlSession: URLSession,+ decode: Output.Type+ ) async throws -> Output {+ guard let url = GeminiGenerateContent.vertexURL(+ project: auth.project,+ location: auth.location,+ model: model+ ) else { throw PlannerError.requestFailed(status: -1, body: "bad url") }++ let body = try GeminiGenerateContent.requestBody(+ parts: [+ ["text": prompt],+ GeminiGenerateContent.inlineDataPart(+ mimeType: compressed.contentType,+ base64: compressed.data.base64EncodedString()+ )+ ],+ generationConfig: generationConfig+ )+ let request = GeminiGenerateContent.vertexRequest(url: url, bearerToken: auth.token, body: body)let (data, response) = try await urlSession.data(for: request)let status = (response as? HTTPURLResponse)?.statusCode ?? -1@@ -114,9 +137,7 @@ public enum GeminiVertexVisionPlanner {throw PlannerError.noOutputText(body: String(data: data, encoding: .utf8) ?? "")}let json = DebugUIInspectionResponseDecoder.jsonObjectSubstring(text)- var action = try JSONDecoder().decode(VisionActionPlanner.PlannedAction.self, from: Data(json.utf8))- action.screenPoint = VisionActionPlanner.screenPoint(action: action, window: window)- return action+ return try JSONDecoder().decode(Output.self, from: Data(json.utf8))}}