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:
@@ -1040,6 +1040,61 @@ describe('AgentService', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('Transcript Agent', () => {
|
||||
test('allows one Transcript Agent per team, including when it is disabled', async () => {
|
||||
const svc = new AgentService()
|
||||
const team = await prisma.team.create({ data: { name: 'Transcript agent team' } })
|
||||
const params = {
|
||||
teamId: team.id,
|
||||
type: 'transcription' as const,
|
||||
name: 'Transcript Agent',
|
||||
avatar: 'custom-transcript-avatar',
|
||||
enabled: false,
|
||||
thinkingLevel: 'off' as const,
|
||||
}
|
||||
|
||||
await expect(svc.createAgent(params)).resolves.toMatchObject({
|
||||
enabled: false,
|
||||
providerId: null,
|
||||
})
|
||||
await expect(svc.createAgent(params)).rejects.toThrow('already exists for this team')
|
||||
expect(await prisma.agent.count({ where: { teamId: team.id, type: 'transcription' } })).toBe(
|
||||
1,
|
||||
)
|
||||
})
|
||||
|
||||
test('provisions and toggles the same read-only agent from the environment', async () => {
|
||||
const svc = new AgentService()
|
||||
const team = await prisma.team.create({ data: { name: 'Managed transcript agent team' } })
|
||||
try {
|
||||
vi.stubEnv('ENABLE_TRANSCRIPTION_AGENT', 'false')
|
||||
await svc.ensureSystemAgentsForTeam(team.id)
|
||||
expect(
|
||||
await prisma.agent.count({ where: { teamId: team.id, type: 'transcription' } }),
|
||||
).toBe(0)
|
||||
|
||||
vi.stubEnv('ENABLE_TRANSCRIPTION_AGENT', 'true')
|
||||
await svc.ensureSystemAgents()
|
||||
const [agent] = await svc.listAgents({ teamId: team.id })
|
||||
expect(await svc.toAgentInfo(agent)).toMatchObject({ enabled: true, readOnly: true })
|
||||
|
||||
vi.stubEnv('ENABLE_TRANSCRIPTION_AGENT', 'false')
|
||||
await svc.ensureSystemAgentsForTeam(team.id)
|
||||
const [disabled] = await svc.listAgents({ teamId: team.id })
|
||||
expect(await svc.toAgentInfo(disabled)).toMatchObject({
|
||||
id: agent.id,
|
||||
enabled: false,
|
||||
readOnly: true,
|
||||
})
|
||||
|
||||
vi.stubEnv('ENABLE_TRANSCRIPTION_AGENT', undefined)
|
||||
expect(await svc.toAgentInfo(disabled)).toMatchObject({ enabled: false, readOnly: false })
|
||||
} finally {
|
||||
vi.unstubAllEnvs()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('ensureEmbeddingAgent', () => {
|
||||
test('creates embedding agent when ENABLE_EMBEDDING_AGENT is true', async () => {
|
||||
const db = prisma
|
||||
@@ -1048,7 +1103,7 @@ describe('AgentService', () => {
|
||||
|
||||
process.env.ENABLE_EMBEDDING_AGENT = 'true'
|
||||
try {
|
||||
await svc.ensureEmbeddingAgentForTeam(team.id)
|
||||
await svc.ensureSystemAgentsForTeam(team.id)
|
||||
const agent = await db.agent.findFirst({
|
||||
where: { teamId: team.id, type: 'embedding' },
|
||||
include: { user: true, skills: { include: { skill: true } }, mcpServers: true },
|
||||
@@ -1063,7 +1118,7 @@ describe('AgentService', () => {
|
||||
expect(info.readOnly).toBe(true)
|
||||
|
||||
// Ensure idempotency
|
||||
await svc.ensureEmbeddingAgentForTeam(team.id)
|
||||
await svc.ensureSystemAgentsForTeam(team.id)
|
||||
const count = await db.agent.count({
|
||||
where: { teamId: team.id, type: 'embedding' },
|
||||
})
|
||||
@@ -1093,7 +1148,7 @@ describe('AgentService', () => {
|
||||
|
||||
process.env.ENABLE_EMBEDDING_AGENT = 'true'
|
||||
try {
|
||||
await svc.ensureEmbeddingAgentForTeam(team.id)
|
||||
await svc.ensureSystemAgentsForTeam(team.id)
|
||||
const agent = await db.agent.findFirst({
|
||||
where: { teamId: team.id, type: 'embedding' },
|
||||
include: { user: true, skills: { include: { skill: true } }, mcpServers: true },
|
||||
@@ -1113,7 +1168,7 @@ describe('AgentService', () => {
|
||||
const team = await db.team.create({ data: { name: 'Team No Agent' } })
|
||||
|
||||
delete process.env.ENABLE_EMBEDDING_AGENT
|
||||
await svc.ensureEmbeddingAgentForTeam(team.id)
|
||||
await svc.ensureSystemAgentsForTeam(team.id)
|
||||
const agent = await db.agent.findFirst({
|
||||
where: { teamId: team.id, type: 'embedding' },
|
||||
})
|
||||
@@ -1127,7 +1182,7 @@ describe('AgentService', () => {
|
||||
|
||||
process.env.ENABLE_EMBEDDING_AGENT = 'false'
|
||||
try {
|
||||
await svc.ensureEmbeddingAgentForTeam(team.id)
|
||||
await svc.ensureSystemAgentsForTeam(team.id)
|
||||
const agent = await db.agent.findFirst({
|
||||
where: { teamId: team.id, type: 'embedding' },
|
||||
})
|
||||
@@ -1157,7 +1212,7 @@ describe('AgentService', () => {
|
||||
|
||||
process.env.ENABLE_EMBEDDING_AGENT = 'false'
|
||||
try {
|
||||
await svc.ensureEmbeddingAgentForTeam(team.id)
|
||||
await svc.ensureSystemAgentsForTeam(team.id)
|
||||
const agent = await db.agent.findFirst({
|
||||
where: { teamId: team.id, type: 'embedding' },
|
||||
include: { user: true, skills: { include: { skill: true } }, mcpServers: true },
|
||||
@@ -1172,7 +1227,7 @@ describe('AgentService', () => {
|
||||
}
|
||||
})
|
||||
|
||||
test('ensureSystemEmbeddingAgents updates all teams when ENABLE_EMBEDDING_AGENT is false', async () => {
|
||||
test('ensureSystemAgents updates all teams when ENABLE_EMBEDDING_AGENT is false', async () => {
|
||||
const db = prisma
|
||||
const svc = new AgentService()
|
||||
const { team: team1 } = await setupTestData(db)
|
||||
@@ -1194,7 +1249,7 @@ describe('AgentService', () => {
|
||||
|
||||
process.env.ENABLE_EMBEDDING_AGENT = 'false'
|
||||
try {
|
||||
await svc.ensureSystemEmbeddingAgents()
|
||||
await svc.ensureSystemAgents()
|
||||
|
||||
const a1 = await db.agent.findFirst({ where: { teamId: team1.id, type: 'embedding' } })
|
||||
const a2 = await db.agent.findFirst({ where: { teamId: team2.id, type: 'embedding' } })
|
||||
|
||||
@@ -22,6 +22,7 @@ import AdmZip from 'adm-zip'
|
||||
import { getAllowedAgentRoles } from './permissions'
|
||||
import { getPresetAvatarBuffer, getPresetAvatarStorageKey, isPresetAvatarId } from './presets'
|
||||
import { agentSessionService } from './session-service'
|
||||
import { getSystemAgentSetting } from './system-agents'
|
||||
|
||||
const agentInclude = {
|
||||
user: true,
|
||||
@@ -58,7 +59,27 @@ function extractS3Key(urlOrKey?: string | null): string | null | undefined {
|
||||
export class AgentService {
|
||||
private skillContentCache = new Map<string, string>()
|
||||
|
||||
constructor(private readonly prismaClient: typeof prisma = prisma) {}
|
||||
constructor(private readonly prismaClient: typeof prisma | Prisma.TransactionClient = prisma) {}
|
||||
|
||||
private inTransaction<T>(work: (tx: Prisma.TransactionClient) => Promise<T>): Promise<T> {
|
||||
const db = this.prismaClient
|
||||
return '$transaction' in db ? db.$transaction(work) : work(db)
|
||||
}
|
||||
|
||||
private async requireUniqueAgentType(
|
||||
tx: Prisma.TransactionClient,
|
||||
teamId: string,
|
||||
type: AgentType,
|
||||
agentId?: string,
|
||||
): Promise<void> {
|
||||
if (type === 'chat') return
|
||||
|
||||
await tx.$queryRaw`SELECT id FROM teams WHERE id = ${teamId} FOR UPDATE`
|
||||
const existing = await tx.agent.findFirst({
|
||||
where: { type, teamId, id: agentId ? { not: agentId } : undefined },
|
||||
})
|
||||
if (existing) throw new Error(`Agent of type ${type} already exists for this team`)
|
||||
}
|
||||
|
||||
async getSkillContent(skillId: string): Promise<string> {
|
||||
const skill = await this.prismaClient.skill.findUnique({
|
||||
@@ -150,18 +171,6 @@ export class AgentService {
|
||||
deniedTools,
|
||||
} = params
|
||||
|
||||
if (type === 'embedding' || type === 'autofill') {
|
||||
const existing = await this.prismaClient.agent.findFirst({
|
||||
where: {
|
||||
type,
|
||||
teamId,
|
||||
},
|
||||
})
|
||||
if (existing) {
|
||||
throw new Error(`Agent of type ${type} already exists for this team`)
|
||||
}
|
||||
}
|
||||
|
||||
if (type === 'chat' || type === 'autofill') {
|
||||
if (!providerId || !modelId) {
|
||||
throw new Error('providerId and modelId are required for chat/autofill agents')
|
||||
@@ -192,11 +201,12 @@ export class AgentService {
|
||||
imageKey = extractS3Key(avatar)
|
||||
}
|
||||
|
||||
return this.prismaClient.$transaction(async (tx) => {
|
||||
return this.inTransaction(async (tx) => {
|
||||
const team = await tx.team.findUnique({
|
||||
where: { id: teamId },
|
||||
})
|
||||
if (!team) throw new Error('team not found')
|
||||
await this.requireUniqueAgentType(tx, teamId, type)
|
||||
|
||||
if (runnerId) {
|
||||
const runner = await tx.runner.findFirst({
|
||||
@@ -298,19 +308,6 @@ export class AgentService {
|
||||
|
||||
if (!agent) throw new Error('agent not found')
|
||||
|
||||
if (type === 'embedding' || type === 'autofill') {
|
||||
const existing = await this.prismaClient.agent.findFirst({
|
||||
where: {
|
||||
type,
|
||||
id: { not: agentId },
|
||||
teamId: agent.teamId,
|
||||
},
|
||||
})
|
||||
if (existing) {
|
||||
throw new Error(`Agent of type ${type} already exists for this team`)
|
||||
}
|
||||
}
|
||||
|
||||
if (type === 'chat' || type === 'autofill') {
|
||||
if (!providerId || !modelId) {
|
||||
throw new Error('providerId and modelId are required for chat/autofill agents')
|
||||
@@ -364,7 +361,9 @@ export class AgentService {
|
||||
avatarPreset: newAvatarPreset,
|
||||
}
|
||||
|
||||
return this.prismaClient.$transaction(async (tx) => {
|
||||
return this.inTransaction(async (tx) => {
|
||||
await this.requireUniqueAgentType(tx, agent.teamId, type, agentId)
|
||||
|
||||
await tx.user.update({
|
||||
where: { id: agentId },
|
||||
data: {
|
||||
@@ -476,10 +475,7 @@ export class AgentService {
|
||||
*/
|
||||
async toAgentInfo(agent: AgentInfoSource): Promise<AgentInfo> {
|
||||
const config = agent.config as unknown as PrismaJson.AgentConfig
|
||||
const isManagedByEnv =
|
||||
process.env.ENABLE_EMBEDDING_AGENT === 'true' ||
|
||||
process.env.ENABLE_EMBEDDING_AGENT === 'false'
|
||||
const isReadOnly = agent.type === 'embedding' && isManagedByEnv
|
||||
const isReadOnly = getSystemAgentSetting(agent.type) !== undefined
|
||||
|
||||
return {
|
||||
id: agent.id,
|
||||
@@ -652,57 +648,43 @@ export class AgentService {
|
||||
)
|
||||
}
|
||||
|
||||
async ensureSystemEmbeddingAgents(): Promise<void> {
|
||||
const envVal = process.env.ENABLE_EMBEDDING_AGENT
|
||||
if (envVal !== 'true' && envVal !== 'false') {
|
||||
return
|
||||
}
|
||||
async ensureSystemAgents(): Promise<void> {
|
||||
if (!getSystemAgentSetting('embedding') && !getSystemAgentSetting('transcription')) return
|
||||
|
||||
const teams = await this.prismaClient.team.findMany({
|
||||
orderBy: { id: 'desc' },
|
||||
select: { id: true },
|
||||
})
|
||||
|
||||
for (const team of teams) {
|
||||
await this.ensureEmbeddingAgentForTeam(team.id)
|
||||
await this.ensureSystemAgentsForTeam(team.id)
|
||||
}
|
||||
}
|
||||
|
||||
async ensureEmbeddingAgentForTeam(teamId: string): Promise<void> {
|
||||
const envVal = process.env.ENABLE_EMBEDDING_AGENT
|
||||
if (envVal !== 'true' && envVal !== 'false') {
|
||||
return
|
||||
}
|
||||
async ensureSystemAgentsForTeam(teamId: string): Promise<void> {
|
||||
for (const type of ['embedding', 'transcription'] as const) {
|
||||
const setting = getSystemAgentSetting(type)
|
||||
if (!setting) continue
|
||||
|
||||
const existing = await this.prismaClient.agent.findFirst({
|
||||
where: {
|
||||
teamId,
|
||||
type: 'embedding',
|
||||
},
|
||||
})
|
||||
await this.inTransaction(async (tx) => {
|
||||
await tx.$queryRaw`SELECT id FROM teams WHERE id = ${teamId} FOR UPDATE`
|
||||
const existing = await tx.agent.findFirst({
|
||||
where: { teamId, type },
|
||||
})
|
||||
|
||||
if (envVal === 'true') {
|
||||
if (!existing) {
|
||||
await this.createAgent({
|
||||
teamId,
|
||||
name: 'embedding-agent',
|
||||
type: 'embedding',
|
||||
avatar: 'avatar-1',
|
||||
thinkingLevel: 'off',
|
||||
enabled: true,
|
||||
})
|
||||
} else if (!existing.enabled) {
|
||||
await this.prismaClient.agent.update({
|
||||
where: { id: existing.id },
|
||||
data: { enabled: true },
|
||||
})
|
||||
}
|
||||
} else if (envVal === 'false') {
|
||||
if (existing && existing.enabled) {
|
||||
await this.prismaClient.agent.update({
|
||||
where: { id: existing.id },
|
||||
data: { enabled: false },
|
||||
})
|
||||
}
|
||||
if (existing && existing.enabled !== setting.enabled) {
|
||||
await tx.agent.update({ where: { id: existing.id }, data: { enabled: setting.enabled } })
|
||||
} else if (!existing && setting.enabled) {
|
||||
await new AgentService(tx).createAgent({
|
||||
teamId,
|
||||
name: type === 'embedding' ? 'embedding-agent' : setting.name,
|
||||
type,
|
||||
avatar: 'avatar-1',
|
||||
thinkingLevel: 'off',
|
||||
enabled: true,
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { AgentType } from '@shumai/dtos'
|
||||
|
||||
const systemAgentSettings = {
|
||||
embedding: { envKey: 'ENABLE_EMBEDDING_AGENT', name: 'Embedding agent' },
|
||||
transcription: { envKey: 'ENABLE_TRANSCRIPTION_AGENT', name: 'Transcript Agent' },
|
||||
} as const
|
||||
|
||||
export function getSystemAgentSetting(type: AgentType) {
|
||||
if (type !== 'embedding' && type !== 'transcription') return undefined
|
||||
|
||||
const { envKey, name } = systemAgentSettings[type]
|
||||
const value = process.env[envKey]
|
||||
if (value !== 'true' && value !== 'false') return undefined
|
||||
|
||||
return { name, enabled: value === 'true' }
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
|
||||
export interface IntegrationEnvKeys {
|
||||
url: string[]
|
||||
@@ -12,6 +13,7 @@ export interface IntegrationDefinition<TKey extends keyof PrismaJson.Settings> {
|
||||
name: string
|
||||
settingsKey: TKey
|
||||
envKeys: IntegrationEnvKeys
|
||||
requireSettingsRead?: boolean
|
||||
}
|
||||
|
||||
export interface ResolvedIntegrationConfig {
|
||||
@@ -45,7 +47,7 @@ function getFirstEnvValue(keys?: string[]): string | undefined {
|
||||
|
||||
export async function resolveIntegrationConfig<TKey extends keyof PrismaJson.Settings>(
|
||||
def: IntegrationDefinition<TKey>,
|
||||
teamId?: string,
|
||||
teamId?: string | null,
|
||||
): Promise<ResolvedIntegrationConfig> {
|
||||
const envUrl = getFirstEnvValue(def.envKeys.url)
|
||||
const envUsername = getFirstEnvValue(def.envKeys.username)
|
||||
@@ -60,12 +62,13 @@ export async function resolveIntegrationConfig<TKey extends keyof PrismaJson.Set
|
||||
}
|
||||
}
|
||||
|
||||
if (teamId) {
|
||||
if (teamId || teamId === null) {
|
||||
try {
|
||||
const team = await prisma.team.findUnique({
|
||||
where: { id: teamId },
|
||||
select: { settings: true },
|
||||
})
|
||||
// Instance-wide consumers use the single team when they have no team ID.
|
||||
const team =
|
||||
teamId === null
|
||||
? await prisma.team.findFirst({ orderBy: { id: 'desc' }, select: { settings: true } })
|
||||
: await prisma.team.findUnique({ where: { id: teamId }, select: { settings: true } })
|
||||
const teamSettings = team?.settings as PrismaJson.Settings | null
|
||||
const serviceSettings = teamSettings?.[def.settingsKey] as
|
||||
{ url?: string; username?: string; password?: string } | undefined
|
||||
@@ -79,6 +82,7 @@ export async function resolveIntegrationConfig<TKey extends keyof PrismaJson.Set
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
if (def.requireSettingsRead) throw err
|
||||
logger.error({ err, teamId }, `Failed to load team ${def.name} settings`)
|
||||
}
|
||||
}
|
||||
@@ -108,9 +112,9 @@ export async function updateIntegrationSettings<TKey extends keyof PrismaJson.Se
|
||||
): Promise<IntegrationSettingsResponse> {
|
||||
const currentConfig = await resolveIntegrationConfig(def, teamId)
|
||||
if (currentConfig.isEnv) {
|
||||
throw new Error(
|
||||
`${def.name} settings are configured via environment variables and cannot be edited`,
|
||||
)
|
||||
throw new HTTPException(400, {
|
||||
message: `${def.name} settings are configured via environment variables and cannot be edited`,
|
||||
})
|
||||
}
|
||||
|
||||
const team = await prisma.team.findUnique({
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { embeddingServerService } from './embedding-server'
|
||||
|
||||
describe('Embedding server settings', () => {
|
||||
setupTestDbHooks()
|
||||
let teamId: string
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.stubEnv('EMBEDDING_PROVIDER', undefined)
|
||||
vi.stubEnv('GEMMA_EMBEDDING_OPENAI_BASE_URL', undefined)
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Embedding integration', settings: { appearance: { hideAgent: true } } },
|
||||
})
|
||||
teamId = team.id
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('saves and clears the local URL, preserving other settings', async () => {
|
||||
await expect(
|
||||
embeddingServerService.updateSettings(teamId, ' http://embedding:9379/ '),
|
||||
).resolves.toEqual({
|
||||
url: 'http://embedding:9379',
|
||||
isEnvConfigured: false,
|
||||
})
|
||||
await expect(embeddingServerService.resolveRuntimeConfig(teamId)).resolves.toEqual({
|
||||
provider: 'gemma-embedding-2-openai',
|
||||
embeddingEndpoint: 'http://embedding:9379/v1/embeddings',
|
||||
transcriptionEndpoint: 'http://embedding:9379/v1/audio/transcriptions',
|
||||
})
|
||||
await expect(embeddingServerService.resolveRuntimeConfig()).resolves.toMatchObject({
|
||||
provider: 'gemma-embedding-2-openai',
|
||||
})
|
||||
await embeddingServerService.updateSettings(teamId, ' ')
|
||||
await expect(embeddingServerService.getSettings(teamId)).resolves.toMatchObject({
|
||||
url: undefined,
|
||||
isEnvConfigured: false,
|
||||
})
|
||||
await expect(embeddingServerService.resolveRuntimeConfig(teamId)).resolves.toMatchObject({
|
||||
provider: 'gemini-embedding-2',
|
||||
})
|
||||
const team = await prisma.team.findUniqueOrThrow({ where: { id: teamId } })
|
||||
expect(team.settings).toEqual({ appearance: { hideAgent: true } })
|
||||
})
|
||||
|
||||
it('keeps Compose environment configuration read-only and tests its effective URL', async () => {
|
||||
await embeddingServerService.updateSettings(teamId, 'https://saved.example/v1')
|
||||
vi.stubEnv('GEMMA_EMBEDDING_OPENAI_BASE_URL', 'http://embedding-server:9379/v1/')
|
||||
vi.stubEnv('EMBEDDING_PROVIDER', 'gemma-embedding-2-openai')
|
||||
const fetch = vi
|
||||
.spyOn(globalThis, 'fetch')
|
||||
.mockResolvedValue(Response.json({ data: [{ id: 'embeddinggemma-2' }] }))
|
||||
await expect(embeddingServerService.getSettings(teamId)).resolves.toEqual({
|
||||
url: 'http://embedding-server:9379/v1',
|
||||
isEnvConfigured: true,
|
||||
})
|
||||
await expect(embeddingServerService.resolveRuntimeConfig(teamId)).resolves.toEqual({
|
||||
provider: 'gemma-embedding-2-openai',
|
||||
embeddingEndpoint: 'http://embedding-server:9379/v1/embeddings',
|
||||
transcriptionEndpoint: 'http://embedding-server:9379/v1/audio/transcriptions',
|
||||
})
|
||||
await expect(embeddingServerService.updateSettings(teamId, '')).rejects.toMatchObject({
|
||||
status: 400,
|
||||
})
|
||||
await expect(
|
||||
embeddingServerService.testConnection(teamId, 'https://draft.example'),
|
||||
).resolves.toEqual({ ok: true })
|
||||
expect(fetch).toHaveBeenCalledExactlyOnceWith(
|
||||
'http://embedding-server:9379/v1/models',
|
||||
expect.objectContaining({ redirect: 'error' }),
|
||||
)
|
||||
vi.stubEnv('GEMMA_EMBEDDING_OPENAI_BASE_URL', undefined)
|
||||
await expect(embeddingServerService.getSettings(teamId)).resolves.toMatchObject({
|
||||
url: 'https://saved.example/v1',
|
||||
})
|
||||
})
|
||||
|
||||
it('respects explicit provider selection and accepts a full embedding endpoint', async () => {
|
||||
await embeddingServerService.updateSettings(
|
||||
teamId,
|
||||
'https://embedding.example/custom/v1/embeddings/',
|
||||
)
|
||||
vi.stubEnv('EMBEDDING_PROVIDER', 'gemini-embedding-2')
|
||||
await expect(embeddingServerService.resolveRuntimeConfig(teamId)).resolves.toEqual({
|
||||
provider: 'gemini-embedding-2',
|
||||
embeddingEndpoint: 'https://embedding.example/custom/v1/embeddings',
|
||||
transcriptionEndpoint: 'https://embedding.example/custom/v1/audio/transcriptions',
|
||||
})
|
||||
})
|
||||
|
||||
it.each([
|
||||
'file:///tmp/server',
|
||||
'https://user:pass@embedding.example',
|
||||
'https://example.test?token=x',
|
||||
'embedding:9379',
|
||||
])('rejects an invalid server URL (%s)', async (url) => {
|
||||
await expect(embeddingServerService.updateSettings(teamId, url)).rejects.toMatchObject({
|
||||
status: 400,
|
||||
})
|
||||
await expect(embeddingServerService.testConnection(teamId, url)).rejects.toMatchObject({
|
||||
status: 400,
|
||||
})
|
||||
})
|
||||
|
||||
it('tests an unsaved URL without changing settings and detects an incompatible endpoint', async () => {
|
||||
const fetch = vi
|
||||
.spyOn(globalThis, 'fetch')
|
||||
.mockResolvedValue(Response.json({ data: [{ id: 'another-model' }] }))
|
||||
await expect(
|
||||
embeddingServerService.testConnection(teamId, 'https://draft.example'),
|
||||
).resolves.toMatchObject({ ok: false })
|
||||
expect(fetch).toHaveBeenCalledWith('https://draft.example/v1/models', expect.any(Object))
|
||||
await expect(embeddingServerService.getSettings(teamId)).resolves.toMatchObject({
|
||||
url: undefined,
|
||||
})
|
||||
})
|
||||
|
||||
it('reports unreachable and HTTP failure responses', async () => {
|
||||
const fetch = vi
|
||||
.spyOn(globalThis, 'fetch')
|
||||
.mockRejectedValueOnce(new Error('socket error'))
|
||||
.mockResolvedValueOnce(new Response(null, { status: 401 }))
|
||||
await expect(embeddingServerService.testConnection(teamId)).resolves.toMatchObject({
|
||||
ok: false,
|
||||
})
|
||||
expect(fetch).not.toHaveBeenCalled()
|
||||
await expect(
|
||||
embeddingServerService.testConnection(teamId, 'https://draft.example'),
|
||||
).resolves.toMatchObject({ ok: false })
|
||||
await expect(
|
||||
embeddingServerService.testConnection(teamId, 'https://draft.example'),
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: expect.stringContaining('401'),
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,97 @@
|
||||
import {
|
||||
resolveIntegrationConfig,
|
||||
updateIntegrationSettings,
|
||||
type IntegrationDefinition,
|
||||
} from '@shumai/core/src/integrations/helper'
|
||||
import {
|
||||
updateEmbeddingServerSettingsRequestSchema,
|
||||
type EmbeddingServerSettingsResponse,
|
||||
} from '@shumai/dtos'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import { z } from 'zod'
|
||||
|
||||
const integration: IntegrationDefinition<'embeddingServer'> = {
|
||||
name: 'Embedding server',
|
||||
settingsKey: 'embeddingServer',
|
||||
envKeys: { url: ['GEMMA_EMBEDDING_OPENAI_BASE_URL'] },
|
||||
requireSettingsRead: true,
|
||||
}
|
||||
|
||||
export const LOCAL_EMBEDDING_PROVIDER = 'gemma-embedding-2-openai'
|
||||
const defaultLocalBaseUrl = 'http://localhost:9379/v1'
|
||||
|
||||
function getOpenAiBaseUrl(url: string): string {
|
||||
const baseUrl = url.replace(/\/embeddings$/, '')
|
||||
return baseUrl.endsWith('/v1') ? baseUrl : `${baseUrl}/v1`
|
||||
}
|
||||
|
||||
function getEmbeddingEndpoint(url: string): string {
|
||||
return url.endsWith('/embeddings') ? url : `${getOpenAiBaseUrl(url)}/embeddings`
|
||||
}
|
||||
|
||||
const modelListSchema = z.object({
|
||||
data: z.array(z.object({ id: z.string() })),
|
||||
})
|
||||
|
||||
export class EmbeddingServerService {
|
||||
async resolveRuntimeConfig(teamId?: string, providerOverride?: string) {
|
||||
const { url, isEnv } = await resolveIntegrationConfig(integration, teamId ?? null)
|
||||
const provider =
|
||||
providerOverride ||
|
||||
process.env.EMBEDDING_PROVIDER ||
|
||||
(url && !isEnv ? LOCAL_EMBEDDING_PROVIDER : 'gemini-embedding-2')
|
||||
const localUrl = url || defaultLocalBaseUrl
|
||||
return {
|
||||
provider,
|
||||
embeddingEndpoint: getEmbeddingEndpoint(localUrl),
|
||||
transcriptionEndpoint: `${getOpenAiBaseUrl(localUrl)}/audio/transcriptions`,
|
||||
}
|
||||
}
|
||||
|
||||
async getSettings(teamId: string): Promise<EmbeddingServerSettingsResponse> {
|
||||
const { url, isEnv } = await resolveIntegrationConfig(integration, teamId)
|
||||
return { url, isEnvConfigured: isEnv }
|
||||
}
|
||||
|
||||
async updateSettings(teamId: string, url: string): Promise<EmbeddingServerSettingsResponse> {
|
||||
const { url: validUrl } = this.validateUrl(url)
|
||||
const settings = await updateIntegrationSettings(integration, teamId, { url: validUrl })
|
||||
return { url: settings.url, isEnvConfigured: settings.isEnvConfigured }
|
||||
}
|
||||
|
||||
async testConnection(teamId: string, url?: string): Promise<{ ok: boolean; error?: string }> {
|
||||
const config = await resolveIntegrationConfig(integration, teamId)
|
||||
const target = config.isEnv || url === undefined ? config.url : this.validateUrl(url).url
|
||||
if (!target) return { ok: false, error: 'Server URL is required' }
|
||||
|
||||
const endpoint = getEmbeddingEndpoint(target.replace(/\/+$/, ''))
|
||||
try {
|
||||
const response = await fetch(endpoint.replace(/\/embeddings$/, '/models'), {
|
||||
redirect: 'error',
|
||||
signal: AbortSignal.timeout(5000),
|
||||
})
|
||||
if (!response.ok) {
|
||||
await response.body?.cancel()
|
||||
return { ok: false, error: `Server returned HTTP ${response.status}` }
|
||||
}
|
||||
|
||||
const models = modelListSchema.safeParse(await response.json().catch(() => undefined))
|
||||
if (!models.success || !models.data.data.some(({ id }) => id === 'embeddinggemma-2')) {
|
||||
return { ok: false, error: 'Server does not advertise the embeddinggemma-2 model' }
|
||||
}
|
||||
return { ok: true }
|
||||
} catch {
|
||||
return { ok: false, error: 'Could not reach the embedding server' }
|
||||
}
|
||||
}
|
||||
|
||||
private validateUrl(url: string) {
|
||||
const result = updateEmbeddingServerSettingsRequestSchema.safeParse({ url })
|
||||
if (!result.success) {
|
||||
throw new HTTPException(400, { message: result.error.issues[0]?.message })
|
||||
}
|
||||
return result.data
|
||||
}
|
||||
}
|
||||
|
||||
export const embeddingServerService = new EmbeddingServerService()
|
||||
@@ -1,10 +0,0 @@
|
||||
export function getGemmaOpenAiBaseUrl(): string {
|
||||
const baseUrl = process.env.GEMMA_EMBEDDING_OPENAI_BASE_URL || 'http://localhost:9379/v1'
|
||||
const url = baseUrl.replace(/\/+$/, '').replace(/\/embeddings$/, '')
|
||||
return url.endsWith('/v1') ? url : `${url}/v1`
|
||||
}
|
||||
|
||||
export function getGemmaEmbeddingEndpoint(): string {
|
||||
const baseUrl = process.env.GEMMA_EMBEDDING_OPENAI_BASE_URL?.replace(/\/+$/, '')
|
||||
return baseUrl?.endsWith('/embeddings') ? baseUrl : `${getGemmaOpenAiBaseUrl()}/embeddings`
|
||||
}
|
||||
@@ -4,19 +4,26 @@ import { LruTtlCache } from '@shumai/core/src/cache/lru-ttl-cache'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import sharp from 'sharp'
|
||||
import { getGemmaEmbeddingEndpoint } from './gemma-embedding-endpoint'
|
||||
import { embeddingServerService, LOCAL_EMBEDDING_PROVIDER } from './embedding-server'
|
||||
|
||||
export function getImageEmbeddingDimensions(): 768 | 1536 {
|
||||
return process.env.EMBEDDING_PROVIDER === 'gemma-embedding-2-openai' ? 768 : 1536
|
||||
export function getImageEmbeddingDimensions(provider: string): 768 | 1536 {
|
||||
return provider === LOCAL_EMBEDDING_PROVIDER ? 768 : 1536
|
||||
}
|
||||
|
||||
export class ImageEmbeddingService {
|
||||
private readonly cache = new LruTtlCache<string, number[]>(100)
|
||||
|
||||
async generateEmbedding(image: string, teamId: string): Promise<number[]> {
|
||||
const dimensions = getImageEmbeddingDimensions()
|
||||
const { provider, embeddingEndpoint } =
|
||||
await embeddingServerService.resolveRuntimeConfig(teamId)
|
||||
const dimensions = getImageEmbeddingDimensions(provider)
|
||||
const digest = createHash('sha256').update(image).digest('hex')
|
||||
const cacheKey = `${teamId}:${dimensions}:${digest}`
|
||||
const cacheKey = JSON.stringify([
|
||||
teamId,
|
||||
dimensions,
|
||||
dimensions === 768 ? embeddingEndpoint : null,
|
||||
digest,
|
||||
])
|
||||
const cached = this.cache.get(cacheKey)
|
||||
if (cached) return cached
|
||||
|
||||
@@ -37,7 +44,7 @@ export class ImageEmbeddingService {
|
||||
const signal = AbortSignal.timeout(15000)
|
||||
embedding =
|
||||
dimensions === 768
|
||||
? await this.embedWithGemma(image, signal)
|
||||
? await this.embedWithGemma(embeddingEndpoint, image, signal)
|
||||
: await this.embedWithGemini(image, signal)
|
||||
if (
|
||||
!embedding ||
|
||||
@@ -73,8 +80,8 @@ export class ImageEmbeddingService {
|
||||
return response.embeddings?.[0]?.values
|
||||
}
|
||||
|
||||
private async embedWithGemma(image: string, signal: AbortSignal) {
|
||||
const response = await fetch(getGemmaEmbeddingEndpoint(), {
|
||||
private async embedWithGemma(endpoint: string, image: string, signal: AbortSignal) {
|
||||
const response = await fetch(endpoint, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
|
||||
@@ -9,6 +9,7 @@ import { PaginatedData, decodeCursor, encodeCursor, PageInfo } from '@shumai/cor
|
||||
import { generateSearchNgrams } from '@shumai/core/src/utils/ngram'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import { getImageEmbeddingDimensions, imageEmbeddingService } from './image-embedding'
|
||||
import { embeddingServerService } from './embedding-server'
|
||||
import { SqlQueryBuilder } from './sql-query-builder'
|
||||
import { TextEmbeddingService, textEmbeddingService } from './text-embedding'
|
||||
|
||||
@@ -266,7 +267,7 @@ export class SearchService {
|
||||
if (!project) throw new HTTPException(404, { message: 'Project folder not found.' })
|
||||
|
||||
await this.requireEmbeddingAgent(project.teamId)
|
||||
const dimensions = getImageEmbeddingDimensions()
|
||||
let dimensions: 768 | 1536
|
||||
let vector: string
|
||||
let excludeAssetId: string | undefined
|
||||
if (req.sourceAssetId) {
|
||||
@@ -274,6 +275,8 @@ export class SearchService {
|
||||
throw new HTTPException(400, { message: 'Find similar requires the project root folder.' })
|
||||
}
|
||||
|
||||
const { provider } = await embeddingServerService.resolveRuntimeConfig(project.teamId)
|
||||
dimensions = getImageEmbeddingDimensions(provider)
|
||||
const column = dimensions === 768 ? Prisma.sql`embedding_768` : Prisma.sql`embedding`
|
||||
const [source] = await this.prismaClient.$queryRaw<
|
||||
{ vector: string | null; excludeAssetId: string }[]
|
||||
@@ -302,9 +305,9 @@ export class SearchService {
|
||||
vector = source.vector
|
||||
excludeAssetId = source.excludeAssetId
|
||||
} else if (req.image) {
|
||||
vector = JSON.stringify(
|
||||
await imageEmbeddingService.generateEmbedding(req.image, project.teamId),
|
||||
)
|
||||
const embedding = await imageEmbeddingService.generateEmbedding(req.image, project.teamId)
|
||||
dimensions = embedding.length === 768 ? 768 : 1536
|
||||
vector = JSON.stringify(embedding)
|
||||
} else {
|
||||
throw new HTTPException(400, { message: 'Provide a search image or source asset.' })
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { GoogleGenAI } from '@google/genai'
|
||||
import { LruTtlCache } from '@shumai/core/src/cache/lru-ttl-cache'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { getGemmaEmbeddingEndpoint } from './gemma-embedding-endpoint'
|
||||
import { embeddingServerService, LOCAL_EMBEDDING_PROVIDER } from './embedding-server'
|
||||
|
||||
export interface TextEmbeddingUsage {
|
||||
model: string
|
||||
@@ -46,12 +46,19 @@ export class TextEmbeddingService {
|
||||
throw new Error('Text to embed must not be empty')
|
||||
}
|
||||
|
||||
const provider = options?.provider || process.env.EMBEDDING_PROVIDER || 'gemini-embedding-2'
|
||||
const model =
|
||||
options?.model ||
|
||||
(provider === 'gemma-embedding-2-openai' ? 'embeddinggemma-2' : 'gemini-embedding-2')
|
||||
const { provider, embeddingEndpoint } = await embeddingServerService.resolveRuntimeConfig(
|
||||
options?.teamId,
|
||||
options?.provider,
|
||||
)
|
||||
const isLocal = provider === LOCAL_EMBEDDING_PROVIDER
|
||||
const model = options?.model || (isLocal ? 'embeddinggemma-2' : 'gemini-embedding-2')
|
||||
|
||||
const cacheKey = `${provider}:${model}:${trimmedText}`
|
||||
const cacheKey = JSON.stringify([
|
||||
provider,
|
||||
isLocal ? embeddingEndpoint : null,
|
||||
model,
|
||||
trimmedText,
|
||||
])
|
||||
if (!options?.skipCache) {
|
||||
const cachedVector = this.cache.get(cacheKey)
|
||||
if (cachedVector) {
|
||||
@@ -67,8 +74,8 @@ export class TextEmbeddingService {
|
||||
const signal = options?.signal ?? AbortSignal.timeout(15000)
|
||||
|
||||
let result: TextEmbeddingResult
|
||||
if (provider === 'gemma-embedding-2-openai') {
|
||||
result = await this.callGemmaEmbeddingServer(trimmedText, model, signal)
|
||||
if (isLocal) {
|
||||
result = await this.callGemmaEmbeddingServer(embeddingEndpoint, trimmedText, model, signal)
|
||||
} else {
|
||||
result = await this.callGeminiEmbedding(trimmedText, model, signal)
|
||||
}
|
||||
@@ -140,11 +147,12 @@ export class TextEmbeddingService {
|
||||
}
|
||||
|
||||
private async callGemmaEmbeddingServer(
|
||||
endpoint: string,
|
||||
text: string,
|
||||
model: string,
|
||||
signal: AbortSignal,
|
||||
): Promise<TextEmbeddingResult> {
|
||||
const response = await fetch(getGemmaEmbeddingEndpoint(), {
|
||||
const response = await fetch(endpoint, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
|
||||
@@ -368,6 +368,8 @@ describe('TeamService', () => {
|
||||
const settings = await teamService.getSettings(team.id)
|
||||
expect(settings).toEqual({
|
||||
semanticSearchEnabled: false,
|
||||
transcriptionAgentManagedByEnv: false,
|
||||
embeddingServer: { url: undefined, isEnvConfigured: false },
|
||||
transcode: {
|
||||
videoStrategy: 'best_match',
|
||||
videoResolutions: ['480p', '720p', '1080p', '1440p', '2160p'],
|
||||
@@ -404,6 +406,8 @@ describe('TeamService', () => {
|
||||
expect(newSettings).toEqual({
|
||||
theme: 'dark',
|
||||
semanticSearchEnabled: false,
|
||||
transcriptionAgentManagedByEnv: false,
|
||||
embeddingServer: { url: undefined, isEnvConfigured: false },
|
||||
transcode: {
|
||||
videoStrategy: 'best_match',
|
||||
videoResolutions: ['480p', '720p', '1080p', '1440p', '2160p'],
|
||||
@@ -449,6 +453,8 @@ describe('TeamService', () => {
|
||||
const finalSettings = await teamService.getSettings(team.id)
|
||||
expect(finalSettings).toEqual({
|
||||
theme: 'dark',
|
||||
transcriptionAgentManagedByEnv: false,
|
||||
embeddingServer: { url: undefined, isEnvConfigured: false },
|
||||
transcode: {
|
||||
videoStrategy: 'multi',
|
||||
videoResolutions: ['720p', '1080p'],
|
||||
|
||||
@@ -7,8 +7,10 @@ import { getAvatarUrl } from '@shumai/core/src/user/avatar'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import { getAllowedAgentRoles } from '@shumai/core/src/agent/permissions'
|
||||
import { AgentService, agentService } from '@shumai/core/src/agent/agent'
|
||||
import { getSystemAgentSetting } from '@shumai/core/src/agent/system-agents'
|
||||
import { turntableService } from '@shumai/core/src/turntable/turntable'
|
||||
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
|
||||
import { embeddingServerService } from '@shumai/core/src/search/embedding-server'
|
||||
import {
|
||||
getArchiveStorageConfig,
|
||||
isArchiveStorageEnabled,
|
||||
@@ -50,7 +52,7 @@ export class TeamService {
|
||||
},
|
||||
})
|
||||
await providerService.initBuiltinProviders(team.id)
|
||||
await agentService.ensureEmbeddingAgentForTeam(team.id)
|
||||
await agentService.ensureSystemAgentsForTeam(team.id)
|
||||
}
|
||||
|
||||
return team
|
||||
@@ -94,8 +96,7 @@ export class TeamService {
|
||||
// but the TransactionClient is compatible with the methods we use.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await new ProviderService(tx as any).initBuiltinProviders(team.id)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await new AgentService(tx as any).ensureEmbeddingAgentForTeam(team.id)
|
||||
await new AgentService(tx).ensureSystemAgentsForTeam(team.id)
|
||||
|
||||
return this.toTeamInfo(updatedTeam)
|
||||
})
|
||||
@@ -359,6 +360,8 @@ export class TeamService {
|
||||
|
||||
settings.turntable = await turntableService.getSettings(teamId)
|
||||
settings.gotenberg = await gotenbergService.getSettings(teamId)
|
||||
settings.embeddingServer = await embeddingServerService.getSettings(teamId)
|
||||
settings.transcriptionAgentManagedByEnv = getSystemAgentSetting('transcription') !== undefined
|
||||
|
||||
const archiveConfig = getArchiveStorageConfig()
|
||||
if (!archiveConfig.enabled) {
|
||||
|
||||
@@ -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'),
|
||||
|
||||
@@ -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' })
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user