Skip to content

Open source CapCut alternative.

TypeScript

refactor(app): extract shared Gemini generateContent endpoint and response parsing

David Lec10ec83afbfa
diff --git a/apps/Donkey/Sources/DonkeyAI/GeminiGenerateContent.swift b/apps/Donkey/Sources/DonkeyAI/GeminiGenerateContent.swift
new file mode 100644
index 00000000..e55ecaa7
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyAI/GeminiGenerateContent.swift
@@ -0,0 +1,35 @@
+import Foundation
+
+/// Small shared plumbing for Gemini `generateContent` calls, reused by the Vertex
+/// vision planners and the voice transcription runtime so each feature builds its
+/// own request body but not the endpoint URL or response parsing.
+public enum GeminiGenerateContent {
+ /// Vertex AI `generateContent` endpoint for a publisher model.
+ public static func vertexURL(project: String, location: String, model: String) -> URL? {
+ let host = location == "global"
+ ? "aiplatform.googleapis.com"
+ : "\(location)-aiplatform.googleapis.com"
+ return URL(
+ string: "https://\(host)/v1/projects/\(project)/locations/\(location)/publishers/google/models/\(model):generateContent"
+ )
+ }
+
+ /// Trim whitespace and treat empty/absent as nil — the env-reading idiom used
+ /// when pulling Gemini config (API key, model) out of the environment.
+ public static func trimmed(_ value: String?) -> String? {
+ let trimmedValue = value?.trimmingCharacters(in: .whitespacesAndNewlines)
+ return trimmedValue?.isEmpty == false ? trimmedValue : nil
+ }
+
+ /// 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? {
+ guard let root = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
+ let candidates = root["candidates"] as? [[String: Any]],
+ let content = candidates.first?["content"] as? [String: Any],
+ let parts = content["parts"] as? [[String: Any]]
+ else { return nil }
+ let text = parts.compactMap { $0["text"] as? String }.joined()
+ return text.isEmpty ? nil : text
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyAI/GeminiVertexVisionBoxPlanner.swift b/apps/Donkey/Sources/DonkeyAI/GeminiVertexVisionBoxPlanner.swift
index 40179dcf..cf8e3369 100644
--- a/apps/Donkey/Sources/DonkeyAI/GeminiVertexVisionBoxPlanner.swift
+++ b/apps/Donkey/Sources/DonkeyAI/GeminiVertexVisionBoxPlanner.swift
@@ -36,9 +36,11 @@ public enum GeminiVertexVisionBoxPlanner {
window: WindowTargetBounds,
urlSession: URLSession = .shared
) async throws -> VisionBoxAction {
- let host = auth.location == "global" ? "aiplatform.googleapis.com" : "\(auth.location)-aiplatform.googleapis.com"
- let endpoint = "https://\(host)/v1/projects/\(auth.project)/locations/\(auth.location)/publishers/google/models/\(model):generateContent"
- guard let url = URL(string: endpoint) else {
+ guard let url = GeminiGenerateContent.vertexURL(
+ project: auth.project,
+ location: auth.location,
+ model: model
+ ) else {
throw GeminiVertexVisionPlanner.PlannerError.requestFailed(status: -1, body: "bad url")
}
@@ -83,7 +85,7 @@ public enum GeminiVertexVisionBoxPlanner {
guard status == 200 else {
throw GeminiVertexVisionPlanner.PlannerError.requestFailed(status: status, body: String(data: data, encoding: .utf8) ?? "")
}
- guard let text = outputText(data), !text.isEmpty else {
+ guard let text = GeminiGenerateContent.candidateText(data), !text.isEmpty else {
throw GeminiVertexVisionPlanner.PlannerError.noOutputText(body: String(data: data, encoding: .utf8) ?? "")
}
let json = DebugUIInspectionResponseDecoder.jsonObjectSubstring(text)
@@ -95,15 +97,6 @@ public enum GeminiVertexVisionBoxPlanner {
return action
}
- private static func outputText(_ data: Data) -> String? {
- guard let root = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
- let candidates = root["candidates"] as? [[String: Any]],
- let content = candidates.first?["content"] as? [String: Any],
- let parts = content["parts"] as? [[String: Any]]
- else { return nil }
- return parts.compactMap { $0["text"] as? String }.joined()
- }
-
private static func prompt(goal: String, app: String, width: Int, height: Int, history: [String], appGuidance: String?) -> String {
let historyBlock = history.isEmpty
? "This is the first action; nothing has been done yet."
diff --git a/apps/Donkey/Sources/DonkeyAI/GeminiVertexVisionPlanner.swift b/apps/Donkey/Sources/DonkeyAI/GeminiVertexVisionPlanner.swift
index f2494f82..c2f08445 100644
--- a/apps/Donkey/Sources/DonkeyAI/GeminiVertexVisionPlanner.swift
+++ b/apps/Donkey/Sources/DonkeyAI/GeminiVertexVisionPlanner.swift
@@ -59,9 +59,11 @@ public enum GeminiVertexVisionPlanner {
window: WindowTargetBounds,
urlSession: URLSession = .shared
) async throws -> VisionActionPlanner.PlannedAction {
- let host = auth.location == "global" ? "aiplatform.googleapis.com" : "\(auth.location)-aiplatform.googleapis.com"
- let endpoint = "https://\(host)/v1/projects/\(auth.project)/locations/\(auth.location)/publishers/google/models/\(model):generateContent"
- guard let url = URL(string: endpoint) else { throw PlannerError.requestFailed(status: -1, body: "bad url") }
+ 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())
@@ -108,7 +110,7 @@ public enum GeminiVertexVisionPlanner {
guard status == 200 else {
throw PlannerError.requestFailed(status: status, body: String(data: data, encoding: .utf8) ?? "")
}
- guard let text = outputText(data), !text.isEmpty else {
+ guard let text = GeminiGenerateContent.candidateText(data), !text.isEmpty else {
throw PlannerError.noOutputText(body: String(data: data, encoding: .utf8) ?? "")
}
let json = DebugUIInspectionResponseDecoder.jsonObjectSubstring(text)
@@ -117,12 +119,4 @@ public enum GeminiVertexVisionPlanner {
return action
}
- private static func outputText(_ data: Data) -> String? {
- guard let root = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
- let candidates = root["candidates"] as? [[String: Any]],
- let content = candidates.first?["content"] as? [String: Any],
- let parts = content["parts"] as? [[String: Any]]
- else { return nil }
- return parts.compactMap { $0["text"] as? String }.joined()
- }
}