feat(search): add image similarity search (#537)

* feat(search): add image similarity search

* feat(search): support pasting image attachments
This commit is contained in:
Yiling-J
2026-11-21 10:32:46 +08:00
committed by GitHub
parent d8c20d6a11
commit 3943407093
25 changed files with 1475 additions and 294 deletions
@@ -0,0 +1,6 @@
export function getGemmaEmbeddingEndpoint(): string {
const baseUrl = process.env.GEMMA_EMBEDDING_OPENAI_BASE_URL || 'http://localhost:9379/v1'
const url = baseUrl.replace(/\/+$/, '')
if (url.endsWith('/embeddings')) return url
return url.endsWith('/v1') ? `${url}/embeddings` : `${url}/v1/embeddings`
}
@@ -0,0 +1,111 @@
import sharp from 'sharp'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ImageEmbeddingService } from './image-embedding'
const embedContent = vi.fn()
vi.mock('@google/genai', () => ({
// eslint-disable-next-line @typescript-eslint/naming-convention
GoogleGenAI: class {
models = { embedContent }
},
}))
async function jpeg(width = 32, height = 24) {
const buffer = await sharp({
create: { width, height, channels: 3, background: '#ffffff' },
})
.jpeg()
.toBuffer()
return buffer.toString('base64')
}
describe('ImageEmbeddingService', () => {
let service: ImageEmbeddingService
beforeEach(() => {
vi.stubEnv('EMBEDDING_PROVIDER', undefined)
vi.stubEnv('GEMINI_API_KEY', 'fake-key')
embedContent.mockReset()
service = new ImageEmbeddingService()
})
afterEach(() => {
vi.unstubAllEnvs()
vi.unstubAllGlobals()
})
it('embeds JPEG images with Gemini and caches the result by team and image', async () => {
const image = await jpeg()
const embedding = Array<number>(1536).fill(0.02)
embedContent.mockResolvedValue({ embeddings: [{ values: embedding }] })
expect(await service.generateEmbedding(image, 'team-a')).toEqual(embedding)
expect(await service.generateEmbedding(image, 'team-a')).toEqual(embedding)
expect(embedContent).toHaveBeenCalledTimes(1)
expect(embedContent).toHaveBeenCalledWith({
model: 'gemini-embedding-2',
contents: [{ inlineData: { data: image, mimeType: 'image/jpeg' } }],
config: { outputDimensionality: 1536, abortSignal: expect.any(AbortSignal) },
})
await service.generateEmbedding(image, 'team-b')
await service.generateEmbedding(await jpeg(18), 'team-a')
expect(embedContent).toHaveBeenCalledTimes(3)
})
it('uses the configured local Gemma endpoint and accepts portrait images', async () => {
vi.stubEnv('EMBEDDING_PROVIDER', 'gemma-embedding-2-openai')
vi.stubEnv('GEMMA_EMBEDDING_OPENAI_BASE_URL', 'http://embedding.test/custom/embeddings/')
const image = await jpeg(720, 1280)
const embedding = Array<number>(768).fill(0.02)
const fetchMock = vi.fn().mockResolvedValue(Response.json({ data: [{ embedding }] }))
vi.stubGlobal('fetch', fetchMock)
expect(await service.generateEmbedding(image, 'team-a')).toEqual(embedding)
expect(fetchMock).toHaveBeenCalledWith(
'http://embedding.test/custom/embeddings',
expect.objectContaining({
method: 'POST',
body: JSON.stringify({
model: 'embeddinggemma-2',
input: [
{
type: 'image_url',
// eslint-disable-next-line @typescript-eslint/naming-convention -- OpenAI request field
image_url: { url: `data:image/jpeg;base64,${image}` },
},
],
}),
}),
)
expect(embedContent).not.toHaveBeenCalled()
})
it('rejects invalid, non-JPEG, and oversized images before contacting the provider', async () => {
const png = await sharp({
create: { width: 32, height: 24, channels: 3, background: '#ffffff' },
})
.png()
.toBuffer()
for (const image of ['aW1hZ2U=', png.toString('base64'), await jpeg(1281, 200)]) {
await expect(service.generateEmbedding(image, 'team-a')).rejects.toMatchObject({
status: 400,
})
}
expect(embedContent).not.toHaveBeenCalled()
})
it('reports provider errors and allows the image to be retried', async () => {
const image = await jpeg()
const embedding = Array<number>(1536).fill(0.02)
embedContent
.mockRejectedValueOnce(new Error('Provider failed'))
.mockResolvedValueOnce({ embeddings: [{ values: [1, 2, 3] }] })
.mockResolvedValueOnce({ embeddings: [{ values: embedding }] })
await expect(service.generateEmbedding(image, 'team-a')).rejects.toMatchObject({ status: 502 })
await expect(service.generateEmbedding(image, 'team-a')).rejects.toMatchObject({ status: 502 })
expect(await service.generateEmbedding(image, 'team-a')).toEqual(embedding)
expect(embedContent).toHaveBeenCalledTimes(3)
})
})
@@ -0,0 +1,99 @@
import { createHash } from 'node:crypto'
import { GoogleGenAI } from '@google/genai'
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'
export function getImageEmbeddingDimensions(): 768 | 1536 {
return process.env.EMBEDDING_PROVIDER === 'gemma-embedding-2-openai' ? 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 digest = createHash('sha256').update(image).digest('hex')
const cacheKey = `${teamId}:${dimensions}:${digest}`
const cached = this.cache.get(cacheKey)
if (cached) return cached
const buffer = Buffer.from(image, 'base64')
const metadata = await sharp(buffer, { limitInputPixels: 1280 * 720 })
.metadata()
.catch(() => null)
if (
metadata?.format !== 'jpeg' ||
Math.max(metadata.width, metadata.height) > 1280 ||
Math.min(metadata.width, metadata.height) > 720
) {
throw new HTTPException(400, { message: 'Provide a JPEG image resized to 720p.' })
}
let embedding: number[] | undefined
try {
const signal = AbortSignal.timeout(15000)
embedding =
dimensions === 768
? await this.embedWithGemma(image, signal)
: await this.embedWithGemini(image, signal)
if (
!embedding ||
embedding.length !== dimensions ||
!embedding.every(Number.isFinite) ||
!embedding.some((value) => value !== 0)
) {
throw new Error('Invalid image embedding returned by provider')
}
} catch (err) {
logger.warn(
{ teamId, dimensions, errorName: err instanceof Error ? err.name : undefined },
'Failed to generate image search embedding',
)
throw new HTTPException(502, { message: 'Failed to generate image search embedding.' })
}
this.cache.set(cacheKey, embedding, 10 * 60 * 1000)
return embedding
}
private async embedWithGemini(image: string, signal: AbortSignal) {
const apiKey = process.env.GEMINI_API_KEY
if (!apiKey) throw new Error('GEMINI_API_KEY environment variable is not configured')
const ai = new GoogleGenAI({ apiKey: process.env[apiKey] || apiKey })
const response = await ai.models.embedContent({
model: 'gemini-embedding-2',
contents: [{ inlineData: { data: image, mimeType: 'image/jpeg' } }],
config: { outputDimensionality: 1536, abortSignal: signal },
})
return response.embeddings?.[0]?.values
}
private async embedWithGemma(image: string, signal: AbortSignal) {
const response = await fetch(getGemmaEmbeddingEndpoint(), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: 'embeddinggemma-2',
input: [
{
type: 'image_url',
// eslint-disable-next-line @typescript-eslint/naming-convention -- OpenAI request field
image_url: { url: `data:image/jpeg;base64,${image}` },
},
],
}),
signal,
})
if (!response.ok) throw new Error(`Embedding server returned status ${response.status}`)
const result = (await response.json()) as { data?: { embedding?: number[] }[] }
return result.data?.[0]?.embedding
}
}
export const imageEmbeddingService = new ImageEmbeddingService()
@@ -0,0 +1,199 @@
import { prisma, Prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { imageSearchRequestSchema } from '@shumai/dtos'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { imageEmbeddingService } from './image-embedding'
import { searchService } from './search'
function vector(dimensions: number, x: number, y = 0): number[] {
return [x, y, ...Array<number>(dimensions - 2).fill(0)]
}
async function insertEmbedding(
assetId: string,
embedding: number[],
startTime: number | null = null,
endTime: number | null = null,
) {
const column = embedding.length === 768 ? Prisma.sql`embedding_768` : Prisma.sql`embedding`
await prisma.$executeRaw`
INSERT INTO asset_embeddings (id, asset_id, ${column}, start_time, end_time, created_at, updated_at)
VALUES (gen_random_uuid()::text, ${assetId}, ${JSON.stringify(embedding)}::vector,
${startTime}, ${endTime}, NOW(), NOW())
`
}
async function createProjectAssets() {
const team = await prisma.team.create({ data: { name: 'Image search team' } })
const user = await prisma.user.create({
data: { name: 'Embedding agent', email: 'visual-search-agent@example.com', type: 'agent' },
})
const agent = await prisma.agent.create({
data: {
id: user.id,
teamId: team.id,
type: 'embedding',
config: { provider: 'google', model: 'gemini-embedding-2' },
},
})
const project = await prisma.project.create({ data: { name: 'Visual search', teamId: team.id } })
const root = await prisma.asset.create({
data: { name: 'Root', type: 'root', status: 'processed', projectId: project.id },
})
await prisma.project.update({ where: { id: project.id }, data: { rootFolderId: root.id } })
const subfolder = await prisma.asset.create({
data: {
name: 'Subfolder',
type: 'folder',
status: 'uploaded',
projectId: project.id,
parentId: root.id,
},
})
const file = (name: string, mediaType: string, parentId = root.id) =>
prisma.asset.create({
data: { name, mediaType, parentId, projectId: project.id, type: 'file', status: 'processed' },
})
const source = await file('source.jpg', 'image/jpeg', subfolder.id)
return { team, agent, root, subfolder, source, file }
}
describe('image search', () => {
setupTestDbHooks()
beforeEach(() => {
vi.stubEnv('ENABLE_EMBEDDING_AGENT', undefined)
vi.stubEnv('EMBEDDING_PROVIDER', 'gemini-embedding-2')
})
afterEach(() => {
vi.unstubAllEnvs()
vi.restoreAllMocks()
})
it('finds images and video segments across the project using the stored image vector', async () => {
const { root, source, file } = await createProjectAssets()
const image = await file('result.jpg', 'image/jpeg')
const video = await file('result.mp4', 'video/mp4')
const deleted = await file('deleted.jpg', 'image/jpeg')
const audio = await file('audio.mp3', 'audio/mpeg')
await prisma.asset.update({ where: { id: deleted.id }, data: { isDeleted: true } })
await insertEmbedding(source.id, vector(1536, 1))
await insertEmbedding(video.id, vector(1536, 1), 4, 12)
await insertEmbedding(video.id, vector(1536, 0, 1), 12, 20)
await insertEmbedding(image.id, vector(1536, 1, 1))
await insertEmbedding(deleted.id, vector(1536, 1))
await insertEmbedding(audio.id, vector(1536, 1))
const provider = vi.spyOn(imageEmbeddingService, 'generateEmbedding')
const request = { sourceAssetId: source.id }
const first = await searchService.searchByImage(
root.id,
imageSearchRequestSchema.parse({ ...request, first: 2 }),
)
expect(first.data.map((item) => item.id)).toEqual([video.id, image.id])
expect(first.data[0]).toMatchObject({ startTime: 4, endTime: 12 })
expect(first.pageInfo).toMatchObject({ total: 3, cursor: expect.any(String) })
const next = await searchService.searchByImage(
root.id,
imageSearchRequestSchema.parse({ ...request, first: 2, after: first.pageInfo.cursor }),
)
expect(next.data).toMatchObject([{ id: video.id, startTime: 12, endTime: 20 }])
expect(next.pageInfo.cursor).toBeUndefined()
const images = await searchService.searchByImage(
root.id,
imageSearchRequestSchema.parse({ ...request, mediaType: 'image' }),
)
const videos = await searchService.searchByImage(
root.id,
imageSearchRequestSchema.parse({ ...request, mediaType: 'video' }),
)
expect(images.data.map((item) => item.id)).toEqual([image.id])
expect(videos.data.map((item) => item.startTime)).toEqual([4, 12])
expect(provider).not.toHaveBeenCalled()
})
it('uses the active provider vector column and reports when an image needs indexing', async () => {
vi.stubEnv('EMBEDDING_PROVIDER', 'gemma-embedding-2-openai')
const { root, source, file } = await createProjectAssets()
const image = await file('result.jpg', 'image/jpeg')
const req = imageSearchRequestSchema.parse({ sourceAssetId: source.id })
await insertEmbedding(source.id, vector(1536, 1))
await expect(searchService.searchByImage(root.id, req)).rejects.toMatchObject({ status: 409 })
await insertEmbedding(source.id, vector(768, 1))
await insertEmbedding(image.id, vector(768, 1))
const result = await searchService.searchByImage(root.id, req)
expect(result.data.map((item) => item.id)).toEqual([image.id])
})
it('limits an uploaded-image search to the folder and applies metadata filters', async () => {
const { team, subfolder, source, file } = await createProjectAssets()
const match = await file('approved.png', 'image/png', subfolder.id)
const outside = await file('outside.png', 'image/png')
for (const asset of [match, source, outside]) {
await insertEmbedding(asset.id, vector(1536, 1))
}
for (const asset of [match, outside]) {
await prisma.assetMetadataValue.create({
data: { assetId: asset.id, fieldKey: 'status', stringValue: 'approved' },
})
}
const provider = vi
.spyOn(imageEmbeddingService, 'generateEmbedding')
.mockResolvedValue(vector(1536, 1))
const image = 'aW1hZ2U='
const result = await searchService.searchByImage(
subfolder.id,
imageSearchRequestSchema.parse({
image,
conditions: [{ field: 'status', operator: 'eq', value: 'approved' }],
}),
)
expect(provider).toHaveBeenCalledWith(image, team.id)
expect(result.data.map((item) => item.id)).toEqual([match.id])
})
it('requires a readable image from the project root scope', async () => {
const { team, root, subfolder, source, file } = await createProjectAssets()
const video = await file('video.mp4', 'video/mp4')
const other = await prisma.project.create({ data: { name: 'Other project', teamId: team.id } })
const otherImage = await prisma.asset.create({
data: {
name: 'other.jpeg',
mediaType: 'image/jpeg',
projectId: other.id,
type: 'file',
status: 'processed',
},
})
for (const id of [video.id, otherImage.id]) {
const req = imageSearchRequestSchema.parse({ sourceAssetId: id })
await expect(searchService.searchByImage(root.id, req)).rejects.toMatchObject({ status: 404 })
}
const req = imageSearchRequestSchema.parse({ sourceAssetId: source.id })
await expect(searchService.searchByImage(subfolder.id, req)).rejects.toMatchObject({
status: 400,
})
})
it('rejects both forms of image search when the agent is disabled', async () => {
const { agent, root, source } = await createProjectAssets()
vi.stubEnv('ENABLE_EMBEDDING_AGENT', 'false')
await expect(
searchService.searchByImage(
root.id,
imageSearchRequestSchema.parse({ sourceAssetId: source.id }),
),
).rejects.toMatchObject({ status: 422 })
vi.stubEnv('ENABLE_EMBEDDING_AGENT', undefined)
await prisma.agent.update({ where: { id: agent.id }, data: { enabled: false } })
const provider = vi.spyOn(imageEmbeddingService, 'generateEmbedding')
await expect(
searchService.searchByImage(root.id, imageSearchRequestSchema.parse({ image: 'aW1hZ2U=' })),
).rejects.toMatchObject({ status: 422 })
expect(provider).not.toHaveBeenCalled()
})
})
+177 -180
View File
@@ -1,11 +1,11 @@
import { prisma } from '@shumai/db'
import { Prisma, AssetType } from '@shumai/db'
import { AssetService, assetService } from '@shumai/core/src/asset/asset'
import { AssetInfo } from '@shumai/dtos'
import { SearchRequest } from '@shumai/dtos'
import type { AssetInfo, ImageSearchRequest, SearchRequest } from '@shumai/dtos'
import { PaginatedData, decodeCursor, encodeCursor, PageInfo } from '@shumai/core/src/pagination'
import { generateSearchNgrams } from '@shumai/core/src/utils/ngram'
import { HTTPException } from 'hono/http-exception'
import { getImageEmbeddingDimensions, imageEmbeddingService } from './image-embedding'
import { SqlQueryBuilder } from './sql-query-builder'
import { TextEmbeddingService, textEmbeddingService } from './text-embedding'
@@ -23,202 +23,37 @@ export class SearchService {
const targetTypes =
req.assetType === 'folder' ? [AssetType.folder] : [AssetType.file, AssetType.version_stack]
// ----------------------------------------------------------------------
// AI Semantic search
// ----------------------------------------------------------------------
if (req.query && req.isSemantic) {
// 1. Check if embedding agent exists and is enabled
const team = await this.prismaClient.asset.findUnique({
const folder = await this.prismaClient.asset.findUnique({
where: { id: folderId },
select: { project: { select: { teamId: true } } },
})
const teamId = team?.project?.teamId
const teamId = folder?.project?.teamId
if (!teamId) throw new Error('Team ID not found for folder')
await this.requireEmbeddingAgent(teamId)
if (process.env.ENABLE_EMBEDDING_AGENT === 'false') {
throw new HTTPException(422, {
message: 'Embedding agent not configured or disabled for this team.',
})
}
const embeddingAgent = await this.prismaClient.agent.findFirst({
where: { teamId, type: 'embedding', enabled: true },
})
if (!embeddingAgent) {
throw new HTTPException(422, {
message: 'Embedding agent not configured or disabled for this team.',
})
}
// 2. Generate query embedding directly using configured environment provider
let queryVector: number[]
let vector: number[]
try {
const result = await this.embeddingSvc.generateEmbedding(req.query, {
teamId,
})
queryVector = result.embedding
const result = await this.embeddingSvc.generateEmbedding(req.query, { teamId })
vector = result.embedding
} catch (err) {
const msg = err instanceof Error ? err.message : String(err)
throw new HTTPException(502, {
message: `Failed to generate query embedding: ${msg}`,
})
}
if (!queryVector || queryVector.length === 0) {
if (!vector || vector.length === 0) {
throw new HTTPException(502, {
message: 'Failed to generate query embedding: empty vector returned',
})
}
// 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", ${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})`)
}
if (req.showSymlink) {
builder.addWhere(Prisma.sql`
(a.type = ANY(${targetTypes}::"AssetType"[]) OR (a.type = 'symlink' AND a.target_id IN (SELECT id FROM assets WHERE type = ANY(${targetTypes}::"AssetType"[]))))
`)
} else {
builder.addWhere(Prisma.sql`a.type = ANY(${targetTypes}::"AssetType"[])`)
}
if (req.conditions && req.conditions.length > 0) {
builder.addSearchConditions(req.operator, req.conditions, { skipNameContains: true })
}
const nameCond = req.conditions?.find((c) => c.field === 'name' && c.operator === 'contains')
if (nameCond) {
const valStr = String(nameCond.value)
const ngrams = generateSearchNgrams(valStr)
if (ngrams.length > 0) {
builder.addWhere(Prisma.sql`a.name_ngram @> ${ngrams}::text[]`)
builder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
} else {
builder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
}
}
builder.orderBy(Prisma.sql`distance ASC`)
// 4. Paginate in SQL using limit/offset
let limit = req.first || 20
if (limit <= 0 || limit > 200) {
limit = 20
}
let offset = 0
if (req.after) {
offset = decodeCursor(req.after)
}
builder.limit(limit + 1).offset(offset)
// 5. Execute raw SQL query
const query = builder.build()
const semanticMatches = await this.prismaClient.$queryRaw<
{
assetId: string
startTime: number | null
endTime: number | null
distance: number
}[]
>(query)
const hasNextPage = semanticMatches.length > limit
const finalMatches = hasNextPage ? semanticMatches.slice(0, limit) : semanticMatches
// 6. Map back to full rich metadata and return time-based duplicate segments
const uniqueIds = Array.from(new Set(finalMatches.map((m) => m.assetId)))
const fetchedInfos = await this.assetSvc.listAssetsByIds(uniqueIds, req.previewFormat)
const assetInfosMap = new Map<string, AssetInfo>()
for (const info of fetchedInfos) {
assetInfosMap.set(info.id, info)
}
const data: AssetInfo[] = []
for (const match of finalMatches) {
const baseInfo = assetInfosMap.get(match.assetId)
if (baseInfo) {
data.push({
...baseInfo,
startTime: match.startTime,
endTime: match.endTime,
})
}
}
const pageInfo: PageInfo = {}
const countBuilder = new SqlQueryBuilder()
.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})`)
}
if (req.showSymlink) {
countBuilder.addWhere(Prisma.sql`
(a.type = ANY(${targetTypes}::"AssetType"[]) OR (a.type = 'symlink' AND a.target_id IN (SELECT id FROM assets WHERE type = ANY(${targetTypes}::"AssetType"[]))))
`)
} else {
countBuilder.addWhere(Prisma.sql`a.type = ANY(${targetTypes}::"AssetType"[])`)
}
if (req.conditions && req.conditions.length > 0) {
countBuilder.addSearchConditions(req.operator, req.conditions, { skipNameContains: true })
}
if (nameCond) {
const valStr = String(nameCond.value)
const ngrams = generateSearchNgrams(valStr)
if (ngrams.length > 0) {
countBuilder.addWhere(Prisma.sql`a.name_ngram @> ${ngrams}::text[]`)
countBuilder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
} else {
countBuilder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
}
}
const countRes = await this.prismaClient.$queryRaw<{ count: bigint }[]>(countBuilder.build())
const totalCount = Number(countRes[0]?.count || 0)
pageInfo.total = totalCount
if (totalCount < 2000) {
countBuilder.select(Prisma.sql`SUM(COALESCE(a.size_byte, 0))::bigint as sum`)
const sumRes = await this.prismaClient.$queryRaw<{ sum: bigint | null }[]>(
countBuilder.build(),
)
pageInfo.totalSize = Number(sumRes[0]?.sum || 0)
} else {
pageInfo.totalSize = -1
}
if (hasNextPage) {
pageInfo.cursor = encodeCursor(offset + limit)
}
return { data, pageInfo }
return this.searchByEmbedding(
targetFolderIds,
req,
JSON.stringify(vector),
vector.length === 768 ? 768 : 1536,
)
}
// ----------------------------------------------------------------------
@@ -447,6 +282,168 @@ export class SearchService {
return { data, pageInfo }
}
async searchByImage(
folderId: string,
req: ImageSearchRequest,
): Promise<PaginatedData<AssetInfo[]>> {
const folder = await this.prismaClient.asset.findFirst({
where: { id: folderId, type: { in: [AssetType.root, AssetType.folder] }, isDeleted: false },
select: { project: { select: { id: true, teamId: true, rootFolderId: true } } },
})
const project = folder?.project
if (!project) throw new HTTPException(404, { message: 'Project folder not found.' })
await this.requireEmbeddingAgent(project.teamId)
const dimensions = getImageEmbeddingDimensions()
let vector: string
if (req.sourceAssetId) {
if (folderId !== project.rootFolderId) {
throw new HTTPException(400, { message: 'Find similar requires the project root folder.' })
}
const column = dimensions === 768 ? Prisma.sql`embedding_768` : Prisma.sql`embedding`
const [source] = await this.prismaClient.$queryRaw<{ vector: string | null }[]>`
SELECT (
SELECT ${column}::text
FROM asset_embeddings
WHERE asset_id = a.id AND ${column} IS NOT NULL
ORDER BY id DESC
LIMIT 1
) AS vector
FROM assets a
WHERE a.id = ${req.sourceAssetId} AND a.project_id = ${project.id}
AND a.type = 'file' AND a.media_type LIKE 'image/%' AND a.is_deleted = false
`
if (!source) throw new HTTPException(404, { message: 'Source image not found.' })
if (!source.vector) {
throw new HTTPException(409, { message: 'The source image is waiting to be indexed.' })
}
vector = source.vector
} else if (req.image) {
vector = JSON.stringify(
await imageEmbeddingService.generateEmbedding(req.image, project.teamId),
)
} else {
throw new HTTPException(400, { message: 'Provide a search image or source asset.' })
}
const folders = await this.assetSvc.getDescendantFolderIds(folderId)
return this.searchByEmbedding(folders, req, vector, dimensions, {
projectId: project.id,
mediaType: req.mediaType,
sourceAssetId: req.sourceAssetId,
})
}
private async requireEmbeddingAgent(teamId: string): Promise<void> {
const agent =
process.env.ENABLE_EMBEDDING_AGENT === 'false'
? null
: await this.prismaClient.agent.findFirst({
where: { teamId, type: 'embedding', enabled: true },
select: { id: true },
})
if (!agent) {
throw new HTTPException(422, {
message: 'Embedding agent not configured or disabled for this team.',
})
}
}
private async searchByEmbedding(
folderIds: string[],
req: Pick<
SearchRequest,
'assetType' | 'showSymlink' | 'conditions' | 'operator' | 'first' | 'after' | 'previewFormat'
>,
vector: string,
dimensions: 768 | 1536,
visual?: {
projectId: string
mediaType?: ImageSearchRequest['mediaType']
sourceAssetId?: string
},
): Promise<PaginatedData<AssetInfo[]>> {
const column = dimensions === 768 ? Prisma.sql`ae.embedding_768` : Prisma.sql`ae.embedding`
const distance = Prisma.sql`(${column} <=> ${vector}::vector)`
const builder = new SqlQueryBuilder()
.from(Prisma.sql`assets a JOIN asset_embeddings ae ON a.id = ae.asset_id`)
.addWhere(Prisma.sql`a.is_deleted = false`)
.addWhere(Prisma.sql`${column} IS NOT NULL`)
if (folderIds.length > 0) {
builder.addWhere(Prisma.sql`a.parent_id = ANY(${folderIds})`)
}
if (visual) {
builder
.addWhere(Prisma.sql`a.project_id = ${visual.projectId} AND a.type = 'file'`)
.addWhere(
visual.mediaType
? Prisma.sql`a.media_type LIKE ${visual.mediaType + '/%'}`
: Prisma.sql`(a.media_type LIKE 'image/%' OR a.media_type LIKE 'video/%')`,
)
if (visual.sourceAssetId) {
builder.addWhere(Prisma.sql`a.id <> ${visual.sourceAssetId}`)
}
} else {
const targetTypes =
req.assetType === 'folder' ? [AssetType.folder] : [AssetType.file, AssetType.version_stack]
builder.addWhere(
req.showSymlink
? Prisma.sql`(a.type = ANY(${targetTypes}::"AssetType"[]) OR (a.type = 'symlink' AND a.target_id IN (SELECT id FROM assets WHERE type = ANY(${targetTypes}::"AssetType"[]))))`
: Prisma.sql`a.type = ANY(${targetTypes}::"AssetType"[])`,
)
}
builder.addSearchConditions(req.operator, req.conditions, { skipNameContains: true })
const nameCond = req.conditions?.find((c) => c.field === 'name' && c.operator === 'contains')
if (nameCond) {
const name = String(nameCond.value)
const ngrams = generateSearchNgrams(name)
if (ngrams.length > 0) builder.addWhere(Prisma.sql`a.name_ngram @> ${ngrams}::text[]`)
builder.addWhere(Prisma.sql`a.name ILIKE ${'%' + name + '%'}`)
}
const countQuery = builder.select(Prisma.sql`COUNT(*)`).build()
const sizeQuery = builder
.select(Prisma.sql`SUM(COALESCE(a.size_byte, 0))::bigint as sum`)
.build()
const requestedLimit = req.first || 20
const limit = requestedLimit <= 0 || requestedLimit > 200 ? 20 : requestedLimit
const offset = req.after ? decodeCursor(req.after) : 0
const resultQuery = builder
.select(
Prisma.sql`a.id as "assetId", ae.start_time as "startTime", ae.end_time as "endTime", ${distance} as "distance"`,
)
.orderBy(visual ? Prisma.sql`distance ASC, ae.id ASC` : Prisma.sql`distance ASC`)
.limit(limit + 1)
.offset(offset)
.build()
const matches =
await this.prismaClient.$queryRaw<
{ assetId: string; startTime: number | null; endTime: number | null }[]
>(resultQuery)
const page = matches.slice(0, limit)
const assetIds = [...new Set(page.map((match) => match.assetId))]
const infos = await this.assetSvc.listAssetsByIds(assetIds, req.previewFormat)
const byId = new Map(infos.map((item) => [item.id, item]))
const data = page.flatMap(({ assetId, startTime, endTime }) => {
const item = byId.get(assetId)
return item ? [{ ...item, startTime, endTime }] : []
})
const counts = await this.prismaClient.$queryRaw<{ count: bigint }[]>(countQuery)
const total = Number(counts[0]?.count ?? 0)
const sizes =
total < 2000 ? await this.prismaClient.$queryRaw<{ sum: bigint | null }[]>(sizeQuery) : []
const pageInfo: PageInfo = { total, totalSize: total < 2000 ? Number(sizes[0]?.sum ?? 0) : -1 }
if (matches.length > limit) pageInfo.cursor = encodeCursor(offset + limit)
return { data, pageInfo }
}
}
export const searchService = new SearchService()
+2 -9
View File
@@ -1,6 +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'
export interface TextEmbeddingUsage {
model: string
@@ -143,15 +144,7 @@ export class TextEmbeddingService {
model: string,
signal: AbortSignal,
): Promise<TextEmbeddingResult> {
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, {
const response = await fetch(getGemmaEmbeddingEndpoint(), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({