feat: configure embedding servers and transcript agents

This commit is contained in:
yiling
2026-12-04 18:54:29 +08:00
parent 72a7f68c92
commit 553269012c
57 changed files with 1686 additions and 271 deletions
+35 -22
View File
@@ -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
+42 -1
View File
@@ -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.',
},
})
},
)