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
@@ -1,15 +1,18 @@
import { getGemmaOpenAiBaseUrl } from '@shumai/core/src/search/gemma-embedding-endpoint'
import {
embeddingServerService,
LOCAL_EMBEDDING_PROVIDER,
} from '@shumai/core/src/search/embedding-server'
import { transcriptLanguageCodeSchema, transcriptLanguagesSchema } from '@shumai/dtos'
import { z } from 'zod'
const transcriptEndpoint = () => `${getGemmaOpenAiBaseUrl()}/audio/transcriptions`
export function isLocalTranscriptionEnabled(): boolean {
return process.env.EMBEDDING_PROVIDER === 'gemma-embedding-2-openai'
export async function isLocalTranscriptionEnabled(teamId?: string): Promise<boolean> {
const { provider } = await embeddingServerService.resolveRuntimeConfig(teamId)
return provider === LOCAL_EMBEDDING_PROVIDER
}
export async function listLocalTranscriptionLanguages() {
const response = await fetch(`${transcriptEndpoint()}/languages`, {
export async function listLocalTranscriptionLanguages(teamId?: string) {
const { transcriptionEndpoint } = await embeddingServerService.resolveRuntimeConfig(teamId)
const response = await fetch(`${transcriptionEndpoint}/languages`, {
signal: AbortSignal.timeout(5_000),
})
if (!response.ok) throw new Error(`Transcription languages endpoint returned ${response.status}`)
@@ -34,11 +37,13 @@ export class LocalTranscriptionError extends Error {
}
export async function transcribeLocalAudio({
teamId,
audio,
language,
model,
signal,
}: {
teamId?: string
audio: Blob
language: string | null
model: string
@@ -51,7 +56,8 @@ export async function transcribeLocalAudio({
if (language) form.set('language', language)
const timeout = AbortSignal.timeout(90 * 60 * 1000)
const response = await fetch(transcriptEndpoint(), {
const { transcriptionEndpoint } = await embeddingServerService.resolveRuntimeConfig(teamId)
const response = await fetch(transcriptionEndpoint, {
method: 'POST',
body: form,
redirect: 'error',
@@ -1,4 +1,4 @@
import { prisma, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
import { prisma, UserType, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { transcriptionErrors } from '@shumai/dtos'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
@@ -8,6 +8,7 @@ describe('TranscriptService', () => {
setupTestDbHooks()
let assetId: string
let projectId: string
let agentId: string
const model = 'whisper-tiny'
const segments = [{ startMs: 125, endMs: 1425, text: 'Original segment' }]
const media: PrismaJson.MediaInfo = {
@@ -24,7 +25,23 @@ describe('TranscriptService', () => {
beforeEach(async () => {
vi.stubEnv('EMBEDDING_PROVIDER', 'gemma-embedding-2-openai')
vi.stubEnv('ENABLE_TRANSCRIPTION_AGENT', undefined)
const team = await prisma.team.create({ data: { name: 'Transcript test' } })
const agent = await prisma.agent.create({
data: {
type: 'transcription',
team: { connect: { id: team.id } },
config: { provider: '', model: '' },
user: {
create: {
name: 'Transcript Agent',
email: 'transcript-agent@example.test',
type: UserType.agent,
},
},
},
})
agentId = agent.id
const project = await prisma.project.create({
data: { name: 'Transcript test', teamId: team.id },
})
@@ -138,6 +155,18 @@ describe('TranscriptService', () => {
expect(await prisma.workflowTask.count({ where: { assetId } })).toBe(0)
})
it('requires an enabled Transcript Agent before contacting the provider or queuing', async () => {
vi.stubEnv('ENABLE_TRANSCRIPTION_AGENT', 'false')
await expect(transcriptService.isGenerationEnabled()).resolves.toBe(false)
vi.stubEnv('ENABLE_TRANSCRIPTION_AGENT', undefined)
await prisma.agent.update({ where: { id: agentId }, data: { enabled: false } })
await expect(transcriptService.generate(assetId, null)).rejects.toMatchObject({ status: 503 })
await prisma.agent.delete({ where: { id: agentId } })
await expect(transcriptService.listLanguages()).rejects.toMatchObject({ status: 503 })
expect(fetch).not.toHaveBeenCalled()
expect(await prisma.workflowTask.count({ where: { assetId } })).toBe(0)
})
it('serializes requests for an asset and uses its project and workflow type', async () => {
const results = await Promise.all([
transcriptService.generate(assetId, 'en'),
+35 -6
View File
@@ -1,4 +1,5 @@
import { logger } from '@shumai/core/src/logger'
import { getSystemAgentSetting } from '@shumai/core/src/agent/system-agents'
import {
notifyWorkflowTaskCreated,
prisma,
@@ -27,10 +28,30 @@ const segmentSelection = { id: true, startMs: true, endMs: true, text: true } as
type Segment = { startMs: number; endMs: number; text: string }
export class TranscriptService {
async findEnabledAgent(teamId?: string): Promise<{ id: string } | null> {
if (getSystemAgentSetting('transcription')?.enabled === false) return null
return prisma.agent.findFirst({
where: { teamId, type: 'transcription', enabled: true },
orderBy: { id: 'desc' },
select: { id: true },
})
}
async isGenerationEnabled(teamId?: string): Promise<boolean> {
return Boolean(
(await this.findEnabledAgent(teamId)) && (await isLocalTranscriptionEnabled(teamId)),
)
}
async listLanguages() {
this.requireEnabled()
await this.requireEnabled()
return this.loadLanguages()
}
private async loadLanguages(teamId?: string) {
try {
return await listLocalTranscriptionLanguages()
return await listLocalTranscriptionLanguages(teamId)
} catch (error) {
logger.warn({ err: error }, 'Failed to load local transcription languages')
throw new HTTPException(503, { message: 'Transcription languages are unavailable' })
@@ -77,11 +98,19 @@ export class TranscriptService {
}
async generate(assetId: string, language: string | null): Promise<GenerateTranscriptResult> {
this.requireEnabled()
const source = await prisma.asset.findUnique({
where: { id: assetId },
select: { project: { select: { teamId: true } } },
})
if (!source?.project) {
throw new HTTPException(400, { message: 'Transcripts require a processed video file' })
}
const { teamId } = source.project
await this.requireEnabled(teamId)
const saved = await this.findSaved(prisma, assetId, language)
if (saved) return saved
const { model, languages } = await this.listLanguages()
const { model, languages } = await this.loadLanguages(teamId)
if (language && !languages.some((entry) => entry.code === language)) {
throw new HTTPException(400, { message: 'Unsupported transcription language' })
}
@@ -248,8 +277,8 @@ export class TranscriptService {
})
}
private requireEnabled(): void {
if (!isLocalTranscriptionEnabled()) {
private async requireEnabled(teamId?: string): Promise<void> {
if (!(await this.isGenerationEnabled(teamId))) {
throw new HTTPException(503, { message: 'Local transcription is disabled' })
}
}