Files
shumai/packages/agent/src/activities/ai.ts
T
Yiling-J aabf59cbe7 refactor(transcode): offload video embedding chunk slicing to transcode queue (#539)
* refactor(transcode): offload video embedding chunk slicing to transcode queue

* fix(transcode): address video chunk offloading review findings
2026-11-22 11:52:58 +08:00

691 lines
20 KiB
TypeScript

import { GoogleGenAI } from '@google/genai'
import { s3Service } from '@shumai/core/src/s3/s3'
import { textEmbeddingService } from '@shumai/core/src/search/text-embedding'
import { prisma, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
import {
ApplicationFailure,
defineStep,
getLocalTaskAbortSignal,
isDbosWorkflowCancelledError,
workflowService,
} from '@shumai/workflow-core'
import sharp from 'sharp'
export interface Usage {
inputTokens: number
outputTokens: number
model: string
}
export interface GeneratedEmbedding {
embedding: number[]
startTime?: number
endTime?: number
}
async function generateMultimodalEmbedding(
ai: GoogleGenAI,
buffer: Buffer,
mimeType: string,
): Promise<number[]> {
const response = await ai.models.embedContent({
model: 'gemini-embedding-2',
contents: [
{
inlineData: {
data: buffer.toString('base64'),
mimeType,
},
},
],
config: {
outputDimensionality: 1536,
},
})
const values = response.embeddings?.[0]?.values
if (!values) {
throw new Error('No embedding values returned from gemini-embedding-2')
}
return values
}
interface OpenAiEmbeddingItem {
type?: string
// eslint-disable-next-line @typescript-eslint/naming-convention
image_url?: {
url: string
}
}
async function callGemmaEmbeddingServer(input: string | OpenAiEmbeddingItem[]): Promise<{
embedding: number[]
usage: Usage
}> {
const rawBaseUrl = process.env.GEMMA_EMBEDDING_OPENAI_BASE_URL || 'http://localhost:9379/v1'
const normalized = rawBaseUrl.replace(/\/+$/, '')
const endpoint = normalized.endsWith('/embeddings')
? normalized
: normalized.endsWith('/v1')
? `${normalized}/embeddings`
: `${normalized}/v1/embeddings`
const response = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: 'embeddinggemma-2',
input,
}),
})
if (!response.ok) {
const errorText = await response.text()
throw ApplicationFailure.create({
message: `Embedding server returned status ${response.status}: ${errorText}`,
nonRetryable: false,
})
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- response json shape is dynamic from external endpoint
const json: any = await response.json()
const embedding = json.data?.[0]?.embedding
if (!embedding || !Array.isArray(embedding)) {
throw ApplicationFailure.create({
message: 'Invalid embedding returned from embedding server',
nonRetryable: false,
})
}
return {
embedding,
usage: {
model: json.model || 'gemma-embedding-2-openai',
inputTokens: json.usage?.prompt_tokens ?? 0,
outputTokens: 0,
},
}
}
export interface GenerateTextEmbeddingParams {
text: string
teamId: string
}
export const generateTextEmbeddingActivity = defineStep(
async function generateTextEmbeddingActivity(params: GenerateTextEmbeddingParams): Promise<{
embedding: number[]
usage: Usage
}> {
const provider = process.env.EMBEDDING_PROVIDER || 'gemini-embedding-2'
if (provider !== 'gemma-embedding-2-openai' && !process.env.GEMINI_API_KEY) {
throw ApplicationFailure.create({
message: 'GEMINI_API_KEY environment variable is not configured',
nonRetryable: true,
})
}
try {
const result = await textEmbeddingService.generateEmbedding(params.text, {
teamId: params.teamId,
skipCache: true,
})
return {
embedding: result.embedding,
usage: {
model: result.usage?.model || provider,
inputTokens: result.usage?.inputTokens ?? 0,
outputTokens: result.usage?.outputTokens ?? 0,
},
}
} catch (err) {
if (err instanceof ApplicationFailure) {
throw err
}
throw ApplicationFailure.create({
message: err instanceof Error ? err.message : String(err),
nonRetryable: false,
})
}
},
)
export const getEmbeddingContextActivity = defineStep(
async function getEmbeddingContextActivity(params: { teamId: string; assetId: string }) {
const team = await prisma.team.findUnique({
where: { id: params.teamId },
})
if (!team) {
throw ApplicationFailure.create({ message: 'failed to get team', nonRetryable: true })
}
const agent = await prisma.agent.findFirst({
where: {
type: 'embedding',
enabled: true,
user: { teamMembers: { some: { teamId: params.teamId } } },
},
})
if (!agent || process.env.ENABLE_EMBEDDING_AGENT === 'false') {
throw ApplicationFailure.create({
message: 'embedding feature is disabled or agent not found',
nonRetryable: true,
})
}
const asset = await prisma.asset.findUnique({
where: { id: params.assetId },
include: { storageKey: true },
})
if (!asset) {
throw ApplicationFailure.create({ message: 'failed to get asset', nonRetryable: true })
}
if (!asset.mediaType) {
throw ApplicationFailure.create({ message: 'asset has no media type', nonRetryable: true })
}
const parsedDuration = parseFloat(process.env.EMBEDDING_CHUNK_DURATION || '')
const chunkDuration =
Number.isFinite(parsedDuration) && parsedDuration > 0 ? parsedDuration : 60.0
const parsedOverlap = parseFloat(process.env.EMBEDDING_CHUNK_OVERLAP || '')
const chunkOverlap = Number.isFinite(parsedOverlap) && parsedOverlap >= 0 ? parsedOverlap : 5.0
const embeddingProvider = process.env.EMBEDDING_PROVIDER || 'gemini-embedding-2'
const existingEmbeddings = await prisma.$queryRaw<ExistingAssetEmbeddingInfo[]>`
SELECT
id,
start_time as "startTime",
end_time as "endTime",
(embedding IS NOT NULL) as "has1536",
(embedding_768 IS NOT NULL) as "has768"
FROM asset_embeddings
WHERE asset_id = ${params.assetId}
`
return {
agent,
asset,
chunkDuration,
chunkOverlap,
embeddingProvider,
existingEmbeddings,
}
},
)
export interface ExistingAssetEmbeddingInfo {
id: string
startTime: number | null
endTime: number | null
has1536: boolean
has768: boolean
}
export const deleteAssetEmbeddingsActivity = defineStep(
async function deleteAssetEmbeddingsActivity(params: { assetId: string; ids?: string[] }) {
if (params.ids && params.ids.length > 0) {
await prisma.assetEmbedding.deleteMany({
where: {
assetId: params.assetId,
id: { in: params.ids },
},
})
} else {
await prisma.assetEmbedding.deleteMany({
where: {
assetId: params.assetId,
},
})
}
},
)
export const saveAssetEmbeddingsActivity = defineStep(
async function saveAssetEmbeddingsActivity(params: {
assetId: string
embeddings: Array<{
embedding: number[]
startTime?: number
endTime?: number
}>
}) {
for (const item of params.embeddings) {
const embVec = JSON.stringify(item.embedding)
const is768 = item.embedding.length === 768
if (item.startTime !== undefined && item.endTime !== undefined) {
if (is768) {
await prisma.$executeRaw`
INSERT INTO asset_embeddings (id, asset_id, embedding_768, start_time, end_time, updated_at)
VALUES (gen_random_uuid()::text, ${params.assetId}, ${embVec}::vector, ${item.startTime}, ${item.endTime}, NOW())
`
} else {
await prisma.$executeRaw`
INSERT INTO asset_embeddings (id, asset_id, embedding, start_time, end_time, updated_at)
VALUES (gen_random_uuid()::text, ${params.assetId}, ${embVec}::vector, ${item.startTime}, ${item.endTime}, NOW())
`
}
} else {
if (is768) {
await prisma.$executeRaw`
INSERT INTO asset_embeddings (id, asset_id, embedding_768, updated_at)
VALUES (gen_random_uuid()::text, ${params.assetId}, ${embVec}::vector, NOW())
`
} else {
await prisma.$executeRaw`
INSERT INTO asset_embeddings (id, asset_id, embedding, updated_at)
VALUES (gen_random_uuid()::text, ${params.assetId}, ${embVec}::vector, NOW())
`
}
}
}
},
)
export interface GenerateImageEmbeddingParams {
teamId: string
assetKey: string
mediaType: string
}
export const generateImageEmbeddingActivity = defineStep(
async function generateImageEmbeddingActivity(params: GenerateImageEmbeddingParams): Promise<{
embedding: number[]
usage: Usage
}> {
const provider = process.env.EMBEDDING_PROVIDER || 'gemini-embedding-2'
const { buffer: data } = await s3Service.getObject(
process.env.S3_BUCKET || 'shumai',
params.assetKey,
)
if (provider === 'gemma-embedding-2-openai') {
let imgData = data
let mimeType = params.mediaType || 'image/jpeg'
if (mimeType !== 'image/jpeg' && mimeType !== 'image/png') {
imgData = await sharp(data).jpeg().toBuffer()
mimeType = 'image/jpeg'
}
return callGemmaEmbeddingServer([
{
type: 'image_url',
// eslint-disable-next-line @typescript-eslint/naming-convention
image_url: {
url: `data:${mimeType};base64,${imgData.toString('base64')}`,
},
},
])
}
const apiKey = process.env.GEMINI_API_KEY
if (!apiKey) {
throw ApplicationFailure.create({
message: 'GEMINI_API_KEY environment variable is not configured',
nonRetryable: true,
})
}
const resolvedApiKey = process.env[apiKey] || apiKey
const ai = new GoogleGenAI({ apiKey: resolvedApiKey })
const usage: Usage = {
model: 'gemini-embedding-2',
inputTokens: 0,
outputTokens: 0,
}
const embVec = await generateMultimodalEmbedding(ai, data, params.mediaType)
return {
embedding: embVec,
usage,
}
},
)
/**
* Standard aspect ratios for video embedding:
* 1:1, 4:3, 3:4, 16:9, 9:16, 21:9 (including ultrawide 64:27), and 9:21.
*
* For these standard ratios, 15 frames guarantees that total input tokens stay strictly
* within the 2048 token signature bucket (<= 1982 tokens). For non-standard or custom
* aspect ratios (e.g. 5:3, 1.4:1), 14 frames is used to mathematically guarantee
* that sequence length never exceeds 2048 tokens (<= 1990 tokens), preventing OOM errors.
*/
export function getGemmaEmbeddingTargetFrameCount(width?: number, height?: number): number {
if (!width || !height || width <= 0 || height <= 0) {
return 14
}
const ratio = width / height
const standardRatios = [
1 / 1, // 1:1
4 / 3, // 4:3
3 / 4, // 3:4
16 / 9, // 16:9
9 / 16, // 9:16
21 / 9, // 21:9
64 / 27, // 21:9 ultrawide (2560x1080, 3440x1440)
9 / 21, // 9:21
27 / 64, // 9:21 ultrawide portrait
]
// Allow up to 3% relative tolerance for minor encoder rounding (e.g. 854x480 vs 16:9)
const isStandard = standardRatios.some((std) => Math.abs(ratio - std) / std <= 0.03)
return isStandard ? 15 : 14
}
export interface GenerateVideoChunkEmbeddingParams {
teamId: string
chunkKey: string
}
export const generateVideoChunkEmbeddingActivity = defineStep(
async function generateVideoChunkEmbeddingActivity(
params: GenerateVideoChunkEmbeddingParams,
): Promise<{
embedding: number[]
usage: Usage
}> {
const provider = process.env.EMBEDDING_PROVIDER || 'gemini-embedding-2'
const isGemma = provider === 'gemma-embedding-2-openai' || params.chunkKey.endsWith('.tar')
if (isGemma) {
const { buffer: data } = await s3Service.getObject(
process.env.S3_BUCKET || 'shumai',
params.chunkKey,
)
let filesMap: Map<string, File>
try {
const archive = new Bun.Archive(data)
filesMap = await archive.files()
} catch (err) {
throw ApplicationFailure.create({
message: `Failed to read chunk archive ${params.chunkKey}: ${err instanceof Error ? err.message : String(err)}`,
nonRetryable: true,
})
}
const frameFiles = Array.from(filesMap.keys())
.filter((f) => /\.(jpe?g|png|webp)$/i.test(f))
.sort()
if (frameFiles.length === 0) {
throw ApplicationFailure.create({
message: `No extracted frames found in chunk archive ${params.chunkKey}`,
nonRetryable: true,
})
}
let targetFrameCount = 14
try {
const firstFile = filesMap.get(frameFiles[0])
if (firstFile) {
const firstFileBytes = await firstFile.bytes()
if (firstFileBytes.byteLength > 0) {
const meta = await sharp(Buffer.from(firstFileBytes)).metadata()
targetFrameCount = getGemmaEmbeddingTargetFrameCount(meta.width, meta.height)
}
}
} catch {
targetFrameCount = 14
}
let selectedFrames = frameFiles
if (selectedFrames.length > targetFrameCount) {
const step = (selectedFrames.length - 1) / (targetFrameCount - 1)
selectedFrames = Array.from(
{ length: targetFrameCount },
(_, i) => selectedFrames[Math.round(i * step)],
)
}
const input: OpenAiEmbeddingItem[] = await Promise.all(
selectedFrames.map(async (f) => {
const file = filesMap.get(f)!
const fileBytes = await file.bytes()
if (fileBytes.byteLength === 0) {
throw ApplicationFailure.create({
message: `Extracted frame ${f} in chunk archive ${params.chunkKey} is empty (0 bytes)`,
nonRetryable: true,
})
}
return {
type: 'image_url',
// eslint-disable-next-line @typescript-eslint/naming-convention
image_url: {
url: `data:image/jpeg;base64,${Buffer.from(fileBytes).toString('base64')}`,
},
}
}),
)
return await callGemmaEmbeddingServer(input)
}
const apiKey = process.env.GEMINI_API_KEY
if (!apiKey) {
throw ApplicationFailure.create({
message: 'GEMINI_API_KEY environment variable is not configured',
nonRetryable: true,
})
}
const resolvedApiKey = process.env[apiKey] || apiKey
const ai = new GoogleGenAI({ apiKey: resolvedApiKey })
const usage: Usage = {
model: 'gemini-embedding-2',
inputTokens: 0,
outputTokens: 0,
}
try {
const { buffer: data } = await s3Service.getObject(
process.env.S3_BUCKET || 'shumai',
params.chunkKey,
)
const embVec = await generateMultimodalEmbedding(ai, data, 'video/mp4')
return {
embedding: embVec,
usage,
}
} catch (err) {
throw ApplicationFailure.create({
message: `Failed to generate video chunk embedding for key ${params.chunkKey}: ${err instanceof Error ? err.message : String(err)}`,
nonRetryable: false,
})
}
},
)
export interface VideoChunkRange {
startTime: number
endTime: number
}
export interface TranscodedVideoChunk extends VideoChunkRange {
chunkKey: string
}
export interface TranscodeVideoChunksParams {
parentTaskId?: string
teamId?: string | null
projectId?: string | null
assetId: string
assetKey: string
format?: 'video' | 'frames'
chunks: VideoChunkRange[]
}
const DEFAULT_TRANSCODE_WAIT_TIMEOUT_MS = 60 * 60 * 1000 // 60 minutes
function getTranscodeWaitTimeoutMs(): number {
const parsed = parseInt(process.env.EMBEDDING_TRANSCODE_WAIT_TIMEOUT_MS || '', 10)
return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_TRANSCODE_WAIT_TIMEOUT_MS
}
async function cancelChildTranscodeTask(childTaskId: string): Promise<void> {
try {
await workflowService.cancel(childTaskId)
} catch {
// Ignore DBOS cancel errors during cleanup
}
try {
await prisma.workflowTask.updateMany({
where: {
id: childTaskId,
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
},
data: {
status: WorkflowTaskStatus.failed,
output: { error: 'Parent embedding workflow was cancelled' },
},
})
} catch {
// Ignore DB update errors during cleanup
}
}
export const transcodeVideoChunksActivity = defineStep(async function transcodeVideoChunksActivity(
params: TranscodeVideoChunksParams,
): Promise<{ chunks: TranscodedVideoChunk[] }> {
if (!params.assetKey) {
throw ApplicationFailure.create({
message: 'assetKey is required for video chunks transcoding',
nonRetryable: true,
})
}
if (!params.chunks || params.chunks.length === 0) {
return { chunks: [] }
}
let childTask = null
if (params.parentTaskId) {
childTask = await prisma.workflowTask.findFirst({
where: {
assetId: params.assetId,
type: WorkflowTaskType.transcode_video_chunks,
status: {
in: [
WorkflowTaskStatus.pending,
WorkflowTaskStatus.processing,
WorkflowTaskStatus.completed,
],
},
payload: {
path: ['videoChunks', 'parentTaskId'],
equals: params.parentTaskId,
},
},
orderBy: { id: 'desc' },
})
}
if (!childTask) {
childTask = await prisma.workflowTask.create({
data: {
assetId: params.assetId,
teamId: params.teamId ?? null,
projectId: params.projectId ?? null,
type: WorkflowTaskType.transcode_video_chunks,
status: WorkflowTaskStatus.pending,
payload: {
projectId: params.projectId ?? '',
videoChunks: {
parentTaskId: params.parentTaskId,
assetKey: params.assetKey,
format: params.format,
chunks: params.chunks,
},
},
},
})
}
const abortSignal = getLocalTaskAbortSignal(params.parentTaskId)
if (abortSignal?.aborted) {
await cancelChildTranscodeTask(childTask.id)
throw ApplicationFailure.create({
message: 'Parent embedding workflow was cancelled before transcode completed',
nonRetryable: true,
})
}
const onAbort = () => {
void cancelChildTranscodeTask(childTask.id)
}
abortSignal?.addEventListener('abort', onAbort, { once: true })
try {
const { task: completedTask, done } = await workflowService.waitFor(
childTask,
getTranscodeWaitTimeoutMs(),
)
if (!done) {
await cancelChildTranscodeTask(childTask.id)
throw ApplicationFailure.create({
message: `Transcode video chunks task ${childTask.id} timed out`,
nonRetryable: true,
})
}
const output = completedTask.output as { chunks?: TranscodedVideoChunk[] } | null
if (!output?.chunks || !Array.isArray(output.chunks)) {
throw ApplicationFailure.create({
message: `Transcode video chunks task ${childTask.id} completed without valid chunks output`,
nonRetryable: true,
})
}
if (abortSignal?.aborted) {
const bucket = process.env.S3_BUCKET || 'shumai'
for (const chunk of output.chunks) {
try {
await s3Service.deleteObject(bucket, chunk.chunkKey)
} catch {
// Best-effort cleanup on cancellation race
}
}
throw ApplicationFailure.create({
message: 'Parent embedding workflow was cancelled before transcode completed',
nonRetryable: true,
})
}
return { chunks: output.chunks }
} catch (err) {
if (abortSignal?.aborted || isDbosWorkflowCancelledError(err)) {
await cancelChildTranscodeTask(childTask.id)
throw err
}
if (err instanceof ApplicationFailure) {
throw err
}
// The child transcode workflow already applies its own step retry policy;
// fail fast here instead of spawning duplicate child tasks on parent retries.
throw ApplicationFailure.create({
message: err instanceof Error ? err.message : String(err),
nonRetryable: true,
cause: err instanceof Error ? err : undefined,
})
} finally {
abortSignal?.removeEventListener('abort', onAbort)
}
})
export const deleteS3ObjectActivity = defineStep(
async function deleteS3ObjectActivity(params: { key: string }): Promise<void> {
const bucket = process.env.S3_BUCKET || 'shumai'
await s3Service.deleteObject(bucket, params.key)
},
{ runOnCancel: true },
)