mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-26 19:04:23 +00:00
refactor(workflow): split database and agent activities for strict database isolation
This commit is contained in:
@@ -1,26 +1,48 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { aiChatActivity } from './agent'
|
||||
import { agentService } from '@/services/agent/agent'
|
||||
import { agentChatActivity, autofillAiActivity } from './agent'
|
||||
import * as piAgent from '@/agent'
|
||||
|
||||
vi.mock('@/services/agent/agent', () => ({
|
||||
agentService: {
|
||||
chatWithAgent: vi.fn(),
|
||||
},
|
||||
}))
|
||||
vi.mock('@/agent', async () => {
|
||||
const actual = await vi.importActual('@/agent')
|
||||
return {
|
||||
...actual,
|
||||
createAgentSession: vi.fn(),
|
||||
fieldsToTypeBoxSchema: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
describe('Agent Activities', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should call aiChatActivity and delegate to agentService', async () => {
|
||||
vi.mocked(agentService.chatWithAgent).mockResolvedValue({
|
||||
text: 'AI response',
|
||||
usage: { inputTokens: 1, outputTokens: 1, model: 'gpt-4' },
|
||||
sessionId: 'mock-session-id',
|
||||
it('should call agentChatActivity and prompt the harness', async () => {
|
||||
const mockHarness = {
|
||||
prompt: vi.fn().mockResolvedValue({
|
||||
content: [{ type: 'text', text: 'AI response' }],
|
||||
usage: { input: 10, output: 20 },
|
||||
}),
|
||||
}
|
||||
const mockSession = {
|
||||
getEntries: vi.fn().mockResolvedValue([]),
|
||||
getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }),
|
||||
}
|
||||
|
||||
vi.mocked(piAgent.createAgentSession).mockResolvedValue({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock session type is not fully compatible with pi-agent-core Session
|
||||
session: mockSession as any,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock harness type is not fully compatible with pi-agent-core Harness
|
||||
harness: mockHarness as any,
|
||||
})
|
||||
|
||||
await aiChatActivity({
|
||||
const context = {
|
||||
agent: { id: 'b1', provider: { name: 'google' }, modelRef: { modelId: 'gemini' } },
|
||||
dbProviders: [],
|
||||
teamSkills: [],
|
||||
allowedDomains: [],
|
||||
}
|
||||
|
||||
const res = await agentChatActivity({
|
||||
teamId: 't1',
|
||||
agentId: 'b1',
|
||||
message: 'Hi',
|
||||
@@ -28,16 +50,58 @@ describe('Agent Activities', () => {
|
||||
projectId: 'p1',
|
||||
folderId: 'f1',
|
||||
sessionId: 'mock-session-id',
|
||||
context,
|
||||
})
|
||||
|
||||
expect(agentService.chatWithAgent).toHaveBeenCalledWith(
|
||||
't1',
|
||||
'b1',
|
||||
'Hi',
|
||||
[],
|
||||
'',
|
||||
'mock-session-id',
|
||||
undefined,
|
||||
)
|
||||
expect(res.text).toBe('AI response')
|
||||
expect(res.usage.inputTokens).toBe(10)
|
||||
expect(res.usage.outputTokens).toBe(20)
|
||||
expect(piAgent.createAgentSession).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should call autofillAiActivity and run autofill tool', async () => {
|
||||
const mockHarness = {
|
||||
prompt: vi.fn().mockResolvedValue({
|
||||
content: [{ type: 'text', text: 'Captured' }],
|
||||
usage: { input: 5, output: 5 },
|
||||
}),
|
||||
}
|
||||
const mockSession = {
|
||||
getEntries: vi.fn().mockResolvedValue([]),
|
||||
getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }),
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- config object is passed dynamically by test runner
|
||||
vi.mocked(piAgent.createAgentSession).mockImplementation(async (config: any) => {
|
||||
// Simulate tool execution
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- customTools type is dynamic and nested
|
||||
const tool = config.customTools.find((t: any) => t.name === 'autofill_metadata')
|
||||
if (tool) {
|
||||
await tool.execute('1', { f1: 'val' })
|
||||
}
|
||||
return {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock session type is not fully compatible with pi-agent-core Session
|
||||
session: mockSession as any,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock harness type is not fully compatible with pi-agent-core Harness
|
||||
harness: mockHarness as any,
|
||||
}
|
||||
})
|
||||
|
||||
const context = {
|
||||
agent: { id: 'b1', provider: { name: 'google' }, modelRef: { modelId: 'gemini' } },
|
||||
dbProviders: [],
|
||||
teamSkills: [],
|
||||
allowedDomains: [],
|
||||
}
|
||||
|
||||
const res = await autofillAiActivity({
|
||||
teamId: 't1',
|
||||
images: [],
|
||||
fields: [{ id: 'f1', config: { name: 'F1', type: 'text' } }],
|
||||
context,
|
||||
})
|
||||
|
||||
expect(res.text).toBe('{"f1":"val"}')
|
||||
expect(res.usage.inputTokens).toBe(5)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,18 +1,131 @@
|
||||
import { agentService } from '@/services/agent/agent'
|
||||
import type { AutofillField } from '@/agent'
|
||||
import { createAgentSession, fieldsToTypeBoxSchema, type AutofillField } from '@/agent'
|
||||
import { logger } from '@/logger'
|
||||
import { s3Service } from '@/services/s3/s3'
|
||||
import { type AgentTool } from '@earendil-works/pi-agent-core'
|
||||
import { type ImageContent } from '@earendil-works/pi-ai'
|
||||
import { type Usage } from '@/services/ai/provider/provider'
|
||||
|
||||
export interface AutofillAiParams {
|
||||
interface AgentExecutionContext {
|
||||
agent: unknown
|
||||
dbProviders: unknown[]
|
||||
teamSkills: unknown[]
|
||||
allowedDomains: string[]
|
||||
}
|
||||
|
||||
async function executeAgentPrompt(params: {
|
||||
teamId: string
|
||||
agentId: string
|
||||
prompt: string
|
||||
images: string[]
|
||||
fields: AutofillField[]
|
||||
agentsInstruction: string
|
||||
sessionId?: string
|
||||
userId?: string
|
||||
tools?: AgentTool[]
|
||||
context: AgentExecutionContext
|
||||
}): Promise<{ text: string; usage: Usage; sessionId: string }> {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- context is a serialized JSON object from db activity
|
||||
const context = params.context as any
|
||||
const agent = context.agent
|
||||
const dbProviders = context.dbProviders
|
||||
const teamSkills = context.teamSkills
|
||||
const allowedDomains = context.allowedDomains
|
||||
|
||||
if (!agent.provider) throw new Error('agent has no provider configured')
|
||||
if (!agent.modelRef) throw new Error('agent has no model configured')
|
||||
|
||||
const providerName = agent.provider.name
|
||||
const modelId = agent.modelRef.modelId
|
||||
|
||||
let systemPrompt = '你是shumai小助手。'
|
||||
if (params.agentsInstruction) {
|
||||
systemPrompt = `${systemPrompt}\n\nContext and Instructions:\n${params.agentsInstruction}`
|
||||
}
|
||||
|
||||
const modelConfig = agent.modelRef?.config as unknown as PrismaJson.ModelConfig
|
||||
if (modelConfig?.input) {
|
||||
systemPrompt += `\n\nYour current model supports the following input types: ${modelConfig.input.join(', ')}.`
|
||||
}
|
||||
|
||||
const { session, harness } = await createAgentSession({
|
||||
agentId: params.agentId,
|
||||
providerName,
|
||||
modelId,
|
||||
systemPrompt,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- s is typed as any because teamSkills is dynamically deserialized JSON
|
||||
teamSkills: teamSkills.map((s: any) => ({
|
||||
id: s.id,
|
||||
name: s.name,
|
||||
description: s.description,
|
||||
})),
|
||||
allowedDomains,
|
||||
sessionId: params.sessionId,
|
||||
userId: params.userId,
|
||||
customTools: params.tools || [],
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- p is typed as any because dbProviders is dynamically deserialized JSON
|
||||
providers: dbProviders.map((p: any) => ({
|
||||
name: p.name,
|
||||
config: p.config,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- m is typed as any because p.models is a generic dynamic JSON array from the DB context
|
||||
models: p.models.map((m: any) => ({
|
||||
modelId: m.modelId,
|
||||
name: m.name,
|
||||
config: m.config,
|
||||
})),
|
||||
})),
|
||||
})
|
||||
|
||||
const imagesToPass: ImageContent[] = []
|
||||
|
||||
if (params.images && params.images.length > 0) {
|
||||
for (const key of params.images) {
|
||||
const { buffer, contentType } = await s3Service.getObject(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
key,
|
||||
)
|
||||
imagesToPass.push({
|
||||
type: 'image',
|
||||
data: buffer.toString('base64'),
|
||||
mimeType: contentType,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const assistantMessage = await harness.prompt(params.prompt, { images: imagesToPass })
|
||||
|
||||
const sessionEntries = await session.getEntries()
|
||||
sessionEntries.forEach((entry) => {
|
||||
if (entry.type === 'message') {
|
||||
const msg = entry.message
|
||||
if (msg.role === 'toolResult') {
|
||||
const logMsg = { ...msg, content: undefined }
|
||||
logger.debug(logMsg, 'agent message')
|
||||
} else {
|
||||
logger.debug(msg, 'agent message')
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
const text = assistantMessage.content
|
||||
.filter((c) => c.type === 'text')
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- text property exists on text content items
|
||||
.map((c) => (c as any).text)
|
||||
.join('\n')
|
||||
|
||||
const usage: Usage = {
|
||||
model: modelId,
|
||||
inputTokens: assistantMessage.usage?.input || 0,
|
||||
outputTokens: assistantMessage.usage?.output || 0,
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- sessionId property added to DatabaseSessionStorage
|
||||
return { text, usage, sessionId: (session.getStorage() as any).sessionId }
|
||||
} finally {
|
||||
// Cleanup handled by agent session if needed
|
||||
}
|
||||
}
|
||||
|
||||
export async function autofillAiActivity(params: AutofillAiParams) {
|
||||
const prompt = 'Analyze the provided images and extract metadata.'
|
||||
return agentService.autofill(params.teamId, prompt, params.images, params.fields)
|
||||
}
|
||||
|
||||
export interface AiChatParams {
|
||||
export interface AgentChatParams {
|
||||
teamId: string
|
||||
agentId: string
|
||||
message: string
|
||||
@@ -23,19 +136,73 @@ export interface AiChatParams {
|
||||
sessionId: string
|
||||
userId?: string
|
||||
explicitMention?: boolean
|
||||
context: AgentExecutionContext
|
||||
}
|
||||
|
||||
export async function aiChatActivity(params: AiChatParams) {
|
||||
export async function agentChatActivity(params: AgentChatParams) {
|
||||
const cleanMessage = params.message.replace(/<@[A-Z0-9]+>/g, '').trim()
|
||||
const sessionId = params.sessionId
|
||||
|
||||
return agentService.chatWithAgent(
|
||||
params.teamId,
|
||||
params.agentId,
|
||||
cleanMessage,
|
||||
params.imageUrls,
|
||||
params.agentsInstruction || '',
|
||||
return executeAgentPrompt({
|
||||
teamId: params.teamId,
|
||||
agentId: params.agentId,
|
||||
prompt: cleanMessage,
|
||||
images: params.imageUrls,
|
||||
agentsInstruction: params.agentsInstruction || '',
|
||||
sessionId,
|
||||
params.userId,
|
||||
)
|
||||
userId: params.userId,
|
||||
context: params.context,
|
||||
})
|
||||
}
|
||||
|
||||
export interface AutofillAiParams {
|
||||
teamId: string
|
||||
images: string[]
|
||||
fields: AutofillField[]
|
||||
context: AgentExecutionContext
|
||||
}
|
||||
|
||||
export async function autofillAiActivity(params: AutofillAiParams) {
|
||||
const prompt = 'Analyze the provided images and extract metadata.'
|
||||
const toolSchema = fieldsToTypeBoxSchema(params.fields)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let capturedData: any = null
|
||||
|
||||
const autofillTool: AgentTool = {
|
||||
name: 'autofill_metadata',
|
||||
label: 'Autofill Metadata',
|
||||
description: 'Extract metadata from the images.',
|
||||
parameters: toolSchema,
|
||||
execute: async (_toolCallId, toolParams) => {
|
||||
capturedData = toolParams
|
||||
return {
|
||||
content: [{ type: 'text', text: 'Metadata captured successfully.' }],
|
||||
details: {},
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
const fullPrompt = `${prompt}\n\nPlease use the "autofill_metadata" tool to provide the extracted metadata.`
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- context is a serialized JSON object from db activity
|
||||
const context = params.context as any
|
||||
const agent = context.agent
|
||||
|
||||
const { usage, sessionId } = await executeAgentPrompt({
|
||||
teamId: params.teamId,
|
||||
agentId: agent.id,
|
||||
prompt: fullPrompt,
|
||||
images: params.images,
|
||||
agentsInstruction: '',
|
||||
sessionId: undefined,
|
||||
userId: undefined,
|
||||
tools: [autofillTool],
|
||||
context: params.context,
|
||||
})
|
||||
|
||||
return {
|
||||
text: capturedData ? JSON.stringify(capturedData) : '{}',
|
||||
usage,
|
||||
sessionId,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,74 +1,50 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { prisma } from '@/db'
|
||||
import { setupTestDbHooks } from '@/db-test-hooks'
|
||||
import { getAssetActivity, generateEmbeddingActivity, getCommentActivity } from './ai'
|
||||
import { aiService } from '@/services/ai/ai'
|
||||
import { generateEmbeddingActivity } from './ai'
|
||||
import { s3Service } from '@/services/s3/s3'
|
||||
|
||||
vi.mock('@/services/ai/ai', () => ({
|
||||
aiService: {
|
||||
generateAssetEmbeddings: vi.fn(),
|
||||
vi.mock('@/services/s3/s3', () => ({
|
||||
s3Service: {
|
||||
getObject: vi.fn(),
|
||||
putObject: vi.fn(),
|
||||
headObject: vi.fn(),
|
||||
listObjects: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('AI Activities', () => {
|
||||
setupTestDbHooks()
|
||||
vi.mock('@/services/ai/provider/gemini', () => {
|
||||
return {
|
||||
GeminiProvider: class {
|
||||
generateImageEmbedding = vi.fn().mockResolvedValue([0.1, 0.2, 0.3])
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
describe('AI Activities', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should get asset with project and team', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Team A' } })
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Proj A', teamId: team.id },
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'test.png',
|
||||
storageKey: { create: { key: 'test.png' } },
|
||||
status: 'uploaded',
|
||||
type: 'file',
|
||||
project: { connect: { id: project.id } },
|
||||
},
|
||||
it('should generate image embedding', async () => {
|
||||
vi.mocked(s3Service.getObject).mockResolvedValue({
|
||||
buffer: Buffer.from('test-image'),
|
||||
contentType: 'image/png',
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock getObject return value needs broad any casting
|
||||
} as any)
|
||||
|
||||
const context = {
|
||||
agent: { config: { provider: 'google', model: 'gemini' } },
|
||||
asset: { id: 'a1', mediaType: 'image/png', storageKey: { key: 'test.png' } },
|
||||
dbProvider: { config: { apiKey: 'key' } },
|
||||
}
|
||||
|
||||
const res = await generateEmbeddingActivity({
|
||||
teamId: 't1',
|
||||
assetId: 'a1',
|
||||
context,
|
||||
})
|
||||
|
||||
const result = await getAssetActivity(asset.id)
|
||||
expect(result?.project?.team?.id).toBe(team.id)
|
||||
})
|
||||
|
||||
it('should call generateAssetEmbeddings', async () => {
|
||||
vi.mocked(aiService.generateAssetEmbeddings).mockResolvedValue({
|
||||
inputTokens: 1,
|
||||
outputTokens: 1,
|
||||
model: 'clip',
|
||||
})
|
||||
|
||||
await generateEmbeddingActivity({ teamId: 't1', assetId: 'a1' })
|
||||
expect(aiService.generateAssetEmbeddings).toHaveBeenCalledWith('t1', 'a1')
|
||||
})
|
||||
|
||||
it('should get and update comments', async () => {
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'Test User', email: 'test-ai@example.com', password: 'pw' },
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'test.png',
|
||||
storageKey: { create: { key: 'test.png' } },
|
||||
status: 'uploaded',
|
||||
type: 'file',
|
||||
},
|
||||
})
|
||||
|
||||
const comment = await prisma.assetComment.create({
|
||||
data: {
|
||||
assetId: asset.id,
|
||||
creatorId: user.id,
|
||||
message: 'Original',
|
||||
},
|
||||
})
|
||||
|
||||
const fetched = await getCommentActivity(comment.id)
|
||||
expect(fetched?.message).toBe('Original')
|
||||
expect(res.embeddings.length).toBe(1)
|
||||
expect(res.embeddings[0].embedding).toEqual([0.1, 0.2, 0.3])
|
||||
expect(s3Service.getObject).toHaveBeenCalledWith('shumai', 'test.png')
|
||||
})
|
||||
})
|
||||
|
||||
+130
-36
@@ -1,54 +1,148 @@
|
||||
import { prisma } from '@/db'
|
||||
import { aiService } from '@/services/ai/ai'
|
||||
import { metadataService } from '@/services/metadata/metadata'
|
||||
import { UpdateAssetMetadataRequest } from '@/dtos/metadata'
|
||||
import { ElevenLabsProvider } from '@/services/ai/provider/elevenlabs'
|
||||
import { GeminiProvider } from '@/services/ai/provider/gemini'
|
||||
import { OpenAiProvider } from '@/services/ai/provider/openai'
|
||||
import { Provider, Usage } from '@/services/ai/provider/provider'
|
||||
import { AiProvider } from '@/dtos/ai'
|
||||
import { s3Service } from '@/services/s3/s3'
|
||||
import { transcodeService } from '@/transcode/transcode'
|
||||
import * as path from 'path'
|
||||
import { exec } from 'child_process'
|
||||
import * as fs from 'fs'
|
||||
import * as os from 'os'
|
||||
import * as path from 'path'
|
||||
import { promisify } from 'util'
|
||||
|
||||
export async function getAssetActivity(assetId: string) {
|
||||
return prisma.asset.findUnique({
|
||||
where: { id: assetId },
|
||||
include: {
|
||||
storageKey: true,
|
||||
project: {
|
||||
include: {
|
||||
team: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
const execAsync = promisify(exec)
|
||||
|
||||
function providerFactory(providerName: string, config: PrismaJson.AiProviderSettings): Provider {
|
||||
let pKey: AiProvider
|
||||
switch (providerName) {
|
||||
case AiProvider.Google:
|
||||
pKey = AiProvider.Google
|
||||
break
|
||||
case AiProvider.OpenAi:
|
||||
pKey = AiProvider.OpenAi
|
||||
break
|
||||
case AiProvider.ElevenLabs:
|
||||
pKey = AiProvider.ElevenLabs
|
||||
break
|
||||
default:
|
||||
throw new Error(`Unsupported provider: ${providerName}`)
|
||||
}
|
||||
|
||||
switch (pKey) {
|
||||
case AiProvider.Google:
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- provider config requires a broad casting since it is a JSON property of the provider model
|
||||
return new GeminiProvider(config as any)
|
||||
case AiProvider.OpenAi:
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- provider config requires a broad casting since it is a JSON property of the provider model
|
||||
return new OpenAiProvider(config as any)
|
||||
case AiProvider.ElevenLabs:
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- provider config requires a broad casting since it is a JSON property of the provider model
|
||||
return new ElevenLabsProvider(config as any)
|
||||
default:
|
||||
throw new Error(`Provider implementation for ${providerName} not found`)
|
||||
}
|
||||
}
|
||||
|
||||
export interface GeneratedEmbedding {
|
||||
embedding: number[]
|
||||
startTime?: number
|
||||
endTime?: number
|
||||
}
|
||||
|
||||
export interface GenerateEmbeddingParams {
|
||||
teamId: string
|
||||
assetId: string
|
||||
context: {
|
||||
agent: unknown
|
||||
asset: unknown
|
||||
dbProvider: unknown
|
||||
}
|
||||
}
|
||||
|
||||
export async function generateEmbeddingActivity(params: GenerateEmbeddingParams) {
|
||||
return aiService.generateAssetEmbeddings(params.teamId, params.assetId)
|
||||
}
|
||||
export async function generateEmbeddingActivity(params: GenerateEmbeddingParams): Promise<{
|
||||
embeddings: GeneratedEmbedding[]
|
||||
usage: Usage
|
||||
}> {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- context properties are fetched as JSON from the DB activity
|
||||
const { agent, asset, dbProvider } = params.context as any
|
||||
|
||||
export async function getProjectAutofillFieldsActivity(projectId: string) {
|
||||
const fields = await metadataService.listProjectFields('', projectId)
|
||||
return fields.filter((f) => f.field.aiAutofill).map((f) => f.field)
|
||||
}
|
||||
const config = agent.config as unknown as PrismaJson.AgentConfig
|
||||
if (!config.provider) throw new Error('embedding provider not configured')
|
||||
if (!config.model) throw new Error('embedding model not configured')
|
||||
|
||||
export interface UpdateAssetMetadataParams {
|
||||
assetId: string
|
||||
metadata: UpdateAssetMetadataRequest[]
|
||||
}
|
||||
if (!asset.mediaType) throw new Error('asset has no media type')
|
||||
|
||||
export async function updateAssetMetadataActivity(params: UpdateAssetMetadataParams) {
|
||||
return metadataService.updateAssetMetadata(params.assetId, params.metadata)
|
||||
}
|
||||
const p = providerFactory(config.provider, dbProvider.config as PrismaJson.AiProviderSettings)
|
||||
|
||||
export async function getCommentActivity(commentId: string) {
|
||||
return prisma.assetComment.findUnique({
|
||||
where: { id: commentId },
|
||||
include: { attachments: { include: { asset: { include: { storageKey: true } } } } },
|
||||
})
|
||||
const usage: Usage = {
|
||||
model: config.model,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
const isImage = asset.mediaType.startsWith('image/')
|
||||
const isVideo = asset.mediaType.startsWith('video/')
|
||||
|
||||
if (!isImage && !isVideo) {
|
||||
throw new Error(`unsupported media type for embeddings: ${asset.mediaType}`)
|
||||
}
|
||||
|
||||
const key = asset.storageKey?.key
|
||||
if (!key) {
|
||||
throw new Error(`asset has no key`)
|
||||
}
|
||||
|
||||
const { buffer: data } = await s3Service.getObject(process.env.S3_BUCKET || 'shumai', key)
|
||||
|
||||
const results: GeneratedEmbedding[] = []
|
||||
|
||||
if (isImage) {
|
||||
const embVec = await p.generateImageEmbedding(config.model, data)
|
||||
results.push({ embedding: embVec })
|
||||
} else if (isVideo) {
|
||||
const tmpFile = path.join(os.tmpdir(), `video-${Date.now()}.mp4`)
|
||||
fs.writeFileSync(tmpFile, data)
|
||||
|
||||
try {
|
||||
const { stdout } = await execAsync(
|
||||
`ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "${tmpFile}"`,
|
||||
)
|
||||
const duration = parseFloat(stdout.trim())
|
||||
if (isNaN(duration)) throw new Error('failed to parse video duration')
|
||||
|
||||
const chunkSize = 60.0
|
||||
for (let start = 0.0; start < duration; start += chunkSize) {
|
||||
let end = start + chunkSize
|
||||
if (end > duration) end = duration
|
||||
|
||||
const chunkTmp = path.join(os.tmpdir(), `video-chunk-${Date.now()}.mp4`)
|
||||
await execAsync(
|
||||
`ffmpeg -y -i "${tmpFile}" -ss ${start} -t ${end - start} -c copy "${chunkTmp}"`,
|
||||
)
|
||||
|
||||
const chunkData = fs.readFileSync(chunkTmp)
|
||||
fs.unlinkSync(chunkTmp)
|
||||
|
||||
try {
|
||||
const embVec = await p.generateVideoEmbedding(config.model, chunkData)
|
||||
results.push({ embedding: embVec, startTime: start, endTime: end })
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} catch (e: any) {
|
||||
console.error(
|
||||
`failed to generate video embedding for chunk ${start}-${end}: ${e.message}`,
|
||||
)
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
fs.unlinkSync(tmpFile)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
embeddings: results,
|
||||
usage,
|
||||
}
|
||||
}
|
||||
|
||||
export interface ExtractAiMetadataParams {
|
||||
|
||||
@@ -6,6 +6,10 @@ import {
|
||||
updateCommentActivity,
|
||||
deleteCommentActivity,
|
||||
initializeAgentSessionActivity,
|
||||
getAgentChatContextActivity,
|
||||
getAgentAutofillContextActivity,
|
||||
getEmbeddingContextActivity,
|
||||
saveAssetEmbeddingsActivity,
|
||||
} from './db'
|
||||
import type { SessionTreeEntry } from '@earendil-works/pi-agent-core'
|
||||
|
||||
@@ -186,4 +190,129 @@ describe('Database Activities', () => {
|
||||
throw new Error('Expected entry to be a message')
|
||||
}
|
||||
})
|
||||
|
||||
it('should support context-fetching and embedding database activities', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 't_ctx' } })
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'p_ctx', teamId: team.id },
|
||||
})
|
||||
const sk = await prisma.storageKey.create({ data: { key: 'asset-key' } })
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'test-asset',
|
||||
type: 'file',
|
||||
projectId: project.id,
|
||||
status: 'uploaded',
|
||||
mediaType: 'image/png',
|
||||
storageKeyId: sk.id,
|
||||
},
|
||||
})
|
||||
|
||||
const provider = await prisma.provider.create({
|
||||
data: {
|
||||
name: 'google',
|
||||
teamId: team.id,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- provider config requires broad any casting since it is defined as generic Json in Prisma schema
|
||||
config: { api: 'google', apiKey: 'key' } as any,
|
||||
},
|
||||
})
|
||||
|
||||
const model = await prisma.model.create({
|
||||
data: {
|
||||
modelId: 'gemini',
|
||||
name: 'Gemini',
|
||||
providerId: provider.id,
|
||||
config: {
|
||||
reasoning: false,
|
||||
input: ['text'],
|
||||
contextWindow: 1000,
|
||||
maxTokens: 1000,
|
||||
cost: {
|
||||
input: 0,
|
||||
output: 0,
|
||||
cacheRead: 0,
|
||||
cacheWrite: 0,
|
||||
},
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- model config requires broad any casting since it is defined as generic Json in Prisma schema
|
||||
} as any,
|
||||
},
|
||||
})
|
||||
|
||||
const botUser = await prisma.user.create({
|
||||
data: { name: 'Pirate Bot', email: 'bot@example.com', type: 'agent' },
|
||||
})
|
||||
|
||||
const agent = await prisma.agent.create({
|
||||
data: {
|
||||
id: botUser.id,
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
config: { provider: 'google', model: 'gemini' },
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: botUser.id, role: 'reviewer' },
|
||||
})
|
||||
|
||||
// Test getAgentChatContextActivity
|
||||
const chatCtx = await getAgentChatContextActivity({ teamId: team.id, agentId: agent.id })
|
||||
expect(chatCtx.agent.id).toBe(agent.id)
|
||||
expect(chatCtx.dbProviders.length).toBe(1)
|
||||
expect(chatCtx.allowedDomains).toEqual([])
|
||||
|
||||
// Test getAgentAutofillContextActivity (needs an autofill agent)
|
||||
const autofillBot = await prisma.user.create({
|
||||
data: { name: 'Autofill Bot', email: 'autobot@example.com', type: 'agent' },
|
||||
})
|
||||
const autofillAgent = await prisma.agent.create({
|
||||
data: {
|
||||
id: autofillBot.id,
|
||||
teamId: team.id,
|
||||
type: 'autofill',
|
||||
enabled: true,
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
config: { provider: 'google', model: 'gemini' },
|
||||
},
|
||||
})
|
||||
const autofillCtx = await getAgentAutofillContextActivity({ teamId: team.id })
|
||||
expect(autofillCtx.agent.id).toBe(autofillAgent.id)
|
||||
|
||||
// Test getEmbeddingContextActivity (needs an embedding agent)
|
||||
const embeddingBot = await prisma.user.create({
|
||||
data: { name: 'Embedding Bot', email: 'emb@example.com', type: 'agent' },
|
||||
})
|
||||
const embeddingAgent = await prisma.agent.create({
|
||||
data: {
|
||||
id: embeddingBot.id,
|
||||
teamId: team.id,
|
||||
type: 'embedding',
|
||||
enabled: true,
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
config: { provider: 'google', model: 'gemini' },
|
||||
},
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: embeddingBot.id, role: 'reviewer' },
|
||||
})
|
||||
const embCtx = await getEmbeddingContextActivity({ teamId: team.id, assetId: asset.id })
|
||||
expect(embCtx.agent.id).toBe(embeddingAgent.id)
|
||||
expect(embCtx.asset.id).toBe(asset.id)
|
||||
|
||||
// Test saveAssetEmbeddingsActivity
|
||||
const mockEmbedding = Array(1536).fill(0.1)
|
||||
await saveAssetEmbeddingsActivity({
|
||||
assetId: asset.id,
|
||||
embeddings: [{ embedding: mockEmbedding }],
|
||||
})
|
||||
const dbEmbeddings = await prisma.assetEmbedding.findMany({
|
||||
where: { assetId: asset.id },
|
||||
})
|
||||
expect(dbEmbeddings.length).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { prisma } from '@/db'
|
||||
import type { AgentMessage, SessionTreeEntry } from '@earendil-works/pi-agent-core'
|
||||
import { ulid } from 'ulid'
|
||||
import { metadataService } from '@/services/metadata/metadata'
|
||||
import { UpdateAssetMetadataRequest } from '@/dtos/metadata'
|
||||
import { WorkflowTaskStatus, AssetStatus } from '@/generated/prisma/client'
|
||||
|
||||
export interface InitializeAgentSessionParams {
|
||||
teamId: string
|
||||
@@ -278,3 +281,273 @@ export async function updateCommentActivity(params: UpdateCommentParams) {
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// New Context-Fetching and Embedding DB Activities
|
||||
// ==========================================
|
||||
|
||||
export interface GetAgentChatContextParams {
|
||||
teamId: string
|
||||
agentId: string
|
||||
}
|
||||
|
||||
export async function getAgentChatContextActivity(params: GetAgentChatContextParams) {
|
||||
const team = await prisma.team.findUnique({
|
||||
where: { id: params.teamId },
|
||||
})
|
||||
if (!team) throw new Error('failed to get team')
|
||||
|
||||
const agent = await prisma.agent.findUnique({
|
||||
where: { id: params.agentId },
|
||||
include: {
|
||||
provider: true,
|
||||
modelRef: true,
|
||||
},
|
||||
})
|
||||
if (!agent) {
|
||||
throw new Error(`agent ${params.agentId} not found`)
|
||||
}
|
||||
|
||||
if (!agent.provider) throw new Error('agent has no provider configured')
|
||||
if (!agent.modelRef) throw new Error('agent has no model configured')
|
||||
|
||||
const providerName = agent.provider.name
|
||||
|
||||
// Fetch the required provider configuration from database
|
||||
const dbProviders = await prisma.provider.findMany({
|
||||
where: { teamId: params.teamId, name: providerName },
|
||||
include: { models: true },
|
||||
})
|
||||
|
||||
// Fetch team skills
|
||||
const teamSkills = await prisma.skill.findMany({
|
||||
where: { teamId: params.teamId },
|
||||
})
|
||||
|
||||
const sandbox = await prisma.sandbox.findUnique({
|
||||
where: { teamId: params.teamId },
|
||||
})
|
||||
const allowedDomains = sandbox?.allowedDomains || []
|
||||
|
||||
return {
|
||||
agent,
|
||||
dbProviders,
|
||||
teamSkills,
|
||||
allowedDomains,
|
||||
}
|
||||
}
|
||||
|
||||
export interface GetAgentAutofillContextParams {
|
||||
teamId: string
|
||||
}
|
||||
|
||||
export async function getAgentAutofillContextActivity(params: GetAgentAutofillContextParams) {
|
||||
const agent = await prisma.agent.findFirst({
|
||||
where: {
|
||||
type: 'autofill',
|
||||
enabled: true,
|
||||
teamId: params.teamId,
|
||||
},
|
||||
})
|
||||
if (!agent) {
|
||||
throw new Error('no autofill agent found for team')
|
||||
}
|
||||
|
||||
const team = await prisma.team.findUnique({
|
||||
where: { id: params.teamId },
|
||||
})
|
||||
if (!team) throw new Error('failed to get team')
|
||||
|
||||
// Find provider/model configuration
|
||||
const agentWithDetails = await prisma.agent.findUnique({
|
||||
where: { id: agent.id },
|
||||
include: {
|
||||
provider: true,
|
||||
modelRef: true,
|
||||
},
|
||||
})
|
||||
if (!agentWithDetails) throw new Error(`agent ${agent.id} not found`)
|
||||
if (!agentWithDetails.provider) throw new Error('agent has no provider configured')
|
||||
if (!agentWithDetails.modelRef) throw new Error('agent has no model configured')
|
||||
|
||||
const providerName = agentWithDetails.provider.name
|
||||
|
||||
// Fetch the required provider configuration from database
|
||||
const dbProviders = await prisma.provider.findMany({
|
||||
where: { teamId: params.teamId, name: providerName },
|
||||
include: { models: true },
|
||||
})
|
||||
|
||||
// Fetch team skills
|
||||
const teamSkills = await prisma.skill.findMany({
|
||||
where: { teamId: params.teamId },
|
||||
})
|
||||
|
||||
const sandbox = await prisma.sandbox.findUnique({
|
||||
where: { teamId: params.teamId },
|
||||
})
|
||||
const allowedDomains = sandbox?.allowedDomains || []
|
||||
|
||||
return {
|
||||
agent: agentWithDetails,
|
||||
dbProviders,
|
||||
teamSkills,
|
||||
allowedDomains,
|
||||
}
|
||||
}
|
||||
|
||||
export interface GetEmbeddingContextParams {
|
||||
teamId: string
|
||||
assetId: string
|
||||
}
|
||||
|
||||
export async function getEmbeddingContextActivity(params: GetEmbeddingContextParams) {
|
||||
const team = await prisma.team.findUnique({
|
||||
where: { id: params.teamId },
|
||||
})
|
||||
if (!team) throw new Error('failed to get team')
|
||||
|
||||
const agent = await prisma.agent.findFirst({
|
||||
where: {
|
||||
type: 'embedding',
|
||||
enabled: true,
|
||||
user: { teamMembers: { some: { teamId: params.teamId } } },
|
||||
},
|
||||
})
|
||||
if (!agent) {
|
||||
throw new Error('embedding feature is disabled or agent not found')
|
||||
}
|
||||
|
||||
const config = agent.config as unknown as PrismaJson.AgentConfig
|
||||
if (!config.provider) throw new Error('embedding provider not configured')
|
||||
if (!config.model) throw new Error('embedding model not configured')
|
||||
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: params.assetId },
|
||||
include: { storageKey: true },
|
||||
})
|
||||
if (!asset) throw new Error('failed to get asset')
|
||||
if (!asset.mediaType) throw new Error('asset has no media type')
|
||||
|
||||
const dbProvider = await prisma.provider.findFirst({
|
||||
where: { teamId: params.teamId, name: config.provider },
|
||||
})
|
||||
if (!dbProvider) throw new Error(`Provider ${config.provider} not found in database`)
|
||||
|
||||
return {
|
||||
agent,
|
||||
asset,
|
||||
dbProvider,
|
||||
}
|
||||
}
|
||||
|
||||
export interface SaveAssetEmbeddingsParams {
|
||||
assetId: string
|
||||
embeddings: Array<{
|
||||
embedding: number[]
|
||||
startTime?: number
|
||||
endTime?: number
|
||||
}>
|
||||
}
|
||||
|
||||
export async function saveAssetEmbeddingsActivity(params: SaveAssetEmbeddingsParams) {
|
||||
for (const item of params.embeddings) {
|
||||
const embVec = JSON.stringify(item.embedding)
|
||||
if (item.startTime !== undefined && item.endTime !== undefined) {
|
||||
await prisma.$executeRaw`
|
||||
INSERT INTO asset_embeddings (id, asset_id, embedding, start_time, end_time, updated_at)
|
||||
VALUES (gen_random_uuid()::text, ${params.assetId}, ${embVec}::vector, ${item.startTime}, ${item.endTime}, NOW())
|
||||
`
|
||||
} else {
|
||||
await prisma.$executeRaw`
|
||||
INSERT INTO asset_embeddings (id, asset_id, embedding, updated_at)
|
||||
VALUES (gen_random_uuid()::text, ${params.assetId}, ${embVec}::vector, NOW())
|
||||
`
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// Moved Database Activities
|
||||
// ==========================================
|
||||
|
||||
export async function getAssetActivity(assetId: string) {
|
||||
return prisma.asset.findUnique({
|
||||
where: { id: assetId },
|
||||
include: {
|
||||
storageKey: true,
|
||||
project: {
|
||||
include: {
|
||||
team: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export async function getCommentActivity(commentId: string) {
|
||||
return prisma.assetComment.findUnique({
|
||||
where: { id: commentId },
|
||||
include: { attachments: { include: { asset: { include: { storageKey: true } } } } },
|
||||
})
|
||||
}
|
||||
|
||||
export async function getProjectAutofillFieldsActivity(projectId: string) {
|
||||
const fields = await metadataService.listProjectFields('', projectId)
|
||||
return fields.filter((f) => f.field.aiAutofill).map((f) => f.field)
|
||||
}
|
||||
|
||||
export interface UpdateAssetMetadataParams {
|
||||
assetId: string
|
||||
metadata: UpdateAssetMetadataRequest[]
|
||||
}
|
||||
|
||||
export async function updateAssetMetadataActivity(params: UpdateAssetMetadataParams) {
|
||||
return metadataService.updateAssetMetadata(params.assetId, params.metadata)
|
||||
}
|
||||
|
||||
export interface UpdateTaskStatusParams {
|
||||
taskId: string
|
||||
status: WorkflowTaskStatus
|
||||
output?: unknown
|
||||
}
|
||||
|
||||
export async function updateTaskStatusActivity(params: UpdateTaskStatusParams): Promise<void> {
|
||||
await prisma.workflowTask.update({
|
||||
where: { id: params.taskId },
|
||||
data: {
|
||||
status: params.status,
|
||||
output: params.output,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export interface UpdateAssetStatusParams {
|
||||
assetId: string
|
||||
status: AssetStatus
|
||||
}
|
||||
|
||||
export async function updateAssetStatusActivity(params: UpdateAssetStatusParams): Promise<void> {
|
||||
await prisma.asset.update({
|
||||
where: { id: params.assetId },
|
||||
data: { status: params.status },
|
||||
})
|
||||
}
|
||||
|
||||
export interface UpdateTaskUsageParams {
|
||||
taskId: string
|
||||
inputTokens: number
|
||||
outputTokens: number
|
||||
model: string
|
||||
}
|
||||
|
||||
export async function updateTaskUsageActivity(params: UpdateTaskUsageParams): Promise<void> {
|
||||
await prisma.workflowTask.update({
|
||||
where: { id: params.taskId },
|
||||
data: {
|
||||
inputTokens: params.inputTokens,
|
||||
outputTokens: params.outputTokens,
|
||||
model: params.model,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { prisma } from '@/db'
|
||||
import { setupTestDbHooks } from '@/db-test-hooks'
|
||||
import {
|
||||
updateTaskStatusActivity,
|
||||
updateAssetStatusActivity,
|
||||
updateTaskUsageActivity,
|
||||
} from './task'
|
||||
import { updateTaskStatusActivity, updateAssetStatusActivity, updateTaskUsageActivity } from './db'
|
||||
import { WorkflowTaskStatus, WorkflowTaskType, AssetStatus } from '@/generated/prisma/client'
|
||||
|
||||
describe('Task Activities', () => {
|
||||
|
||||
@@ -1,52 +1,3 @@
|
||||
import { prisma } from '@/db'
|
||||
import { WorkflowTaskStatus, AssetStatus } from '@/generated/prisma/client'
|
||||
|
||||
export interface UpdateTaskStatusParams {
|
||||
taskId: string
|
||||
status: WorkflowTaskStatus
|
||||
output?: unknown
|
||||
}
|
||||
|
||||
export async function updateTaskStatusActivity(params: UpdateTaskStatusParams): Promise<void> {
|
||||
await prisma.workflowTask.update({
|
||||
where: { id: params.taskId },
|
||||
data: {
|
||||
status: params.status,
|
||||
output: params.output,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export interface UpdateAssetStatusParams {
|
||||
assetId: string
|
||||
status: AssetStatus
|
||||
}
|
||||
|
||||
export async function updateAssetStatusActivity(params: UpdateAssetStatusParams): Promise<void> {
|
||||
await prisma.asset.update({
|
||||
where: { id: params.assetId },
|
||||
data: { status: params.status },
|
||||
})
|
||||
}
|
||||
|
||||
export interface UpdateTaskUsageParams {
|
||||
taskId: string
|
||||
inputTokens: number
|
||||
outputTokens: number
|
||||
model: string
|
||||
}
|
||||
|
||||
export async function updateTaskUsageActivity(params: UpdateTaskUsageParams): Promise<void> {
|
||||
await prisma.workflowTask.update({
|
||||
where: { id: params.taskId },
|
||||
data: {
|
||||
inputTokens: params.inputTokens,
|
||||
outputTokens: params.outputTokens,
|
||||
model: params.model,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export async function getTranscodeWorkerQueueActivity(): Promise<string> {
|
||||
return 'transcode_queue'
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user