fix(agent): adaptively set video embedding frame count based on aspect ratio (#477)

* fix(agent): adaptively set video embedding frame count based on aspect ratio

Adjust sampled video frame counts between 15 and 14 based on the video's aspect ratio. Standard aspect ratios (1:1, 4:3, 3:4, 16:9, 9:16, 21:9) stay within the 2048 token signature bucket when using 15 frames, while non-standard or custom aspect ratios use 14 frames to guarantee that sequence length never exceeds 2048 tokens, preventing out-of-memory errors on the embedding server.

* feat(agent): persist video chunk embeddings incrementally and resume on retry (#478)
This commit is contained in:
Yiling-J
2026-10-16 08:36:51 +08:00
committed by yiling
parent 6cc90bf973
commit 1a46f63160
7 changed files with 496 additions and 40 deletions
+168 -2
View File
@@ -4,8 +4,10 @@ import {
extractAiMetadataActivity,
getEmbeddingContextActivity,
saveAssetEmbeddingsActivity,
deleteAssetEmbeddingsActivity,
generateImageEmbeddingActivity,
generateVideoChunkEmbeddingActivity,
getGemmaEmbeddingTargetFrameCount,
} from './ai'
import { s3Service } from '@shumai/core/src/s3/s3'
import { transcodeService } from '@shumai/core'
@@ -335,7 +337,84 @@ describe('AI Activities Unit Tests', () => {
expect(mockFetch).toHaveBeenCalled()
})
it('should sample uniform 16 frames when chunk archive contains more than 16 frames', async () => {
describe('getGemmaEmbeddingTargetFrameCount', () => {
it('should return 15 for standard aspect ratios', () => {
// 16:9
expect(getGemmaEmbeddingTargetFrameCount(1920, 1080)).toBe(15)
expect(getGemmaEmbeddingTargetFrameCount(1280, 720)).toBe(15)
expect(getGemmaEmbeddingTargetFrameCount(854, 480)).toBe(15)
// 9:16
expect(getGemmaEmbeddingTargetFrameCount(1080, 1920)).toBe(15)
// 1:1
expect(getGemmaEmbeddingTargetFrameCount(1080, 1080)).toBe(15)
expect(getGemmaEmbeddingTargetFrameCount(480, 480)).toBe(15)
// 4:3
expect(getGemmaEmbeddingTargetFrameCount(1440, 1080)).toBe(15)
expect(getGemmaEmbeddingTargetFrameCount(640, 480)).toBe(15)
// 3:4
expect(getGemmaEmbeddingTargetFrameCount(1080, 1440)).toBe(15)
// 21:9
expect(getGemmaEmbeddingTargetFrameCount(2560, 1080)).toBe(15)
expect(getGemmaEmbeddingTargetFrameCount(3440, 1440)).toBe(15)
})
it('should return 14 for non-standard aspect ratios and missing/invalid dimensions', () => {
expect(getGemmaEmbeddingTargetFrameCount(1000, 600)).toBe(14) // 5:3
expect(getGemmaEmbeddingTargetFrameCount(700, 500)).toBe(14) // 1.4:1
expect(getGemmaEmbeddingTargetFrameCount(854, 672)).toBe(14) // ~1.27:1
expect(getGemmaEmbeddingTargetFrameCount(undefined, undefined)).toBe(14)
expect(getGemmaEmbeddingTargetFrameCount(0, 0)).toBe(14)
expect(getGemmaEmbeddingTargetFrameCount(-100, 100)).toBe(14)
})
})
it('should sample uniform 15 frames when chunk archive contains standard 16:9 frames', async () => {
process.env.EMBEDDING_PROVIDER = 'gemma-embedding-2-openai'
const mockFetch = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({
model: 'embeddinggemma-2',
data: [{ embedding: Array(768).fill(0.3) }],
// eslint-disable-next-line @typescript-eslint/naming-convention
usage: { prompt_tokens: 140 },
}),
})
vi.stubGlobal('fetch', mockFetch)
const sampleJpg = await sharp({
create: {
width: 160,
height: 90,
channels: 3,
background: { r: 0, g: 0, b: 0 },
},
})
.jpeg()
.toBuffer()
const frames: Record<string, Buffer> = {}
for (let i = 1; i <= 30; i++) {
frames[`frame_${String(i).padStart(4, '0')}.jpg`] = sampleJpg
}
const sampleArchive = new Bun.Archive(frames)
const archiveBytes = await sampleArchive.bytes()
vi.mocked(s3Service.getObject).mockResolvedValue({
buffer: Buffer.from(archiveBytes.buffer, archiveBytes.byteOffset, archiveBytes.byteLength),
contentType: 'application/x-tar',
} as unknown as { buffer: Buffer; contentType: string })
const res = await generateVideoChunkEmbeddingActivity({
teamId: 't1',
chunkKey: 'files/asset-1/tmp-embedding-chunks/frames-0-60.tar',
})
expect(res.embedding).toHaveLength(768)
const requestBody = JSON.parse(mockFetch.mock.calls[0][1].body)
expect(requestBody.input).toHaveLength(15)
})
it('should fallback to 14 frames when chunk archive contains non-standard or unparseable frames', async () => {
process.env.EMBEDDING_PROVIDER = 'gemma-embedding-2-openai'
const mockFetch = vi.fn().mockResolvedValue({
ok: true,
@@ -367,7 +446,7 @@ describe('AI Activities Unit Tests', () => {
expect(res.embedding).toHaveLength(768)
const requestBody = JSON.parse(mockFetch.mock.calls[0][1].body)
expect(requestBody.input).toHaveLength(16)
expect(requestBody.input).toHaveLength(14)
})
it('should throw non-retryable ApplicationFailure when chunk archive contains no valid frames', async () => {
@@ -642,6 +721,45 @@ describe('AI Database Activities Integration', () => {
delete process.env.EMBEDDING_CHUNK_DURATION
delete process.env.EMBEDDING_CHUNK_OVERLAP
})
it('should return existing embeddings for the asset', async () => {
// Ensure agent exists
await prisma.agent.upsert({
where: { id: user.id },
update: {},
create: {
id: user.id,
teamId: team.id,
type: 'embedding',
enabled: true,
config: { provider: 'openai', model: 'gpt-4' },
},
})
await saveAssetEmbeddingsActivity({
assetId: asset.id,
embeddings: [
{ embedding: Array(1536).fill(0.01), startTime: 0.0, endTime: 60.0 },
{ embedding: Array(768).fill(0.02), startTime: 55.0, endTime: 115.0 },
],
})
const ctx = await getEmbeddingContextActivity({
teamId: team.id,
assetId: asset.id,
})
expect(ctx.existingEmbeddings).toHaveLength(2)
const chunk1 = ctx.existingEmbeddings.find((e) => e.startTime === 0)
expect(chunk1).toBeDefined()
expect(chunk1?.has1536).toBe(true)
expect(chunk1?.has768).toBe(false)
const chunk2 = ctx.existingEmbeddings.find((e) => e.startTime === 55)
expect(chunk2).toBeDefined()
expect(chunk2?.has1536).toBe(false)
expect(chunk2?.has768).toBe(true)
})
})
describe('saveAssetEmbeddingsActivity', () => {
@@ -709,4 +827,52 @@ describe('AI Database Activities Integration', () => {
expect(dbEmbeddings[1].has1536).toBe(false)
})
})
describe('deleteAssetEmbeddingsActivity', () => {
it('should delete specific embeddings by id', async () => {
await saveAssetEmbeddingsActivity({
assetId: asset.id,
embeddings: [
{ embedding: Array(1536).fill(0.01), startTime: 0, endTime: 60 },
{ embedding: Array(1536).fill(0.02), startTime: 55, endTime: 115 },
],
})
const before = await prisma.assetEmbedding.findMany({
where: { assetId: asset.id },
})
expect(before).toHaveLength(2)
const targetId = before[0].id
await deleteAssetEmbeddingsActivity({
assetId: asset.id,
ids: [targetId],
})
const after = await prisma.assetEmbedding.findMany({
where: { assetId: asset.id },
})
expect(after).toHaveLength(1)
expect(after[0].id).not.toBe(targetId)
})
it('should delete all embeddings for an asset when ids is not provided', async () => {
await saveAssetEmbeddingsActivity({
assetId: asset.id,
embeddings: [
{ embedding: Array(1536).fill(0.01), startTime: 0, endTime: 60 },
{ embedding: Array(1536).fill(0.02), startTime: 55, endTime: 115 },
],
})
await deleteAssetEmbeddingsActivity({
assetId: asset.id,
})
const after = await prisma.assetEmbedding.findMany({
where: { assetId: asset.id },
})
expect(after).toHaveLength(0)
})
})
})
+89 -3
View File
@@ -250,12 +250,49 @@ export async function getEmbeddingContextActivity(params: { teamId: string; asse
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 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,
},
})
}
}
@@ -360,6 +397,38 @@ export async function generateImageEmbeddingActivity(
}
}
/**
* 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
@@ -402,10 +471,27 @@ export async function generateVideoChunkEmbeddingActivity(
})
}
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 > 16) {
const step = (selectedFrames.length - 1) / 15
selectedFrames = Array.from({ length: 16 }, (_, i) => selectedFrames[Math.round(i * step)])
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(