mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-04 15:14:10 +00:00
feat: configure embedding servers and transcript agents
This commit is contained in:
@@ -1,5 +1,9 @@
|
||||
import { GoogleGenAI } from '@google/genai'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import {
|
||||
embeddingServerService,
|
||||
LOCAL_EMBEDDING_PROVIDER,
|
||||
} from '@shumai/core/src/search/embedding-server'
|
||||
import { textEmbeddingService } from '@shumai/core/src/search/text-embedding'
|
||||
import { prisma, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
|
||||
import {
|
||||
@@ -59,19 +63,13 @@ interface OpenAiEmbeddingItem {
|
||||
}
|
||||
}
|
||||
|
||||
async function callGemmaEmbeddingServer(input: string | OpenAiEmbeddingItem[]): Promise<{
|
||||
async function callGemmaEmbeddingServer(
|
||||
endpoint: string,
|
||||
input: 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' },
|
||||
@@ -89,8 +87,12 @@ async function callGemmaEmbeddingServer(input: string | OpenAiEmbeddingItem[]):
|
||||
})
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- response json shape is dynamic from external endpoint
|
||||
const json: any = await response.json()
|
||||
const json = (await response.json()) as {
|
||||
model?: string
|
||||
data?: Array<{ embedding?: number[] }>
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention -- OpenAI response field
|
||||
usage?: { prompt_tokens?: number }
|
||||
}
|
||||
const embedding = json.data?.[0]?.embedding
|
||||
if (!embedding || !Array.isArray(embedding)) {
|
||||
throw ApplicationFailure.create({
|
||||
@@ -102,7 +104,7 @@ async function callGemmaEmbeddingServer(input: string | OpenAiEmbeddingItem[]):
|
||||
return {
|
||||
embedding,
|
||||
usage: {
|
||||
model: json.model || 'gemma-embedding-2-openai',
|
||||
model: json.model || LOCAL_EMBEDDING_PROVIDER,
|
||||
inputTokens: json.usage?.prompt_tokens ?? 0,
|
||||
outputTokens: 0,
|
||||
},
|
||||
@@ -119,8 +121,8 @@ export const generateTextEmbeddingActivity = defineStep(
|
||||
embedding: number[]
|
||||
usage: Usage
|
||||
}> {
|
||||
const provider = process.env.EMBEDDING_PROVIDER || 'gemini-embedding-2'
|
||||
if (provider !== 'gemma-embedding-2-openai' && !process.env.GEMINI_API_KEY) {
|
||||
const { provider } = await embeddingServerService.resolveRuntimeConfig(params.teamId)
|
||||
if (provider !== LOCAL_EMBEDDING_PROVIDER && !process.env.GEMINI_API_KEY) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'GEMINI_API_KEY environment variable is not configured',
|
||||
nonRetryable: true,
|
||||
@@ -129,6 +131,7 @@ export const generateTextEmbeddingActivity = defineStep(
|
||||
|
||||
try {
|
||||
const result = await textEmbeddingService.generateEmbedding(params.text, {
|
||||
provider,
|
||||
teamId: params.teamId,
|
||||
skipCache: true,
|
||||
})
|
||||
@@ -193,7 +196,9 @@ export const getEmbeddingContextActivity = defineStep(
|
||||
|
||||
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 { provider: embeddingProvider } = await embeddingServerService.resolveRuntimeConfig(
|
||||
params.teamId,
|
||||
)
|
||||
|
||||
const existingEmbeddings = await prisma.$queryRaw<ExistingAssetEmbeddingInfo[]>`
|
||||
SELECT
|
||||
@@ -290,6 +295,7 @@ export const saveAssetEmbeddingsActivity = defineStep(
|
||||
|
||||
export interface GenerateImageEmbeddingParams {
|
||||
teamId: string
|
||||
provider?: string
|
||||
assetKey: string
|
||||
mediaType: string
|
||||
}
|
||||
@@ -299,20 +305,23 @@ export const generateImageEmbeddingActivity = defineStep(
|
||||
embedding: number[]
|
||||
usage: Usage
|
||||
}> {
|
||||
const provider = process.env.EMBEDDING_PROVIDER || 'gemini-embedding-2'
|
||||
const { provider, embeddingEndpoint } = await embeddingServerService.resolveRuntimeConfig(
|
||||
params.teamId,
|
||||
params.provider,
|
||||
)
|
||||
const { buffer: data } = await s3Service.getObject(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
params.assetKey,
|
||||
)
|
||||
|
||||
if (provider === 'gemma-embedding-2-openai') {
|
||||
if (provider === LOCAL_EMBEDDING_PROVIDER) {
|
||||
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([
|
||||
return callGemmaEmbeddingServer(embeddingEndpoint, [
|
||||
{
|
||||
type: 'image_url',
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
@@ -383,6 +392,7 @@ export function getGemmaEmbeddingTargetFrameCount(width?: number, height?: numbe
|
||||
|
||||
export interface GenerateVideoChunkEmbeddingParams {
|
||||
teamId: string
|
||||
provider?: string
|
||||
chunkKey: string
|
||||
}
|
||||
|
||||
@@ -393,8 +403,11 @@ export const generateVideoChunkEmbeddingActivity = defineStep(
|
||||
embedding: number[]
|
||||
usage: Usage
|
||||
}> {
|
||||
const provider = process.env.EMBEDDING_PROVIDER || 'gemini-embedding-2'
|
||||
const isGemma = provider === 'gemma-embedding-2-openai' || params.chunkKey.endsWith('.tar')
|
||||
const { provider, embeddingEndpoint } = await embeddingServerService.resolveRuntimeConfig(
|
||||
params.teamId,
|
||||
params.provider,
|
||||
)
|
||||
const isGemma = provider === LOCAL_EMBEDDING_PROVIDER || params.chunkKey.endsWith('.tar')
|
||||
|
||||
if (isGemma) {
|
||||
const { buffer: data } = await s3Service.getObject(
|
||||
@@ -467,7 +480,7 @@ export const generateVideoChunkEmbeddingActivity = defineStep(
|
||||
}),
|
||||
)
|
||||
|
||||
return await callGemmaEmbeddingServer(input)
|
||||
return await callGemmaEmbeddingServer(embeddingEndpoint, input)
|
||||
}
|
||||
|
||||
const apiKey = process.env.GEMINI_API_KEY
|
||||
|
||||
@@ -54,12 +54,14 @@ export const extractTranscriptAudioActivity = defineStep(
|
||||
assetId,
|
||||
taskId,
|
||||
audioKey,
|
||||
teamId,
|
||||
}: {
|
||||
assetId: string
|
||||
taskId: string
|
||||
audioKey: string
|
||||
teamId?: string
|
||||
}): Promise<void> {
|
||||
if (!isLocalTranscriptionEnabled()) {
|
||||
if (!(await isLocalTranscriptionEnabled(teamId))) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Local transcription is disabled',
|
||||
nonRetryable: true,
|
||||
@@ -131,11 +133,13 @@ export const extractTranscriptAudioActivity = defineStep(
|
||||
)
|
||||
|
||||
export const transcribeAudioActivity = defineStep(async function transcribeAudioActivity({
|
||||
teamId,
|
||||
taskId,
|
||||
audioKey,
|
||||
language,
|
||||
model,
|
||||
}: {
|
||||
teamId?: string
|
||||
taskId: string
|
||||
audioKey: string
|
||||
language: string | null
|
||||
@@ -145,6 +149,7 @@ export const transcribeAudioActivity = defineStep(async function transcribeAudio
|
||||
try {
|
||||
const path = await ensureLocalMediaFile(audioKey, join(directory, 'audio.wav'))
|
||||
return await transcribeLocalAudio({
|
||||
teamId,
|
||||
audio: Bun.file(path),
|
||||
language,
|
||||
model,
|
||||
@@ -179,3 +184,39 @@ export const saveTranscriptActivity = defineStep(async function saveTranscriptAc
|
||||
throw ApplicationFailure.create({ message: 'Video is no longer available', nonRetryable: true })
|
||||
}
|
||||
})
|
||||
|
||||
export const reportTranscriptionFailureActivity = defineStep(
|
||||
async function reportTranscriptionFailureActivity(taskId: string, reason: string | undefined) {
|
||||
if (getLocalTaskAbortSignal(taskId)?.aborted) return
|
||||
|
||||
const task = await prisma.workflowTask.findUnique({
|
||||
where: { id: taskId, type: 'ai_transcription', status: 'processing' },
|
||||
select: { assetId: true, teamId: true },
|
||||
})
|
||||
if (!task?.teamId) return
|
||||
|
||||
const asset = await prisma.asset.findFirst({
|
||||
where: { id: task.assetId, isDeleted: false, project: { teamId: task.teamId } },
|
||||
select: { id: true },
|
||||
})
|
||||
if (!asset) return
|
||||
|
||||
const agent = await transcriptService.findEnabledAgent(task.teamId)
|
||||
if (!agent || getLocalTaskAbortSignal(taskId)?.aborted) return
|
||||
|
||||
const detail = Object.values(transcriptionErrors).find((message) => message === reason)
|
||||
await prisma.assetComment.upsert({
|
||||
where: { transcriptionTaskId: taskId },
|
||||
update: {},
|
||||
create: {
|
||||
assetId: asset.id,
|
||||
creatorId: agent.id,
|
||||
transcriptionTaskId: taskId,
|
||||
isInternal: true,
|
||||
message: detail
|
||||
? `Transcription failed. ${detail}.`
|
||||
: 'Transcription failed. Try generating the transcript again.',
|
||||
},
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { LOCAL_EMBEDDING_PROVIDER } from '@shumai/core/src/search/embedding-server'
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import {
|
||||
ApplicationFailure,
|
||||
@@ -56,7 +57,7 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
|
||||
const { asset, chunkDuration, chunkOverlap, embeddingProvider, existingEmbeddings } = context
|
||||
const isGemmaProvider = embeddingProvider === 'gemma-embedding-2-openai'
|
||||
const isGemmaProvider = embeddingProvider === LOCAL_EMBEDDING_PROVIDER
|
||||
|
||||
const existing = existingEmbeddings || []
|
||||
|
||||
@@ -130,6 +131,7 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
if (!alreadyEmbedded) {
|
||||
const result = await generateImageEmbeddingActivity({
|
||||
teamId: task.teamId,
|
||||
provider: embeddingProvider,
|
||||
assetKey: embeddingKey,
|
||||
mediaType: embeddingMediaType || 'image/jpeg',
|
||||
})
|
||||
@@ -195,6 +197,7 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
// Step B: Generate embedding on agent worker
|
||||
const chunkResult = await generateVideoChunkEmbeddingActivity({
|
||||
teamId: task.teamId,
|
||||
provider: embeddingProvider,
|
||||
chunkKey: chunk.chunkKey,
|
||||
})
|
||||
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import { ApplicationFailure } from '@shumai/workflow-core'
|
||||
import { ApplicationFailure, isDbosWorkflowCancelledError } from '@shumai/workflow-core'
|
||||
import { deleteS3ObjectActivity } from '../activities/ai'
|
||||
import {
|
||||
extractTranscriptAudioActivity,
|
||||
saveTranscriptActivity,
|
||||
transcribeAudioActivity,
|
||||
reportTranscriptionFailureActivity,
|
||||
} from '../activities/transcription'
|
||||
|
||||
export async function transcribeVideoWorkflow(task: WorkflowTask): Promise<void> {
|
||||
@@ -19,10 +20,11 @@ export async function transcribeVideoWorkflow(task: WorkflowTask): Promise<void>
|
||||
|
||||
const taskId = task.id
|
||||
const assetId = task.assetId
|
||||
const teamId = task.teamId ?? undefined
|
||||
const audioKey = `temp/transcripts/${taskId}.wav`
|
||||
try {
|
||||
await extractTranscriptAudioActivity({ assetId, taskId, audioKey })
|
||||
const transcript = await transcribeAudioActivity({ taskId, audioKey, ...request })
|
||||
await extractTranscriptAudioActivity({ assetId, taskId, audioKey, teamId })
|
||||
const transcript = await transcribeAudioActivity({ taskId, audioKey, teamId, ...request })
|
||||
if (request.language && transcript.language && request.language !== transcript.language) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Transcription returned an unexpected language',
|
||||
@@ -40,6 +42,18 @@ export async function transcribeVideoWorkflow(task: WorkflowTask): Promise<void>
|
||||
text: segment.text,
|
||||
})),
|
||||
})
|
||||
} catch (error) {
|
||||
if (!isDbosWorkflowCancelledError(error)) {
|
||||
try {
|
||||
await reportTranscriptionFailureActivity(
|
||||
taskId,
|
||||
error instanceof Error ? error.message : undefined,
|
||||
)
|
||||
} catch (commentError) {
|
||||
logger.error({ err: commentError, taskId }, 'Failed to post transcript failure comment')
|
||||
}
|
||||
}
|
||||
throw error
|
||||
} finally {
|
||||
try {
|
||||
await deleteS3ObjectActivity({ key: audioKey })
|
||||
|
||||
Reference in New Issue
Block a user