Skip to content

Open source CapCut alternative.

TypeScript

feat: multimodal llm.generate for audio/video transcription

David Le0976e4204cfb
diff --git a/apps/Donkey/Sources/Donkey/GeminiLiveVoiceController.swift b/apps/Donkey/Sources/Donkey/GeminiLiveVoiceController.swift
index bbce41f0..ecf5dee3 100644
--- a/apps/Donkey/Sources/Donkey/GeminiLiveVoiceController.swift
+++ b/apps/Donkey/Sources/Donkey/GeminiLiveVoiceController.swift
@@ -82,6 +82,9 @@ final class GeminiLiveVoiceController {
let backend = DonkeyBackendInferenceClient(configuration: backendConfiguration)
let textGenerator = HostedTextGenerator(backend: backend)
services.textGenerator = { await textGenerator.generate($0) }
+ services.mediaGenerator = { prompt, fileURL, mimeType in
+ await textGenerator.generate(prompt, attachmentPath: fileURL, mimeType: mimeType)
+ }
// Web research goes through the backend on the service-account credential: search uses
// Google Search grounding; fetch returns the page as clean markdown (boilerplate stripped).
let hostedWebSearch = HostedWebSearch(backend: backend)
diff --git a/apps/Donkey/Sources/DonkeyAI/HostedTextGenerator.swift b/apps/Donkey/Sources/DonkeyAI/HostedTextGenerator.swift
index f244879d..9184c19c 100644
--- a/apps/Donkey/Sources/DonkeyAI/HostedTextGenerator.swift
+++ b/apps/Donkey/Sources/DonkeyAI/HostedTextGenerator.swift
@@ -1,6 +1,7 @@
import DonkeyContracts
import DonkeyHarness
import Foundation
+import UniformTypeIdentifiers
/// The model boundary behind the generic `llm.generate` harness tool: one prompt in, generated text
/// out. It composes, transforms, summarizes, or massages text through the same hosted inference route
@@ -53,4 +54,106 @@ public struct HostedTextGenerator: Sendable {
.trimmingCharacters(in: .whitespacesAndNewlines)
return (text?.isEmpty == false) ? text : nil
}
+
+ /// Runs `prompt` against a local media file (audio or video) — the multimodal arm of
+ /// `llm.generate`. The file is read and sent inline (base64) alongside the prompt, so the prompt
+ /// decides the output (transcribe to SRT, translate, summarize, answer a question). `mimeType` is
+ /// inferred from the extension when nil and must resolve to audio/* or video/*. The provider
+ /// chooses a model that handles audio/video — no model id leaks past this adapter.
+ ///
+ /// Inline base64 bounds the file size, so the call rejects oversized files (chunk them) and reads
+ /// off the cooperative executor so a large file never stalls the caller. A transcript cut off at
+ /// the model's token ceiling is surfaced as `.truncated`, not as a complete result.
+ public func generate(
+ _ prompt: String,
+ attachmentPath: URL,
+ mimeType: String? = nil
+ ) async -> HarnessMediaGenerationOutcome {
+ guard let resolvedMIME = (mimeType?.trimmingCharacters(in: .whitespacesAndNewlines).nilIfEmpty
+ ?? Self.inferredMIMEType(for: attachmentPath))?.lowercased() else {
+ return .unsupportedType("unknown")
+ }
+ let partType: String
+ if resolvedMIME.hasPrefix("video/") {
+ partType = "input_video"
+ } else if resolvedMIME.hasPrefix("audio/") {
+ partType = "input_audio"
+ } else {
+ return .unsupportedType(resolvedMIME)
+ }
+ // Reject an oversized file up front (with a chunk-it signal) rather than reading the whole
+ // thing just to overrun the request-body limit at the network.
+ if let size = Self.fileByteSize(attachmentPath), size > Self.maxInlineMediaBytes {
+ return .tooLarge(bytes: size, limit: Self.maxInlineMediaBytes)
+ }
+ // Read + base64-encode off the cooperative executor (the media arm is wired onto the always-on
+ // Live session path), and memory-map so the raw bytes aren't held resident alongside the
+ // base64 string.
+ let fileURL = attachmentPath
+ let base64: String
+ do {
+ base64 = try await Task.detached(priority: .utility) {
+ try Data(contentsOf: fileURL, options: .mappedIfSafe).base64EncodedString()
+ }.value
+ } catch {
+ return .unreadableFile
+ }
+ // Transcription output (an SRT/VTT transcript) runs much longer than a one-line text massage,
+ // and audio/video decoding takes longer than a text turn, so widen both ceilings here.
+ let mediaMaxOutputTokens = max(maxOutputTokens, 8_000)
+ let mediaTimeoutSeconds = max(timeoutSeconds, 180)
+ let request = RemoteInferenceResponseCreateRequest(
+ input: .array([
+ .object([
+ "role": .string("user"),
+ "content": .array([
+ .object(["type": .string("input_text"), "text": .string(prompt)]),
+ .object([
+ "type": .string(partType),
+ "dataBase64": .string(base64),
+ "mimeType": .string(resolvedMIME)
+ ])
+ ])
+ ])
+ ]),
+ store: false,
+ metadata: ["source": "hosted-text-generator", "prompt_version": "llm-generate-media-v1"],
+ parameters: [
+ // Low temperature keeps a transcript faithful to the audio rather than creative.
+ "temperature": .number(0.2),
+ "max_output_tokens": .number(Double(mediaMaxOutputTokens)),
+ "thinking_level": .string("low")
+ ]
+ )
+ let backend = self.backend
+ guard let response = try? await AIDeadline.enforce(seconds: mediaTimeoutSeconds, {
+ try await backend.createResponse(request)
+ }) else {
+ return .empty
+ }
+ // A transcript cut off at the token ceiling comes back non-empty but incomplete; surface it as
+ // truncated so the caller re-chunks instead of writing a silently-partial subtitle file.
+ if let finishReason = RemoteInferenceResponseHelpers.providerFinishReason(from: response),
+ finishReason.uppercased().contains("MAX_TOKENS") {
+ return .truncated
+ }
+ let text = RemoteInferenceResponseHelpers.outputText(from: response)?
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ guard let text, !text.isEmpty else { return .empty }
+ return .text(text)
+ }
+
+ private static let maxInlineMediaBytes = 14 * 1024 * 1024
+
+ private static func inferredMIMEType(for url: URL) -> String? {
+ UTType(filenameExtension: url.pathExtension.lowercased())?.preferredMIMEType
+ }
+
+ private static func fileByteSize(_ url: URL) -> Int? {
+ (try? url.resourceValues(forKeys: [.fileSizeKey]))?.fileSize
+ }
+}
+
+private extension String {
+ var nilIfEmpty: String? { isEmpty ? nil : self }
}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift
index 2aaf5b1b..496b0b89 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift
@@ -246,6 +246,119 @@ struct GenericHarnessTests {
try? FileManager.default.removeItem(atPath: path)
}
+ @Test
+ func llmGenerateRoutesToTheMediaBoundaryWhenGivenAFilePath() async throws {
+ let audio = FileManager.default.temporaryDirectory
+ .appendingPathComponent("donkey-media-test-\(UUID().uuidString).mp3")
+ try Data([0x00, 0x01, 0x02]).write(to: audio)
+ defer { try? FileManager.default.removeItem(at: audio) }
+
+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors(
+ services: HarnessBuiltInToolServices(
+ // Fails if the text path is taken by mistake.
+ textGenerator: { _ in "TEXT PATH" },
+ mediaGenerator: { prompt, file, mimeType in
+ .text("SRT for \(file.lastPathComponent) mime=\(mimeType ?? "nil"): \(prompt)")
+ }
+ )
+ )
+ let result = await registry.execute(
+ HarnessToolCall(name: "llm.generate", input: [
+ "prompt": "transcribe to SRT",
+ "filePath": audio.path,
+ "mimeType": "audio/mpeg"
+ ]),
+ taskID: "t", worldModel: HarnessWorldModel(), grantedPermissions: []
+ )
+ #expect(result.status == .succeeded)
+ let text = result.metadata["text"]
+ // Routed to the media boundary, which saw the file and the forwarded mimeType.
+ #expect(text?.contains("SRT for \(audio.lastPathComponent)") == true)
+ #expect(text?.contains("mime=audio/mpeg") == true)
+ #expect(text?.contains("transcribe to SRT") == true)
+ #expect(text?.contains("TEXT PATH") == false)
+ }
+
+ @Test
+ func llmGenerateSurfacesATruncatedTranscriptAsAFailure() async throws {
+ let audio = FileManager.default.temporaryDirectory
+ .appendingPathComponent("donkey-media-test-\(UUID().uuidString).mp3")
+ try Data([0x00, 0x01]).write(to: audio)
+ defer { try? FileManager.default.removeItem(at: audio) }
+
+ // A transcript cut off at the token cap must not be written as a complete result.
+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors(
+ services: HarnessBuiltInToolServices(mediaGenerator: { _, _, _ in .truncated })
+ )
+ let result = await registry.execute(
+ HarnessToolCall(name: "llm.generate", input: ["prompt": "transcribe", "filePath": audio.path]),
+ taskID: "t", worldModel: HarnessWorldModel(), grantedPermissions: []
+ )
+ #expect(result.status == .failed)
+ #expect(result.metadata["reason"] == "mediaOutputTruncated")
+ }
+
+ @Test
+ func llmGenerateMapsMediaOutcomesToDistinctReasons() async throws {
+ let audio = FileManager.default.temporaryDirectory
+ .appendingPathComponent("donkey-media-test-\(UUID().uuidString).mp3")
+ try Data([0x00]).write(to: audio)
+ defer { try? FileManager.default.removeItem(at: audio) }
+
+ // Each media failure mode reaches the planner as its own reason rather than an opaque nil.
+ let cases: [(HarnessMediaGenerationOutcome, String)] = [
+ (.unreadableFile, "mediaFileUnreadable"),
+ (.tooLarge(bytes: 20_000_000, limit: 14_000_000), "mediaFileTooLarge"),
+ (.unsupportedType("image/png"), "mediaUnsupportedType"),
+ (.empty, "emptyGeneration")
+ ]
+ for (outcome, expectedReason) in cases {
+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors(
+ services: HarnessBuiltInToolServices(mediaGenerator: { _, _, _ in outcome })
+ )
+ let result = await registry.execute(
+ HarnessToolCall(name: "llm.generate", input: ["prompt": "transcribe", "filePath": audio.path]),
+ taskID: "t", worldModel: HarnessWorldModel(), grantedPermissions: []
+ )
+ #expect(result.status == .failed)
+ #expect(result.metadata["reason"] == expectedReason)
+ }
+ }
+
+ @Test
+ func llmGenerateFailsCleanlyWithoutAMediaBoundaryWhenGivenAFilePath() async throws {
+ let audio = FileManager.default.temporaryDirectory
+ .appendingPathComponent("donkey-media-test-\(UUID().uuidString).mp3")
+ try Data([0x00]).write(to: audio)
+ defer { try? FileManager.default.removeItem(at: audio) }
+
+ // Only the text boundary is wired — a media call must not silently fall back to it.
+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors(
+ services: HarnessBuiltInToolServices(textGenerator: { _ in "text" })
+ )
+ let result = await registry.execute(
+ HarnessToolCall(name: "llm.generate", input: ["prompt": "transcribe", "filePath": audio.path]),
+ taskID: "t", worldModel: HarnessWorldModel(), grantedPermissions: []
+ )
+ #expect(result.status == .failed)
+ #expect(result.metadata["reason"] == "mediaGeneratorUnavailable")
+ }
+
+ @Test
+ func llmGenerateRejectsAMissingMediaFile() async {
+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors(
+ services: HarnessBuiltInToolServices(mediaGenerator: { _, _, _ in .text("unused") })
+ )
+ let result = await registry.execute(
+ HarnessToolCall(name: "llm.generate", input: [
+ "prompt": "transcribe",
+ "filePath": "/no/such/donkey-media-\(UUID().uuidString).mp3"
+ ]),
+ taskID: "t", worldModel: HarnessWorldModel(), grantedPermissions: []
+ )
+ #expect(result.status == .invalidInput)
+ }
+
@Test
func webSearchReturnsRankedResultsFromTheSearcher() async {
let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors(
diff --git a/site/src/lib/inference/adapters/gemini-computer-use.ts b/site/src/lib/inference/adapters/gemini-computer-use.ts
index 19844e2f..3e56d2aa 100644
--- a/site/src/lib/inference/adapters/gemini-computer-use.ts
+++ b/site/src/lib/inference/adapters/gemini-computer-use.ts
@@ -316,6 +316,15 @@ function partFromValue(value: JsonValue): JsonObject {
return imagePart(value);
}
+ if (
+ value.type === "input_audio" ||
+ value.type === "audio" ||
+ value.type === "input_video" ||
+ value.type === "video"
+ ) {
+ return mediaPart(value);
+ }
+
const text = stringValue(value.text);
if (text) {
return { text };
@@ -356,6 +365,56 @@ function imagePart(value: JsonObject): JsonObject {
return { text: JSON.stringify(value) };
}
+// Audio/video content part. Mirrors imagePart: inline base64 becomes inlineData; a URI becomes
+// fileData. On Vertex, fileData.fileUri must be a gs:// Cloud Storage URI (or, for video, a YouTube
+// URL) — a plain https object URL is rejected by Vertex at request time. The gs:// form backs the
+// staged long-media path. Vertex reads audio and video the same way it reads images.
+function mediaPart(value: JsonObject): JsonObject {
+ const isVideo = value.type === "input_video" || value.type === "video";
+ const mimeType =
+ stringValue(value.mime_type) ||
+ stringValue(value.mimeType) ||
+ (isVideo ? "video/mp4" : "audio/mpeg");
+ const base64 =
+ stringValue(value.dataBase64) ||
+ stringValue(value.data_base64) ||
+ stringValue(value.audio_base64) ||
+ stringValue(value.video_base64);
+ if (base64) {
+ return {
+ inlineData: {
+ mimeType,
+ data: base64,
+ },
+ };
+ }
+
+ const fileURI =
+ stringValue(value.fileUri) ||
+ stringValue(value.file_uri) ||
+ stringValue(value.url);
+ if (fileURI?.startsWith("data:")) {
+ const inline = dataURLToInlineData(fileURI);
+ if (inline) {
+ return inline;
+ }
+ }
+
+ if (fileURI) {
+ return {
+ fileData: {
+ mimeType,
+ fileUri: fileURI,
+ },
+ };
+ }
+
+ // A media part with no recognized base64 or URI key: emit a short marker rather than
+ // JSON.stringify(value), which would inline a multi-megabyte base64 blob under an unexpected key
+ // as prompt text and blow the token budget.
+ return { text: "[unsupported media part: no inline data or file URI]" };
+}
+
function functionResponsePart(value: JsonObject): JsonObject {
const name = stringValue(value.name) || "unknown_function";
const response = isJsonObject(value.response) ? value.response : {};