mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-27 11:24:43 +00:00
feat(agent): support gemma-embedding-2-openai provider (#475)
* feat(agent): support gemma-embedding-2-openai provider Add support for local LiteRT-LM Gemma Embedding 2 provider with 768-dimensional vector embeddings, environment-configured read-only embedding agents, 16-frame uniform sampling for video chunks, and automatic WebP-to-JPEG conversion. * refactor(agent): remove unused legacy generateEmbeddingActivity * chore(agent): align sharp version to 0.35.4 * refactor(agent): rename embedding server env to GEMMA_EMBEDDING_OPENAI_BASE_URL * refactor(agent,transcode): use native Bun.Archive for video chunk frames * fix(transcode,agent): populate buffer entries in Bun.Archive and validate frame sizes
This commit is contained in:
@@ -976,4 +976,85 @@ describe('AgentService', () => {
|
||||
expect(ids).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('ensureEmbeddingAgent', () => {
|
||||
test('creates embedding agent when ENABLE_EMBEDDING_AGENT is true', async () => {
|
||||
const db = prisma
|
||||
const svc = new AgentService()
|
||||
const { team } = await setupTestData(db)
|
||||
|
||||
process.env.ENABLE_EMBEDDING_AGENT = 'true'
|
||||
try {
|
||||
await svc.ensureEmbeddingAgentForTeam(team.id)
|
||||
const agent = await db.agent.findFirst({
|
||||
where: { teamId: team.id, type: 'embedding' },
|
||||
include: { user: true, skills: { include: { skill: true } }, mcpServers: true },
|
||||
})
|
||||
expect(agent).toBeDefined()
|
||||
const info = await svc.toAgentInfo(agent!)
|
||||
expect(info.name).toBe('embedding-agent')
|
||||
expect(info.type).toBe('embedding')
|
||||
expect(info.enabled).toBe(true)
|
||||
expect(info.avatarPreset).toBe('avatar-1')
|
||||
expect(info.avatar).toContain('avatar-1.webp')
|
||||
expect(info.readOnly).toBe(true)
|
||||
|
||||
// Ensure idempotency
|
||||
await svc.ensureEmbeddingAgentForTeam(team.id)
|
||||
const count = await db.agent.count({
|
||||
where: { teamId: team.id, type: 'embedding' },
|
||||
})
|
||||
expect(count).toBe(1)
|
||||
} finally {
|
||||
delete process.env.ENABLE_EMBEDDING_AGENT
|
||||
}
|
||||
})
|
||||
|
||||
test('enables existing embedding agent when ENABLE_EMBEDDING_AGENT is true', async () => {
|
||||
const db = prisma
|
||||
const svc = new AgentService()
|
||||
const { team } = await setupTestData(db)
|
||||
|
||||
const bot = await db.user.create({
|
||||
data: { name: 'Existing Embedding', email: 'existing-emb@shumai.ai', type: 'agent' },
|
||||
})
|
||||
await db.agent.create({
|
||||
data: {
|
||||
id: bot.id,
|
||||
teamId: team.id,
|
||||
type: 'embedding',
|
||||
enabled: false,
|
||||
config: { provider: '', model: '' },
|
||||
},
|
||||
})
|
||||
|
||||
process.env.ENABLE_EMBEDDING_AGENT = 'true'
|
||||
try {
|
||||
await svc.ensureEmbeddingAgentForTeam(team.id)
|
||||
const agent = await db.agent.findFirst({
|
||||
where: { teamId: team.id, type: 'embedding' },
|
||||
include: { user: true, skills: { include: { skill: true } }, mcpServers: true },
|
||||
})
|
||||
expect(agent?.id).toBe(bot.id)
|
||||
expect(agent?.enabled).toBe(true)
|
||||
const info = await svc.toAgentInfo(agent!)
|
||||
expect(info.readOnly).toBe(true)
|
||||
} finally {
|
||||
delete process.env.ENABLE_EMBEDDING_AGENT
|
||||
}
|
||||
})
|
||||
|
||||
test('does nothing when ENABLE_EMBEDDING_AGENT is false or not set', async () => {
|
||||
const db = prisma
|
||||
const svc = new AgentService()
|
||||
const team = await db.team.create({ data: { name: 'Team No Agent' } })
|
||||
|
||||
delete process.env.ENABLE_EMBEDDING_AGENT
|
||||
await svc.ensureEmbeddingAgentForTeam(team.id)
|
||||
const agent = await db.agent.findFirst({
|
||||
where: { teamId: team.id, type: 'embedding' },
|
||||
})
|
||||
expect(agent).toBeNull()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -43,8 +43,8 @@ interface AgentInfoSource {
|
||||
config: unknown
|
||||
soul: string | null
|
||||
user: { name: string; image: string | null }
|
||||
skills: Array<{ id: string; skillId: string; skill: { id: string; name: string } }>
|
||||
mcpServers: Array<{ mcpServerId: string }>
|
||||
skills?: Array<{ id: string; skillId: string; skill: { id: string; name: string } }>
|
||||
mcpServers?: Array<{ mcpServerId: string }>
|
||||
}
|
||||
|
||||
function extractS3Key(urlOrKey?: string | null): string | null | undefined {
|
||||
@@ -462,6 +462,8 @@ export class AgentService {
|
||||
*/
|
||||
async toAgentInfo(agent: AgentInfoSource): Promise<AgentInfo> {
|
||||
const config = agent.config as unknown as PrismaJson.AgentConfig
|
||||
const isReadOnly = agent.type === 'embedding' && process.env.ENABLE_EMBEDDING_AGENT === 'true'
|
||||
|
||||
return {
|
||||
id: agent.id,
|
||||
name: agent.user.name,
|
||||
@@ -475,13 +477,14 @@ export class AgentService {
|
||||
thinkingLevel: config.thinkingLevel || 'off',
|
||||
systemPrompt: config.systemPrompt,
|
||||
soul: agent.soul || undefined,
|
||||
skills: agent.skills.map((s) => ({
|
||||
skills: (agent.skills || []).map((s) => ({
|
||||
id: s.id,
|
||||
skillId: s.skillId,
|
||||
skill: s.skill,
|
||||
})),
|
||||
mcpServerIds: (agent.mcpServers || []).map((m) => m.mcpServerId),
|
||||
deniedTools: config.deniedTools || [],
|
||||
readOnly: isReadOnly,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -718,6 +721,49 @@ export class AgentService {
|
||||
params,
|
||||
)
|
||||
}
|
||||
|
||||
async ensureSystemEmbeddingAgents(): Promise<void> {
|
||||
if (process.env.ENABLE_EMBEDDING_AGENT !== 'true') {
|
||||
return
|
||||
}
|
||||
|
||||
const teams = await this.prismaClient.team.findMany({
|
||||
select: { id: true },
|
||||
})
|
||||
|
||||
for (const team of teams) {
|
||||
await this.ensureEmbeddingAgentForTeam(team.id)
|
||||
}
|
||||
}
|
||||
|
||||
async ensureEmbeddingAgentForTeam(teamId: string): Promise<void> {
|
||||
if (process.env.ENABLE_EMBEDDING_AGENT !== 'true') {
|
||||
return
|
||||
}
|
||||
|
||||
const existing = await this.prismaClient.agent.findFirst({
|
||||
where: {
|
||||
teamId,
|
||||
type: 'embedding',
|
||||
},
|
||||
})
|
||||
|
||||
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 },
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const agentService = new AgentService()
|
||||
|
||||
@@ -857,6 +857,154 @@ describe('SearchService', () => {
|
||||
|
||||
mockExecuteWait.mockRestore()
|
||||
})
|
||||
|
||||
it('matches and sorts 768-dimensional embeddings using embedding_768 column', async () => {
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'semantic-user-768', email: 'semantic-user-768@example.com', type: 'human' },
|
||||
})
|
||||
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'semantic-team-768' },
|
||||
})
|
||||
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'semantic-project-768', teamId: team.id },
|
||||
})
|
||||
|
||||
const botUser = await prisma.user.create({
|
||||
data: { name: 'Embedding Bot 768', email: 'emb-768@example.com', type: 'agent' },
|
||||
})
|
||||
const provider = await prisma.provider.create({
|
||||
data: {
|
||||
name: 'gemma',
|
||||
teamId: team.id,
|
||||
config: { api: 'openai', apiKey: 'key' } as unknown as PrismaJson.ProviderConfig,
|
||||
},
|
||||
})
|
||||
const model = await prisma.model.create({
|
||||
data: {
|
||||
modelId: 'embeddinggemma-2',
|
||||
name: 'EmbeddingGemma 2',
|
||||
providerId: provider.id,
|
||||
config: {
|
||||
reasoning: false,
|
||||
input: ['text'],
|
||||
contextWindow: 1000,
|
||||
maxTokens: 1000,
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
} as unknown as PrismaJson.ModelConfig,
|
||||
},
|
||||
})
|
||||
await prisma.agent.create({
|
||||
data: {
|
||||
id: botUser.id,
|
||||
teamId: team.id,
|
||||
type: 'embedding',
|
||||
enabled: true,
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
config: { provider: 'gemma-embedding-2-openai', model: 'embeddinggemma-2' },
|
||||
},
|
||||
})
|
||||
|
||||
const rootFolder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'root-768',
|
||||
type: AssetType.folder,
|
||||
projectId: project.id,
|
||||
creatorId: user.id,
|
||||
status: 'uploaded',
|
||||
},
|
||||
})
|
||||
|
||||
const videoAssetA = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'VideoA_768.mp4',
|
||||
type: AssetType.file,
|
||||
mediaType: 'video/mp4',
|
||||
projectId: project.id,
|
||||
parentId: rootFolder.id,
|
||||
creatorId: user.id,
|
||||
status: 'uploaded',
|
||||
},
|
||||
})
|
||||
|
||||
const videoAssetB = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'VideoB_768.mp4',
|
||||
type: AssetType.file,
|
||||
mediaType: 'video/mp4',
|
||||
projectId: project.id,
|
||||
parentId: rootFolder.id,
|
||||
creatorId: user.id,
|
||||
status: 'uploaded',
|
||||
},
|
||||
})
|
||||
|
||||
const arrA1 = Array(768).fill(0)
|
||||
arrA1[0] = 1.0
|
||||
const vectorA1 = JSON.stringify(arrA1)
|
||||
|
||||
const arrB1 = Array(768).fill(0)
|
||||
arrB1[0] = 1.0
|
||||
arrB1[1] = 1.0
|
||||
const vectorB1 = JSON.stringify(arrB1)
|
||||
|
||||
await prisma.$executeRaw`
|
||||
INSERT INTO asset_embeddings (id, asset_id, embedding_768, start_time, end_time, created_at, updated_at)
|
||||
VALUES (
|
||||
'chunk-768-a1',
|
||||
${videoAssetA.id},
|
||||
${vectorA1}::vector,
|
||||
0.0,
|
||||
10.0,
|
||||
NOW(),
|
||||
NOW()
|
||||
)
|
||||
`
|
||||
await prisma.$executeRaw`
|
||||
INSERT INTO asset_embeddings (id, asset_id, embedding_768, start_time, end_time, created_at, updated_at)
|
||||
VALUES (
|
||||
'chunk-768-b1',
|
||||
${videoAssetB.id},
|
||||
${vectorB1}::vector,
|
||||
5.0,
|
||||
15.0,
|
||||
NOW(),
|
||||
NOW()
|
||||
)
|
||||
`
|
||||
|
||||
// Query vector with 768 dims pointing along dimension 0
|
||||
const queryVector = Array(768).fill(0)
|
||||
queryVector[0] = 1.0
|
||||
const mockExecuteWait = vi
|
||||
.spyOn(workflowService, 'executeWait')
|
||||
.mockImplementation(async (task) => {
|
||||
return {
|
||||
...task,
|
||||
status: 'completed',
|
||||
output: {
|
||||
embedding: queryVector,
|
||||
},
|
||||
} as unknown as typeof task
|
||||
})
|
||||
|
||||
const result = await searchService.search(rootFolder.id, {
|
||||
recursively: true,
|
||||
assetType: 'file',
|
||||
operator: 'AND',
|
||||
conditions: [],
|
||||
query: 'find 768 dim match',
|
||||
isSemantic: true,
|
||||
})
|
||||
|
||||
expect(result.data.length).toBeGreaterThanOrEqual(2)
|
||||
expect(result.data[0].id).toBe(videoAssetA.id)
|
||||
expect(result.data[1].id).toBe(videoAssetB.id)
|
||||
|
||||
mockExecuteWait.mockRestore()
|
||||
})
|
||||
})
|
||||
|
||||
describe('totalSize calculation', () => {
|
||||
|
||||
@@ -68,12 +68,21 @@ export class SearchService {
|
||||
|
||||
// 3. Construct raw SQL using SqlQueryBuilder
|
||||
const vectorJson = JSON.stringify(queryVector)
|
||||
const is768 = queryVector.length === 768
|
||||
const distanceExpr = is768
|
||||
? Prisma.sql`(ae.embedding_768 <=> ${vectorJson}::vector)`
|
||||
: Prisma.sql`(ae.embedding <=> ${vectorJson}::vector)`
|
||||
const notNullCond = is768
|
||||
? Prisma.sql`ae.embedding_768 IS NOT NULL`
|
||||
: Prisma.sql`ae.embedding IS NOT NULL`
|
||||
|
||||
const builder = new SqlQueryBuilder()
|
||||
.select(
|
||||
Prisma.sql`a.id as "assetId", ae.start_time as "startTime", ae.end_time as "endTime", (ae.embedding <=> ${vectorJson}::vector) as "distance"`,
|
||||
Prisma.sql`a.id as "assetId", ae.start_time as "startTime", ae.end_time as "endTime", ${distanceExpr} as "distance"`,
|
||||
)
|
||||
.from(Prisma.sql`assets a JOIN asset_embeddings ae ON a.id = ae.asset_id`)
|
||||
.addWhere(Prisma.sql`a.is_deleted = false`)
|
||||
.addWhere(notNullCond)
|
||||
|
||||
if (targetFolderIds.length > 0) {
|
||||
builder.addWhere(Prisma.sql`a.parent_id = ANY(${targetFolderIds})`)
|
||||
@@ -158,6 +167,7 @@ export class SearchService {
|
||||
.select(Prisma.sql`COUNT(*)`)
|
||||
.from(Prisma.sql`assets a JOIN asset_embeddings ae ON a.id = ae.asset_id`)
|
||||
.addWhere(Prisma.sql`a.is_deleted = false`)
|
||||
.addWhere(notNullCond)
|
||||
|
||||
if (targetFolderIds.length > 0) {
|
||||
countBuilder.addWhere(Prisma.sql`a.parent_id = ANY(${targetFolderIds})`)
|
||||
|
||||
@@ -6,6 +6,7 @@ import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
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 { sandboxService } from '@shumai/core/src/sandbox/sandbox-service'
|
||||
import { turntableService } from '@shumai/core/src/turntable/turntable'
|
||||
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
|
||||
@@ -46,6 +47,7 @@ export class TeamService {
|
||||
},
|
||||
})
|
||||
await providerService.initBuiltinProviders(team.id)
|
||||
await agentService.ensureEmbeddingAgentForTeam(team.id)
|
||||
}
|
||||
|
||||
return team
|
||||
@@ -86,10 +88,12 @@ export class TeamService {
|
||||
},
|
||||
})
|
||||
|
||||
// We use 'any' here because ProviderService expects the full PrismaClient,
|
||||
// We use 'any' here because ProviderService/AgentService expect the full PrismaClient,
|
||||
// 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)
|
||||
|
||||
return this.toTeamInfo(updatedTeam)
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user