mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-23 17:47:38 +00:00
refactor(workflow): split database and agent activities for strict database isolation
This commit is contained in:
@@ -1,17 +1,7 @@
|
||||
import { describe, expect, test, vi, beforeEach } from 'vitest'
|
||||
import { describe, expect, test } from 'vitest'
|
||||
import { AgentService } from './agent'
|
||||
import { prisma } from '@/db'
|
||||
import { setupTestDbHooks } from '@/db-test-hooks'
|
||||
import * as piAgent from '@/agent'
|
||||
import { type AutofillField } from '@/agent'
|
||||
|
||||
vi.mock('@/agent', async () => {
|
||||
const actual = await vi.importActual('@/agent')
|
||||
return {
|
||||
...actual,
|
||||
createAgentSession: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
describe('AgentService', () => {
|
||||
setupTestDbHooks()
|
||||
@@ -230,273 +220,4 @@ describe('AgentService', () => {
|
||||
expect(agents[0].modelRef).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('agent execution', () => {
|
||||
const mockProviderConfig: PrismaJson.AiProviderSettings = {
|
||||
apiKey: 'test-key',
|
||||
}
|
||||
|
||||
const mockModelConfig: PrismaJson.ModelConfig = {
|
||||
reasoning: false,
|
||||
input: ['text'],
|
||||
contextWindow: 1000,
|
||||
maxTokens: 1000,
|
||||
cost: {
|
||||
input: 0,
|
||||
output: 0,
|
||||
cacheRead: 0,
|
||||
cacheWrite: 0,
|
||||
},
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
test('autofill extracts metadata', async () => {
|
||||
const db = prisma
|
||||
const svc = new AgentService()
|
||||
|
||||
const team = await db.team.create({
|
||||
data: {
|
||||
name: 'Autofill Team',
|
||||
},
|
||||
})
|
||||
|
||||
const provider = await db.provider.create({
|
||||
data: {
|
||||
name: 'google',
|
||||
teamId: team.id,
|
||||
// Config is generic Json in Prisma
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
config: mockProviderConfig as any,
|
||||
},
|
||||
})
|
||||
|
||||
const model = await db.model.create({
|
||||
data: {
|
||||
modelId: 'gemini',
|
||||
name: 'Gemini',
|
||||
providerId: provider.id,
|
||||
// Config is generic Json in Prisma
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
config: mockModelConfig as any,
|
||||
},
|
||||
})
|
||||
|
||||
await db.user.create({
|
||||
data: {
|
||||
name: 'Autofiller',
|
||||
email: `autofiller-${Date.now()}@shumai.ai`,
|
||||
type: 'agent',
|
||||
agent: {
|
||||
create: {
|
||||
teamId: team.id,
|
||||
type: 'autofill',
|
||||
enabled: true,
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
config: {
|
||||
provider: 'google',
|
||||
model: 'gemini',
|
||||
},
|
||||
},
|
||||
},
|
||||
teamMembers: {
|
||||
create: {
|
||||
teamId: team.id,
|
||||
role: 'reviewer',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const mockHarness = {
|
||||
prompt: vi.fn().mockResolvedValue({
|
||||
content: [{ type: 'text', text: 'Metadata captured successfully.' }],
|
||||
usage: { input: 5, output: 5 },
|
||||
}),
|
||||
}
|
||||
const mockSession = {
|
||||
getEntries: vi.fn().mockResolvedValue([]),
|
||||
getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }),
|
||||
}
|
||||
|
||||
// Mocking createAgentSession which has complex internal types
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(piAgent.createAgentSession as any).mockImplementation(async (config: unknown) => {
|
||||
const tool = (
|
||||
config as {
|
||||
customTools: Array<{ name: string; execute: (...args: unknown[]) => Promise<unknown> }>
|
||||
}
|
||||
).customTools.find((t) => t.name === 'autofill_metadata')
|
||||
if (tool) {
|
||||
await tool.execute('1', { f1: 'data-val' }, undefined)
|
||||
}
|
||||
return { session: mockSession, harness: mockHarness }
|
||||
})
|
||||
|
||||
const fields: AutofillField[] = [{ id: 'f1', config: { name: 'Field 1', type: 'text' } }]
|
||||
const resp = await svc.autofill(team.id, 'extract data', [], fields)
|
||||
expect(resp.text).toBe('{"f1":"data-val"}')
|
||||
expect(resp.usage.inputTokens).toBe(5)
|
||||
})
|
||||
|
||||
test('chats with bot', async () => {
|
||||
const db = prisma
|
||||
const svc = new AgentService()
|
||||
|
||||
const team = await db.team.create({
|
||||
data: {
|
||||
name: 'Chat Bot Team',
|
||||
},
|
||||
})
|
||||
|
||||
const provider = await db.provider.create({
|
||||
data: {
|
||||
name: 'google',
|
||||
teamId: team.id,
|
||||
// Config is generic Json in Prisma
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
config: mockProviderConfig as any,
|
||||
},
|
||||
})
|
||||
|
||||
const model = await db.model.create({
|
||||
data: {
|
||||
modelId: 'gemini',
|
||||
name: 'Gemini',
|
||||
providerId: provider.id,
|
||||
// Config is generic Json in Prisma
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
config: mockModelConfig as any,
|
||||
},
|
||||
})
|
||||
|
||||
await db.user.create({
|
||||
data: {
|
||||
name: 'Chatter',
|
||||
email: `chatter-${Date.now()}@shumai.ai`,
|
||||
type: 'agent',
|
||||
agent: {
|
||||
create: {
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
config: {
|
||||
provider: 'google',
|
||||
model: 'gemini',
|
||||
},
|
||||
},
|
||||
},
|
||||
teamMembers: {
|
||||
create: {
|
||||
teamId: team.id,
|
||||
role: 'reviewer',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const mockHarness = {
|
||||
prompt: vi.fn().mockResolvedValue({
|
||||
content: [{ type: 'text', text: 'mock text' }],
|
||||
usage: { input: 5, output: 5 },
|
||||
}),
|
||||
}
|
||||
const mockSession = {
|
||||
getEntries: vi.fn().mockResolvedValue([]),
|
||||
getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }),
|
||||
}
|
||||
// Mocking createAgentSession
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(piAgent.createAgentSession as any).mockResolvedValue({
|
||||
session: mockSession,
|
||||
harness: mockHarness,
|
||||
})
|
||||
|
||||
const resp = await svc.chat(team.id, 'hello')
|
||||
expect(resp.text).toBe('mock text')
|
||||
})
|
||||
|
||||
test('chat with instruction', async () => {
|
||||
const db = prisma
|
||||
const svc = new AgentService()
|
||||
|
||||
const team = await db.team.create({
|
||||
data: {
|
||||
name: 'Pirate Team',
|
||||
},
|
||||
})
|
||||
|
||||
const provider = await db.provider.create({
|
||||
data: {
|
||||
name: 'google',
|
||||
teamId: team.id,
|
||||
// Config is generic Json in Prisma
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
config: mockProviderConfig as any,
|
||||
},
|
||||
})
|
||||
|
||||
const model = await db.model.create({
|
||||
data: {
|
||||
modelId: 'gemini-pro',
|
||||
name: 'Gemini Pro',
|
||||
providerId: provider.id,
|
||||
// Config is generic Json in Prisma
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
config: mockModelConfig as any,
|
||||
},
|
||||
})
|
||||
|
||||
const botUser = await db.user.create({
|
||||
data: { name: 'Pirate', email: 'pirate@shumai.ai', type: 'agent' },
|
||||
})
|
||||
|
||||
const agent = await db.agent.create({
|
||||
data: {
|
||||
id: botUser.id,
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
soul: 'You are a pirate',
|
||||
config: {
|
||||
provider: 'google',
|
||||
model: 'gemini-pro',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await db.teamMember.create({
|
||||
data: { teamId: team.id, userId: botUser.id, role: 'reviewer' },
|
||||
})
|
||||
|
||||
const mockHarness = {
|
||||
prompt: vi.fn().mockResolvedValue({
|
||||
content: [{ type: 'text', text: 'Arr matey!' }],
|
||||
usage: { input: 10, output: 20 },
|
||||
}),
|
||||
}
|
||||
const mockSession = {
|
||||
getEntries: vi.fn().mockResolvedValue([]),
|
||||
getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }),
|
||||
}
|
||||
// Mocking createAgentSession
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(piAgent.createAgentSession as any).mockResolvedValue({
|
||||
session: mockSession,
|
||||
harness: mockHarness,
|
||||
})
|
||||
|
||||
const resp = await svc.chatWithAgent(team.id, agent.id, 'hello', [], 'Talk like a pirate')
|
||||
expect(resp.text).toBe('Arr matey!')
|
||||
expect(resp.usage.inputTokens).toBe(10)
|
||||
expect(resp.usage.outputTokens).toBe(20)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -6,12 +6,6 @@ import {
|
||||
UpdateAgentParams,
|
||||
} from '@/dtos/agent'
|
||||
import '@/prisma-json-types'
|
||||
import { createAgentSession, fieldsToTypeBoxSchema, type AutofillField } from '@/agent'
|
||||
import { logger } from '@/logger'
|
||||
import { Usage } from '@/services/ai/provider/provider'
|
||||
import { s3Service } from '@/services/s3/s3'
|
||||
import { type AgentTool } from '@earendil-works/pi-agent-core'
|
||||
import { type ImageContent } from '@earendil-works/pi-ai'
|
||||
|
||||
export class AgentService {
|
||||
constructor(private readonly prismaClient: typeof prisma = prisma) {}
|
||||
@@ -240,219 +234,6 @@ export class AgentService {
|
||||
})
|
||||
}
|
||||
|
||||
private async getTeam(teamId: string) {
|
||||
return this.prismaClient.team.findUnique({
|
||||
where: { id: teamId },
|
||||
})
|
||||
}
|
||||
|
||||
private async getSandbox(teamId: string) {
|
||||
return this.prismaClient.sandbox.findUnique({
|
||||
where: { teamId },
|
||||
})
|
||||
}
|
||||
|
||||
async chat(teamId: string, prompt: string): Promise<{ text: string; usage: Usage }> {
|
||||
const agent = await this.prismaClient.agent.findFirst({
|
||||
where: {
|
||||
type: 'chat',
|
||||
enabled: true,
|
||||
teamId,
|
||||
},
|
||||
})
|
||||
if (!agent) {
|
||||
throw new Error('no chat agent found for team')
|
||||
}
|
||||
const { text, usage } = await this.chatWithAgent(teamId, agent.id, prompt, [], '')
|
||||
return { text, usage }
|
||||
}
|
||||
|
||||
async chatWithAgent(
|
||||
teamId: string,
|
||||
agentId: string,
|
||||
prompt: string,
|
||||
images: string[],
|
||||
agentsInstruction: string,
|
||||
sessionId?: string,
|
||||
userId?: string,
|
||||
tools: AgentTool[] = [],
|
||||
): Promise<{ text: string; usage: Usage; sessionId: string }> {
|
||||
const t = await this.getTeam(teamId)
|
||||
if (!t) throw new Error('failed to get team')
|
||||
|
||||
const agent = await this.prismaClient.agent.findUnique({
|
||||
where: { id: agentId },
|
||||
include: {
|
||||
provider: true,
|
||||
modelRef: true,
|
||||
},
|
||||
})
|
||||
|
||||
if (!agent) {
|
||||
throw new Error(`agent ${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
|
||||
const modelId = agent.modelRef.modelId
|
||||
|
||||
// Fetch the required provider configuration from database
|
||||
const dbProviders = await this.prismaClient.provider.findMany({
|
||||
where: { teamId, name: providerName },
|
||||
include: { models: true },
|
||||
})
|
||||
|
||||
// Fetch team skills
|
||||
const teamSkills = await this.prismaClient.skill.findMany({
|
||||
where: { teamId },
|
||||
})
|
||||
|
||||
const sandbox = await this.getSandbox(teamId)
|
||||
const allowedDomains = sandbox?.allowedDomains || []
|
||||
|
||||
let systemPrompt = '你是shumai小助手。'
|
||||
if (agentsInstruction) {
|
||||
systemPrompt = `${systemPrompt}\n\nContext and Instructions:\n${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,
|
||||
providerName,
|
||||
modelId,
|
||||
systemPrompt,
|
||||
teamSkills: teamSkills.map((s) => ({
|
||||
id: s.id,
|
||||
name: s.name,
|
||||
description: s.description,
|
||||
})),
|
||||
allowedDomains,
|
||||
sessionId,
|
||||
userId,
|
||||
customTools: tools,
|
||||
providers: dbProviders.map((p) => ({
|
||||
name: p.name,
|
||||
config: p.config,
|
||||
models: p.models.map((m) => ({
|
||||
modelId: m.modelId,
|
||||
name: m.name,
|
||||
config: m.config,
|
||||
})),
|
||||
})),
|
||||
})
|
||||
|
||||
const imagesToPass: ImageContent[] = []
|
||||
|
||||
if (images && images.length > 0) {
|
||||
for (const key of 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(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
|
||||
}
|
||||
}
|
||||
|
||||
async autofill(
|
||||
teamId: string,
|
||||
prompt: string,
|
||||
images: string[],
|
||||
fields: AutofillField[],
|
||||
): Promise<{ text: string; usage: Usage; sessionId: string }> {
|
||||
const agent = await this.prismaClient.agent.findFirst({
|
||||
where: {
|
||||
type: 'autofill',
|
||||
enabled: true,
|
||||
teamId,
|
||||
},
|
||||
})
|
||||
if (!agent) {
|
||||
throw new Error('no autofill agent found for team')
|
||||
}
|
||||
|
||||
const toolSchema = fieldsToTypeBoxSchema(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, params) => {
|
||||
capturedData = params
|
||||
return {
|
||||
content: [{ type: 'text', text: 'Metadata captured successfully.' }],
|
||||
details: {},
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
const fullPrompt = `${prompt}\n\nPlease use the "autofill_metadata" tool to provide the extracted metadata.`
|
||||
|
||||
const { usage, sessionId } = await this.chatWithAgent(
|
||||
teamId,
|
||||
agent.id,
|
||||
fullPrompt,
|
||||
images,
|
||||
'',
|
||||
undefined,
|
||||
undefined,
|
||||
[autofillTool],
|
||||
)
|
||||
|
||||
return {
|
||||
text: capturedData ? JSON.stringify(capturedData) : '{}',
|
||||
usage,
|
||||
sessionId,
|
||||
}
|
||||
}
|
||||
|
||||
async getSessionEntries(params: { sessionId: string }) {
|
||||
return this.prismaClient.agentSessionEntry.findMany({
|
||||
where: { sessionId: params.sessionId },
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { prisma } from '@/db'
|
||||
import { setupTestDbHooks } from '@/db-test-hooks'
|
||||
import { aiService } from './ai'
|
||||
|
||||
const mockProviderConfig: PrismaJson.ProviderConfig = {
|
||||
api: 'openai-completions',
|
||||
baseUrl: 'http://localhost:11434/v1',
|
||||
apiKey: 'test-key',
|
||||
}
|
||||
|
||||
const mockModelConfig: PrismaJson.ModelConfig = {
|
||||
reasoning: false,
|
||||
input: ['text'],
|
||||
contextWindow: 1000,
|
||||
maxTokens: 1000,
|
||||
cost: {
|
||||
input: 0,
|
||||
output: 0,
|
||||
cacheRead: 0,
|
||||
cacheWrite: 0,
|
||||
},
|
||||
}
|
||||
|
||||
describe('AiService', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('transcribes', async () => {
|
||||
// Transcribe still uses provider factory
|
||||
const mockTranscribe = vi.fn().mockResolvedValue({
|
||||
text: 'mock transcription',
|
||||
usage: { model: 'whisper', inputTokens: 0, outputTokens: 0 },
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(aiService as any).providerFactory = () => ({
|
||||
transcribe: mockTranscribe,
|
||||
})
|
||||
|
||||
const team = await prisma.team.create({
|
||||
data: {
|
||||
name: 'Transcribe Team',
|
||||
},
|
||||
})
|
||||
|
||||
const provider = await prisma.provider.create({
|
||||
data: {
|
||||
name: 'openai',
|
||||
teamId: team.id,
|
||||
config: mockProviderConfig,
|
||||
},
|
||||
})
|
||||
|
||||
const model = await prisma.model.create({
|
||||
data: {
|
||||
modelId: 'whisper',
|
||||
name: 'Whisper',
|
||||
providerId: provider.id,
|
||||
config: mockModelConfig,
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.user.create({
|
||||
data: {
|
||||
name: 'Transcriber',
|
||||
email: `transcriber-${Date.now()}@shumai.ai`,
|
||||
type: 'agent',
|
||||
agent: {
|
||||
create: {
|
||||
teamId: team.id,
|
||||
type: 'transcription',
|
||||
enabled: true,
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
config: {
|
||||
provider: 'openai',
|
||||
model: 'whisper',
|
||||
},
|
||||
},
|
||||
},
|
||||
teamMembers: {
|
||||
create: {
|
||||
teamId: team.id,
|
||||
role: 'reviewer',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const resp = await aiService.transcribe(team.id, Buffer.from(''))
|
||||
expect(resp.text).toBe('mock transcription')
|
||||
expect(mockTranscribe).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,242 +0,0 @@
|
||||
import { prisma } from '@/db'
|
||||
import { AiProvider } from '@/dtos/ai'
|
||||
import { s3Service } from '@/services/s3/s3'
|
||||
|
||||
import { exec } from 'child_process'
|
||||
import * as fs from 'fs'
|
||||
import * as os from 'os'
|
||||
import * as path from 'path'
|
||||
import { promisify } from 'util'
|
||||
import { ElevenLabsProvider } from './provider/elevenlabs'
|
||||
import { GeminiProvider } from './provider/gemini'
|
||||
import { OpenAiProvider } from './provider/openai'
|
||||
import { Provider, Usage } from './provider/provider'
|
||||
|
||||
const execAsync = promisify(exec)
|
||||
|
||||
export type ProviderFactory = (
|
||||
providerName: string,
|
||||
config: PrismaJson.AiProviderSettings,
|
||||
) => Provider
|
||||
|
||||
function defaultProviderFactory(
|
||||
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}`)
|
||||
}
|
||||
|
||||
// Typecasting config for now to match the strict interface in providers.
|
||||
switch (pKey) {
|
||||
case AiProvider.Google:
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return new GeminiProvider(config as any)
|
||||
case AiProvider.OpenAi:
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return new OpenAiProvider(config as any)
|
||||
case AiProvider.ElevenLabs:
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return new ElevenLabsProvider(config as any)
|
||||
default:
|
||||
throw new Error(`Provider implementation for ${providerName} not found`)
|
||||
}
|
||||
}
|
||||
|
||||
export class AiService {
|
||||
private providerFactory: ProviderFactory = defaultProviderFactory
|
||||
|
||||
constructor(private readonly prismaClient: typeof prisma = prisma) {}
|
||||
|
||||
private async getTeam(teamId: string) {
|
||||
return this.prismaClient.team.findUnique({
|
||||
where: { id: teamId },
|
||||
})
|
||||
}
|
||||
|
||||
async transcribe(teamId: string, audioBuffer: Buffer): Promise<{ text: string; usage: Usage }> {
|
||||
const t = await this.getTeam(teamId)
|
||||
if (!t) throw new Error('failed to get team')
|
||||
|
||||
const agent = await this.prismaClient.agent.findFirst({
|
||||
where: {
|
||||
type: 'transcription',
|
||||
enabled: true,
|
||||
user: { teamMembers: { some: { teamId } } },
|
||||
},
|
||||
})
|
||||
if (!agent) {
|
||||
throw new Error('transcription feature is disabled or agent not found')
|
||||
}
|
||||
|
||||
const config = agent.config as unknown as PrismaJson.AgentConfig
|
||||
if (!config.provider) throw new Error('transcription provider not configured')
|
||||
if (!config.model) throw new Error('transcription model not configured')
|
||||
|
||||
const dbProvider = await this.prismaClient.provider.findFirst({
|
||||
where: { teamId, name: config.provider },
|
||||
})
|
||||
if (!dbProvider) throw new Error(`Provider ${config.provider} not found in database`)
|
||||
|
||||
const p = this.providerFactory(
|
||||
config.provider,
|
||||
dbProvider.config as PrismaJson.AiProviderSettings,
|
||||
)
|
||||
|
||||
return p.transcribe(config.model, audioBuffer)
|
||||
}
|
||||
|
||||
async generateAssetEmbeddings(teamId: string, assetId: string): Promise<Usage> {
|
||||
const t = await this.getTeam(teamId)
|
||||
if (!t) throw new Error('failed to get team')
|
||||
|
||||
const agent = await this.prismaClient.agent.findFirst({
|
||||
where: {
|
||||
type: 'embedding',
|
||||
enabled: true,
|
||||
user: { teamMembers: { some: { 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 this.prismaClient.asset.findUnique({
|
||||
where: { id: 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 this.prismaClient.provider.findFirst({
|
||||
where: { teamId, name: config.provider },
|
||||
})
|
||||
if (!dbProvider) throw new Error(`Provider ${config.provider} not found in database`)
|
||||
|
||||
const p = this.providerFactory(
|
||||
config.provider,
|
||||
dbProvider.config as PrismaJson.AiProviderSettings,
|
||||
)
|
||||
|
||||
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)
|
||||
|
||||
if (isImage) {
|
||||
const embVec = await p.generateImageEmbedding(config.model, data)
|
||||
|
||||
await this.prismaClient.$executeRaw`
|
||||
INSERT INTO asset_embeddings (id, asset_id, embedding, updated_at)
|
||||
VALUES (gen_random_uuid()::text, ${asset.id}, ${embVec}::vector, NOW())
|
||||
`
|
||||
} 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)
|
||||
await this.prismaClient.$executeRaw`
|
||||
INSERT INTO asset_embeddings (id, asset_id, embedding, start_time, end_time, updated_at)
|
||||
VALUES (gen_random_uuid()::text, ${asset.id}, ${embVec}::vector, ${start}, ${end}, NOW())
|
||||
`
|
||||
// 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 usage
|
||||
}
|
||||
|
||||
async generateTextEmbeddings(teamId: string, text: string): Promise<number[]> {
|
||||
const t = await this.getTeam(teamId)
|
||||
if (!t) throw new Error('failed to get team')
|
||||
|
||||
const agent = await this.prismaClient.agent.findFirst({
|
||||
where: {
|
||||
type: 'embedding',
|
||||
enabled: true,
|
||||
user: { teamMembers: { some: { 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 dbProvider = await this.prismaClient.provider.findFirst({
|
||||
where: { teamId, name: config.provider },
|
||||
})
|
||||
if (!dbProvider) throw new Error(`Provider ${config.provider} not found in database`)
|
||||
|
||||
const p = this.providerFactory(
|
||||
config.provider,
|
||||
dbProvider.config as PrismaJson.AiProviderSettings,
|
||||
)
|
||||
|
||||
return p.generateTextEmbedding(config.model, text)
|
||||
}
|
||||
}
|
||||
|
||||
export const aiService = new AiService()
|
||||
@@ -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'
|
||||
}
|
||||
|
||||
@@ -2,9 +2,9 @@ import { prisma } from '@/db'
|
||||
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@/generated/prisma/client'
|
||||
import { Executor } from './executor'
|
||||
import { aiTranscriptionMedia } from './workflows/ai-transcription'
|
||||
import { aiEmbeddingMedia } from './workflows/ai-embedding'
|
||||
import { aiAutofillMedia } from './workflows/ai-autofill'
|
||||
import { aiChat } from './workflows/ai-chat'
|
||||
import { agentEmbeddingMedia } from './workflows/agent-embedding'
|
||||
import { agentAutofillMedia } from './workflows/agent-autofill'
|
||||
import { agentChat } from './workflows/agent-chat'
|
||||
import { transcodeMedia } from '@/transcode/workflows/transcode'
|
||||
import { activities } from './activities/index'
|
||||
import { logger } from '@/logger'
|
||||
@@ -87,13 +87,13 @@ export class LocalExecutor implements Executor {
|
||||
await aiTranscriptionMedia(task)
|
||||
break
|
||||
case WorkflowTaskType.ai_embedding:
|
||||
await aiEmbeddingMedia(task)
|
||||
await agentEmbeddingMedia(task)
|
||||
break
|
||||
case WorkflowTaskType.ai_metadata_autofill:
|
||||
await aiAutofillMedia(task)
|
||||
await agentAutofillMedia(task)
|
||||
break
|
||||
case WorkflowTaskType.chat:
|
||||
await aiChat(task)
|
||||
await agentChat(task)
|
||||
break
|
||||
case WorkflowTaskType.transcode:
|
||||
await transcodeMedia(task)
|
||||
|
||||
@@ -20,13 +20,13 @@ export class TemporalExecutor implements Executor {
|
||||
workflowName = 'aiTranscriptionWorkflow'
|
||||
break
|
||||
case WorkflowTaskType.ai_embedding:
|
||||
workflowName = 'aiEmbeddingWorkflow'
|
||||
workflowName = 'agentEmbeddingWorkflow'
|
||||
break
|
||||
case WorkflowTaskType.ai_metadata_autofill:
|
||||
workflowName = 'aiAutofillWorkflow'
|
||||
workflowName = 'agentAutofillWorkflow'
|
||||
break
|
||||
case WorkflowTaskType.chat:
|
||||
workflowName = 'aiChatWorkflow'
|
||||
workflowName = 'agentChatWorkflow'
|
||||
break
|
||||
case WorkflowTaskType.transcode:
|
||||
workflowName = 'transcodeWorkflow'
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { agentAutofillMedia } from './agent-autofill'
|
||||
import { prisma } from '@/db'
|
||||
import { setupTestDbHooks } from '@/db-test-hooks'
|
||||
import * as workflowUtils from '@/workflow/workflow-utils'
|
||||
|
||||
vi.mock('@/workflow/workflow-utils', async () => {
|
||||
const actual = await vi.importActual('@/workflow/workflow-utils')
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
describe('Agent Autofill Workflow', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should run agent autofill workflow successfully', async () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
||||
extractAiMetadataActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'extractAiMetadataActivity',
|
||||
}),
|
||||
getProjectAutofillFieldsActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getProjectAutofillFieldsActivity',
|
||||
}),
|
||||
getAgentAutofillContextActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAgentAutofillContextActivity',
|
||||
}),
|
||||
autofillAiActivity: Object.assign(vi.fn(), { _activityName: 'autofillAiActivity' }),
|
||||
updateTaskUsageActivity: Object.assign(vi.fn(), { _activityName: 'updateTaskUsageActivity' }),
|
||||
updateAssetMetadataActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateAssetMetadataActivity',
|
||||
}),
|
||||
createCommentActivity: Object.assign(vi.fn(), { _activityName: 'createCommentActivity' }),
|
||||
updateCommentActivity: Object.assign(vi.fn(), { _activityName: 'updateCommentActivity' }),
|
||||
getTranscodeWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getTranscodeWorkerQueueActivity',
|
||||
}),
|
||||
getAgentWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAgentWorkerQueueActivity',
|
||||
}),
|
||||
downloadMediaToTmpActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'downloadMediaToTmpActivity',
|
||||
}),
|
||||
cleanupTmpDirActivity: Object.assign(vi.fn(), { _activityName: 'cleanupTmpDirActivity' }),
|
||||
}
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' })
|
||||
mockActivities.getAssetActivity.mockResolvedValue({ id: 'a1', storageKey: { key: 'asset-key' }, project: { id: 'p1', teamId: 't1' }, mediaType: 'image/png' })
|
||||
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_queue')
|
||||
mockActivities.downloadMediaToTmpActivity.mockResolvedValue({ filePath: '/tmp/test.png', tmpDir: '/tmp' })
|
||||
mockActivities.extractAiMetadataActivity.mockResolvedValue(['/tmp/1.webp'])
|
||||
mockActivities.getProjectAutofillFieldsActivity.mockResolvedValue([{ id: 'f1', config: { name: 'F1', type: 'text' } }])
|
||||
mockActivities.getAgentAutofillContextActivity.mockResolvedValue({ agent: { id: 'b1' } })
|
||||
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
|
||||
mockActivities.autofillAiActivity.mockResolvedValue({
|
||||
text: '{"f1":"val"}',
|
||||
sessionId: 'session-123',
|
||||
usage: { inputTokens: 5, outputTokens: 5, model: 'gpt' },
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities contains vi.fn mock functions which are cast to expected activity proxy types
|
||||
vi.mocked(workflowUtils.getActivities).mockReturnValue(mockActivities as any)
|
||||
vi.mocked(workflowUtils.executeActivity).mockImplementation(async (_queue, act, ...args) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- act is one of the mocked activities
|
||||
return (act as any)(...args)
|
||||
})
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'ai_metadata_autofill',
|
||||
status: 'pending',
|
||||
assetId: 'a1',
|
||||
},
|
||||
})
|
||||
|
||||
await agentAutofillMedia(task)
|
||||
|
||||
expect(mockActivities.getAgentAutofillContextActivity).toHaveBeenCalled()
|
||||
expect(mockActivities.autofillAiActivity).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -7,12 +7,13 @@ import {
|
||||
TaskQueueTranscode,
|
||||
} from '@/workflow/workflow-utils'
|
||||
|
||||
export async function aiAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
const {
|
||||
updateTaskStatusActivity,
|
||||
getAssetActivity,
|
||||
extractAiMetadataActivity,
|
||||
getProjectAutofillFieldsActivity,
|
||||
getAgentAutofillContextActivity,
|
||||
autofillAiActivity,
|
||||
updateTaskUsageActivity,
|
||||
updateAssetMetadataActivity,
|
||||
@@ -107,6 +108,11 @@ export async function aiAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
return
|
||||
}
|
||||
|
||||
// 3b. Fetch Agent Context (Database Activity on db_queue)
|
||||
const context = await executeActivity(TaskQueueDb, getAgentAutofillContextActivity, {
|
||||
teamId,
|
||||
})
|
||||
|
||||
// 4. Call AI Service
|
||||
const agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
|
||||
|
||||
@@ -118,6 +124,7 @@ export async function aiAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
config: f.config as unknown as PrismaJson.FieldConfig,
|
||||
description: f.description,
|
||||
})),
|
||||
context,
|
||||
})
|
||||
|
||||
if (aiResult.usage) {
|
||||
@@ -159,7 +166,7 @@ export async function aiAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
status: 'completed',
|
||||
})
|
||||
} catch (err) {
|
||||
console.error(`AiAutofillMedia failed for task ${task.id}:`, err)
|
||||
console.error(`AgentAutofillMedia failed for task ${task.id}:`, err)
|
||||
|
||||
// Update placeholder comment with error message
|
||||
if (placeholderCommentId) {
|
||||
@@ -191,4 +198,4 @@ export async function aiAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
export const aiAutofillWorkflow = aiAutofillMedia
|
||||
export const agentAutofillWorkflow = agentAutofillMedia
|
||||
@@ -0,0 +1,79 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { agentChat } from './agent-chat'
|
||||
import { prisma } from '@/db'
|
||||
import { setupTestDbHooks } from '@/db-test-hooks'
|
||||
import * as workflowUtils from '@/workflow/workflow-utils'
|
||||
|
||||
vi.mock('@/workflow/workflow-utils', async () => {
|
||||
const actual = await vi.importActual('@/workflow/workflow-utils')
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
describe('Agent Chat Workflow', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should run agent chat workflow successfully', async () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
getCommentActivity: Object.assign(vi.fn(), { _activityName: 'getCommentActivity' }),
|
||||
createCommentActivity: Object.assign(vi.fn(), { _activityName: 'createCommentActivity' }),
|
||||
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
||||
initializeAgentSessionActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'initializeAgentSessionActivity',
|
||||
}),
|
||||
getAgentChatContextActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAgentChatContextActivity',
|
||||
}),
|
||||
getAgentWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAgentWorkerQueueActivity',
|
||||
}),
|
||||
agentChatActivity: Object.assign(vi.fn(), { _activityName: 'agentChatActivity' }),
|
||||
updateCommentActivity: Object.assign(vi.fn(), { _activityName: 'updateCommentActivity' }),
|
||||
updateTaskUsageActivity: Object.assign(vi.fn(), { _activityName: 'updateTaskUsageActivity' }),
|
||||
deleteCommentActivity: Object.assign(vi.fn(), { _activityName: 'deleteCommentActivity' }),
|
||||
}
|
||||
|
||||
mockActivities.getCommentActivity.mockResolvedValue({ id: 'c1', message: 'hello', replyToId: null })
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' })
|
||||
mockActivities.getAssetActivity.mockResolvedValue({ id: 'a1', project: { teamId: 't1' } })
|
||||
mockActivities.initializeAgentSessionActivity.mockResolvedValue('session-123')
|
||||
mockActivities.getAgentChatContextActivity.mockResolvedValue({ agent: { id: 'b1' } })
|
||||
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
|
||||
mockActivities.agentChatActivity.mockResolvedValue({
|
||||
text: 'arr matey!',
|
||||
sessionId: 'session-123',
|
||||
usage: { inputTokens: 5, outputTokens: 5, model: 'gpt' },
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities contains vi.fn mock functions which are cast to expected activity proxy types
|
||||
vi.mocked(workflowUtils.getActivities).mockReturnValue(mockActivities as any)
|
||||
vi.mocked(workflowUtils.executeActivity).mockImplementation(async (_queue, act, ...args) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- act is one of the mocked activities
|
||||
return (act as any)(...args)
|
||||
})
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'chat',
|
||||
status: 'pending',
|
||||
assetId: 'a1',
|
||||
payload: { userCommentId: 'c1', agentId: 'b1' },
|
||||
},
|
||||
})
|
||||
|
||||
await agentChat(task)
|
||||
|
||||
expect(mockActivities.getAgentChatContextActivity).toHaveBeenCalled()
|
||||
expect(mockActivities.agentChatActivity).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -6,12 +6,13 @@ import {
|
||||
TaskQueueDb,
|
||||
} from '@/workflow/workflow-utils'
|
||||
|
||||
export async function aiChat(task: WorkflowTask): Promise<void> {
|
||||
export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
const {
|
||||
updateTaskStatusActivity,
|
||||
getAssetActivity,
|
||||
getCommentActivity,
|
||||
aiChatActivity,
|
||||
getAgentChatContextActivity,
|
||||
agentChatActivity,
|
||||
createCommentActivity,
|
||||
updateCommentActivity,
|
||||
updateTaskUsageActivity,
|
||||
@@ -67,6 +68,12 @@ export async function aiChat(task: WorkflowTask): Promise<void> {
|
||||
})
|
||||
}
|
||||
|
||||
// 4b. Fetch Agent Context (Database Activity on db_queue)
|
||||
const context = await executeActivity(TaskQueueDb, getAgentChatContextActivity, {
|
||||
teamId,
|
||||
agentId: payload.agentId,
|
||||
})
|
||||
|
||||
// 5. Prepare Images (Attachments only)
|
||||
const attachmentImageUrls: string[] = []
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
@@ -103,7 +110,7 @@ export async function aiChat(task: WorkflowTask): Promise<void> {
|
||||
|
||||
const agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
|
||||
|
||||
const aiResult = await executeActivity(agentWorkerQueue, aiChatActivity, {
|
||||
const aiResult = await executeActivity(agentWorkerQueue, agentChatActivity, {
|
||||
teamId,
|
||||
agentId: payload.agentId,
|
||||
message: userComment.message || '',
|
||||
@@ -114,6 +121,7 @@ export async function aiChat(task: WorkflowTask): Promise<void> {
|
||||
sessionId,
|
||||
userId: payload.userId,
|
||||
explicitMention: payload?.explicitMention,
|
||||
context,
|
||||
})
|
||||
|
||||
// 7. Update Placeholder Comment
|
||||
@@ -146,7 +154,7 @@ export async function aiChat(task: WorkflowTask): Promise<void> {
|
||||
output: { sessionId: aiResult.sessionId },
|
||||
})
|
||||
} catch (err) {
|
||||
console.error(`AiChat failed for task ${task.id}:`, err)
|
||||
console.error(`AgentChat failed for task ${task.id}:`, err)
|
||||
|
||||
// Update placeholder comment with error message
|
||||
if (placeholderCommentId) {
|
||||
@@ -175,4 +183,4 @@ export async function aiChat(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
export const aiChatWorkflow = aiChat
|
||||
export const agentChatWorkflow = agentChat
|
||||
@@ -0,0 +1,75 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { agentEmbeddingMedia } from './agent-embedding'
|
||||
import { prisma } from '@/db'
|
||||
import { setupTestDbHooks } from '@/db-test-hooks'
|
||||
import * as workflowUtils from '@/workflow/workflow-utils'
|
||||
|
||||
vi.mock('@/workflow/workflow-utils', async () => {
|
||||
const actual = await vi.importActual('@/workflow/workflow-utils')
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
describe('Agent Embedding Workflow', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should run agent embedding workflow successfully', async () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
getEmbeddingContextActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getEmbeddingContextActivity',
|
||||
}),
|
||||
generateEmbeddingActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'generateEmbeddingActivity',
|
||||
}),
|
||||
saveAssetEmbeddingsActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'saveAssetEmbeddingsActivity',
|
||||
}),
|
||||
updateTaskUsageActivity: Object.assign(vi.fn(), { _activityName: 'updateTaskUsageActivity' }),
|
||||
createCommentActivity: Object.assign(vi.fn(), { _activityName: 'createCommentActivity' }),
|
||||
updateCommentActivity: Object.assign(vi.fn(), { _activityName: 'updateCommentActivity' }),
|
||||
getAgentWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAgentWorkerQueueActivity',
|
||||
}),
|
||||
}
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' })
|
||||
mockActivities.getEmbeddingContextActivity.mockResolvedValue({ agent: { id: 'b1' }, asset: { id: 'a1' }, dbProvider: { name: 'google' } })
|
||||
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
|
||||
mockActivities.generateEmbeddingActivity.mockResolvedValue({
|
||||
embeddings: [{ embedding: [0.1, 0.2] }],
|
||||
usage: { inputTokens: 5, outputTokens: 5, model: 'gpt' },
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities contains vi.fn mock functions which are cast to expected activity proxy types
|
||||
vi.mocked(workflowUtils.getActivities).mockReturnValue(mockActivities as any)
|
||||
vi.mocked(workflowUtils.executeActivity).mockImplementation(async (_queue, act, ...args) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- act is one of the mocked activities
|
||||
return (act as any)(...args)
|
||||
})
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'ai_embedding',
|
||||
status: 'pending',
|
||||
assetId: 'a1',
|
||||
teamId: 't1',
|
||||
},
|
||||
})
|
||||
|
||||
await agentEmbeddingMedia(task)
|
||||
|
||||
expect(mockActivities.getEmbeddingContextActivity).toHaveBeenCalled()
|
||||
expect(mockActivities.generateEmbeddingActivity).toHaveBeenCalled()
|
||||
expect(mockActivities.saveAssetEmbeddingsActivity).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,10 +1,12 @@
|
||||
import type { WorkflowTask } from '@/generated/prisma/client'
|
||||
import { getActivities, executeActivity, TaskQueueDb, TaskQueueAgent } from '../workflow-utils'
|
||||
|
||||
export async function aiEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
const {
|
||||
updateTaskStatusActivity,
|
||||
getEmbeddingContextActivity,
|
||||
generateEmbeddingActivity,
|
||||
saveAssetEmbeddingsActivity,
|
||||
updateTaskUsageActivity,
|
||||
createCommentActivity,
|
||||
updateCommentActivity,
|
||||
@@ -32,21 +34,36 @@ export async function aiEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
|
||||
if (!task.teamId) throw new Error('Task has no teamId')
|
||||
|
||||
// 1. Fetch Agent Context (Database Activity on db_queue)
|
||||
const context = await executeActivity(TaskQueueDb, getEmbeddingContextActivity, {
|
||||
teamId: task.teamId,
|
||||
assetId: task.assetId,
|
||||
})
|
||||
|
||||
const agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
|
||||
|
||||
// Call the activity to generate embeddings
|
||||
const result = await executeActivity(agentWorkerQueue, generateEmbeddingActivity, {
|
||||
teamId: task.teamId,
|
||||
assetId: task.assetId,
|
||||
context,
|
||||
})
|
||||
|
||||
// Save computed embeddings
|
||||
if (result.embeddings.length > 0) {
|
||||
await executeActivity(TaskQueueDb, saveAssetEmbeddingsActivity, {
|
||||
assetId: task.assetId,
|
||||
embeddings: result.embeddings,
|
||||
})
|
||||
}
|
||||
|
||||
// Update Usage
|
||||
if (result) {
|
||||
if (result.usage) {
|
||||
await executeActivity(TaskQueueDb, updateTaskUsageActivity, {
|
||||
taskId: task.id,
|
||||
inputTokens: result.inputTokens,
|
||||
outputTokens: result.outputTokens,
|
||||
model: result.model,
|
||||
inputTokens: result.usage.inputTokens,
|
||||
outputTokens: result.usage.outputTokens,
|
||||
model: result.usage.model,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -64,7 +81,7 @@ export async function aiEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
status: 'completed',
|
||||
})
|
||||
} catch (err) {
|
||||
console.error(`AiEmbeddingMedia failed for task ${task.id}:`, err)
|
||||
console.error(`AgentEmbeddingMedia failed for task ${task.id}:`, err)
|
||||
|
||||
// Update placeholder comment with error message
|
||||
if (placeholderCommentId) {
|
||||
@@ -88,4 +105,4 @@ export async function aiEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
export const aiEmbeddingWorkflow = aiEmbeddingMedia
|
||||
export const agentEmbeddingWorkflow = agentEmbeddingMedia
|
||||
@@ -1,203 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { aiAutofillMedia } from './ai-autofill'
|
||||
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@/generated/prisma/client'
|
||||
import * as workflowUtils from '@/workflow/workflow-utils'
|
||||
|
||||
vi.mock('@/workflow/workflow-utils', async (importOriginal) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const actual = (await importOriginal()) as any
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
sleep: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
describe('AIAutofill Workflow', () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
||||
extractAiMetadataActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'extractAiMetadataActivity',
|
||||
}),
|
||||
getProjectAutofillFieldsActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getProjectAutofillFieldsActivity',
|
||||
}),
|
||||
autofillAiActivity: Object.assign(vi.fn(), { _activityName: 'autofillAiActivity' }),
|
||||
updateTaskUsageActivity: Object.assign(vi.fn(), { _activityName: 'updateTaskUsageActivity' }),
|
||||
updateAssetMetadataActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateAssetMetadataActivity',
|
||||
}),
|
||||
createCommentActivity: Object.assign(vi.fn(), { _activityName: 'createCommentActivity' }),
|
||||
updateCommentActivity: Object.assign(vi.fn(), { _activityName: 'updateCommentActivity' }),
|
||||
getTranscodeWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getTranscodeWorkerQueueActivity',
|
||||
}),
|
||||
getAgentWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAgentWorkerQueueActivity',
|
||||
}),
|
||||
downloadMediaToTmpActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'downloadMediaToTmpActivity',
|
||||
}),
|
||||
cleanupTmpDirActivity: Object.assign(vi.fn(), { _activityName: 'cleanupTmpDirActivity' }),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.getActivities as any).mockReturnValue(mockActivities)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.executeActivity as any).mockImplementation(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(_queue: string, fn: any, ...args: any[]) => {
|
||||
if (typeof fn !== 'function') {
|
||||
throw new Error(`fn is not a function in executeActivity. Queue: ${_queue}`)
|
||||
}
|
||||
return fn(...args)
|
||||
},
|
||||
)
|
||||
|
||||
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_worker_queue')
|
||||
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_worker_queue')
|
||||
mockActivities.downloadMediaToTmpActivity.mockResolvedValue({
|
||||
filePath: '/tmp/test.mp4',
|
||||
tmpDir: '/tmp',
|
||||
})
|
||||
})
|
||||
|
||||
it('should process AI autofill successfully', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-1',
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.ai_metadata_autofill,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: {},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-1-uid',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-1',
|
||||
storageKey: { key: 'test.mp4' },
|
||||
mediaType: 'video/mp4',
|
||||
project: { id: 'proj-1', teamId: 'team-1' },
|
||||
})
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'placeholder-1' })
|
||||
mockActivities.extractAiMetadataActivity.mockResolvedValue(['frame1.webp'])
|
||||
mockActivities.getProjectAutofillFieldsActivity.mockResolvedValue([
|
||||
{ id: 'field-1', config: { type: 'text', name: 'Field 1' } },
|
||||
])
|
||||
mockActivities.autofillAiActivity.mockResolvedValue({
|
||||
text: JSON.stringify({ 'field-1': 'Extracted Value' }),
|
||||
usage: { inputTokens: 10, outputTokens: 5, model: 'gpt-4v' },
|
||||
})
|
||||
|
||||
await aiAutofillMedia(task)
|
||||
|
||||
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-1',
|
||||
message: '__AUTOFILL__',
|
||||
sessionId: 'task-1',
|
||||
agentId: 'default',
|
||||
})
|
||||
|
||||
expect(mockActivities.updateAssetMetadataActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-1',
|
||||
metadata: [{ key: 'field-1', value: 'Extracted Value' }],
|
||||
})
|
||||
})
|
||||
|
||||
it('should use agentId from payload if provided', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-1',
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.ai_metadata_autofill,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: { agentId: 'real-agent-id' },
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-1-uid',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-1',
|
||||
storageKey: { key: 'test.mp4' },
|
||||
mediaType: 'video/mp4',
|
||||
project: { id: 'proj-1', teamId: 'team-1' },
|
||||
})
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'placeholder-1' })
|
||||
mockActivities.extractAiMetadataActivity.mockResolvedValue(['frame1.webp'])
|
||||
mockActivities.getProjectAutofillFieldsActivity.mockResolvedValue([
|
||||
{ id: 'field-1', config: { type: 'text', name: 'Field 1' } },
|
||||
])
|
||||
mockActivities.autofillAiActivity.mockResolvedValue({
|
||||
text: JSON.stringify({ 'field-1': 'Extracted Value' }),
|
||||
usage: { inputTokens: 10, outputTokens: 5, model: 'gpt-4v' },
|
||||
})
|
||||
|
||||
await aiAutofillMedia(task)
|
||||
|
||||
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-1',
|
||||
message: '__AUTOFILL__',
|
||||
sessionId: 'task-1',
|
||||
agentId: 'real-agent-id',
|
||||
})
|
||||
})
|
||||
|
||||
it('should handle failures and update task status with error', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-fail',
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.ai_metadata_autofill,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: {},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-fail-uid',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'placeholder-err' })
|
||||
mockActivities.getAssetActivity.mockRejectedValue(new Error('Asset missing'))
|
||||
|
||||
await expect(aiAutofillMedia(task)).rejects.toThrow('Asset missing')
|
||||
|
||||
expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({
|
||||
commentId: 'placeholder-err',
|
||||
message: expect.stringContaining('failed'),
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-fail',
|
||||
status: WorkflowTaskStatus.failed,
|
||||
output: { error: 'Asset missing' },
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,327 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { aiChat } from './ai-chat'
|
||||
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@/generated/prisma/client'
|
||||
import * as workflowUtils from '@/workflow/workflow-utils'
|
||||
|
||||
vi.mock('@/workflow/workflow-utils', async (importOriginal) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const actual = (await importOriginal()) as any
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
sleep: vi.fn().mockResolvedValue(undefined),
|
||||
}
|
||||
})
|
||||
|
||||
describe('AIChat Workflow', () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
||||
getCommentActivity: Object.assign(vi.fn(), { _activityName: 'getCommentActivity' }),
|
||||
extractAiMetadataActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'extractAiMetadataActivity',
|
||||
}),
|
||||
aiChatActivity: Object.assign(vi.fn(), { _activityName: 'aiChatActivity' }),
|
||||
createCommentActivity: Object.assign(vi.fn(), { _activityName: 'createCommentActivity' }),
|
||||
updateCommentActivity: Object.assign(vi.fn(), { _activityName: 'updateCommentActivity' }),
|
||||
updateTaskUsageActivity: Object.assign(vi.fn(), { _activityName: 'updateTaskUsageActivity' }),
|
||||
getAgentWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAgentWorkerQueueActivity',
|
||||
}),
|
||||
deleteCommentActivity: Object.assign(vi.fn(), { _activityName: 'deleteCommentActivity' }),
|
||||
initializeAgentSessionActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'initializeAgentSessionActivity',
|
||||
}),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.getActivities as any).mockReturnValue(mockActivities)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.executeActivity as any).mockImplementation(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(_queue: string, fn: any, ...args: any[]) => {
|
||||
if (typeof fn !== 'function') {
|
||||
throw new Error(`fn is not a function in executeActivity. Queue: ${_queue}`)
|
||||
}
|
||||
return fn(...args)
|
||||
},
|
||||
)
|
||||
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_worker_queue')
|
||||
mockActivities.initializeAgentSessionActivity.mockResolvedValue('mock-session-id')
|
||||
})
|
||||
|
||||
it('should process AI chat successfully', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-1',
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.chat,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: {
|
||||
userCommentId: 'comment-1',
|
||||
agentId: 'bot-1',
|
||||
projectId: 'proj-1',
|
||||
},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-1',
|
||||
key: 'test.png',
|
||||
mediaType: 'image/png',
|
||||
project: { teamId: 'team-1', id: 'proj-1' },
|
||||
})
|
||||
|
||||
mockActivities.getCommentActivity.mockResolvedValue({
|
||||
id: 'comment-1',
|
||||
message: 'Hello AI',
|
||||
})
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({
|
||||
id: 'placeholder-1',
|
||||
})
|
||||
|
||||
mockActivities.aiChatActivity.mockResolvedValue({
|
||||
text: 'Hello Human',
|
||||
usage: { inputTokens: 10, outputTokens: 20, model: 'gpt-4' },
|
||||
})
|
||||
|
||||
await aiChat(task)
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-1',
|
||||
status: WorkflowTaskStatus.processing,
|
||||
})
|
||||
|
||||
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-1',
|
||||
message: '__CHAT__',
|
||||
sessionId: 'pending',
|
||||
agentId: 'bot-1',
|
||||
replyToId: 'comment-1',
|
||||
})
|
||||
|
||||
expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({
|
||||
commentId: 'placeholder-1',
|
||||
message: 'Hello Human',
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskUsageActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-1',
|
||||
inputTokens: 10,
|
||||
outputTokens: 20,
|
||||
model: 'gpt-4',
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-1',
|
||||
status: WorkflowTaskStatus.completed,
|
||||
output: { sessionId: undefined },
|
||||
})
|
||||
})
|
||||
|
||||
it('should attach AI response to thread root if triggering comment is a reply', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-nested',
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.chat,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: {
|
||||
userCommentId: 'reply-1',
|
||||
agentId: 'bot-1',
|
||||
},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid-nested',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-1',
|
||||
project: { teamId: 'team-1', id: 'proj-1' },
|
||||
})
|
||||
|
||||
mockActivities.getCommentActivity.mockResolvedValue({
|
||||
id: 'reply-1',
|
||||
replyToId: 'root-comment-id',
|
||||
message: 'Nested reply message',
|
||||
})
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'placeholder-nested' })
|
||||
|
||||
mockActivities.aiChatActivity.mockResolvedValue({
|
||||
text: 'AI response to root',
|
||||
})
|
||||
|
||||
await aiChat(task)
|
||||
|
||||
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-1',
|
||||
message: '__CHAT__',
|
||||
sessionId: 'pending',
|
||||
agentId: 'bot-1',
|
||||
replyToId: 'root-comment-id', // MUST be root, not reply-1
|
||||
})
|
||||
})
|
||||
|
||||
it('should handle failures and update placeholder with error', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-fail',
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.chat,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: {
|
||||
userCommentId: 'comment-1',
|
||||
agentId: 'bot-1',
|
||||
},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({
|
||||
id: 'placeholder-err',
|
||||
})
|
||||
|
||||
mockActivities.getAssetActivity.mockRejectedValue(new Error('DB Down'))
|
||||
|
||||
await expect(aiChat(task)).rejects.toThrow('DB Down')
|
||||
|
||||
expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({
|
||||
commentId: 'placeholder-err',
|
||||
message: expect.stringContaining('error'),
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-fail',
|
||||
status: WorkflowTaskStatus.failed,
|
||||
output: { error: 'DB Down' },
|
||||
})
|
||||
})
|
||||
|
||||
it('should pass explicitMention payload parameter and format instruction when true', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-explicit',
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.chat,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: {
|
||||
userCommentId: 'comment-1',
|
||||
agentId: 'bot-1',
|
||||
explicitMention: true,
|
||||
},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid-explicit',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-1',
|
||||
project: { teamId: 'team-1', id: 'proj-1' },
|
||||
})
|
||||
|
||||
mockActivities.getCommentActivity.mockResolvedValue({
|
||||
id: 'comment-1',
|
||||
message: 'Hello AI',
|
||||
})
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({
|
||||
id: 'placeholder-1',
|
||||
})
|
||||
|
||||
mockActivities.aiChatActivity.mockResolvedValue({
|
||||
text: 'Hello Human',
|
||||
usage: { inputTokens: 5, outputTokens: 5, model: 'gpt-4' },
|
||||
})
|
||||
|
||||
await aiChat(task)
|
||||
|
||||
expect(mockActivities.aiChatActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
explicitMention: true,
|
||||
agentsInstruction: expect.stringContaining('MUST reply to this message'),
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('should delete placeholder comment when AI response is __NO_REPLY__', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-no-reply',
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.chat,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: {
|
||||
userCommentId: 'comment-1',
|
||||
agentId: 'bot-1',
|
||||
explicitMention: false,
|
||||
},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid-no-reply',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-1',
|
||||
project: { teamId: 'team-1', id: 'proj-1' },
|
||||
})
|
||||
|
||||
mockActivities.getCommentActivity.mockResolvedValue({
|
||||
id: 'comment-1',
|
||||
message: 'Hello AI',
|
||||
})
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({
|
||||
id: 'placeholder-delete-me',
|
||||
})
|
||||
|
||||
mockActivities.aiChatActivity.mockResolvedValue({
|
||||
text: ' __NO_REPLY__ ',
|
||||
usage: { inputTokens: 5, outputTokens: 5, model: 'gpt-4' },
|
||||
})
|
||||
|
||||
await aiChat(task)
|
||||
|
||||
expect(mockActivities.deleteCommentActivity).toHaveBeenCalledWith('placeholder-delete-me')
|
||||
expect(mockActivities.updateCommentActivity).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,179 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { aiEmbeddingMedia } from './ai-embedding'
|
||||
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@/generated/prisma/client'
|
||||
import * as workflowUtils from '../workflow-utils'
|
||||
|
||||
vi.mock('../workflow-utils', async (importOriginal) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const actual = (await importOriginal()) as any
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
sleep: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
describe('AIEmbedding Workflow', () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
generateEmbeddingActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'generateEmbeddingActivity',
|
||||
}),
|
||||
updateTaskUsageActivity: Object.assign(vi.fn(), { _activityName: 'updateTaskUsageActivity' }),
|
||||
createCommentActivity: Object.assign(vi.fn(), { _activityName: 'createCommentActivity' }),
|
||||
updateCommentActivity: Object.assign(vi.fn(), { _activityName: 'updateCommentActivity' }),
|
||||
getAgentWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAgentWorkerQueueActivity',
|
||||
}),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.getActivities as any).mockReturnValue(mockActivities)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.executeActivity as any).mockImplementation(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(_queue: string, fn: any, ...args: any[]) => {
|
||||
if (typeof fn !== 'function') {
|
||||
throw new Error(`fn is not a function in executeActivity. Queue: ${_queue}`)
|
||||
}
|
||||
return fn(...args)
|
||||
},
|
||||
)
|
||||
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_worker_queue')
|
||||
})
|
||||
|
||||
it('should generate embeddings successfully', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-1',
|
||||
assetId: 'asset-1',
|
||||
teamId: 'team-1',
|
||||
type: WorkflowTaskType.ai_embedding,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: {},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'placeholder-1' })
|
||||
mockActivities.generateEmbeddingActivity.mockResolvedValue({
|
||||
inputTokens: 5,
|
||||
outputTokens: 5,
|
||||
model: 'clip',
|
||||
})
|
||||
|
||||
await aiEmbeddingMedia(task)
|
||||
|
||||
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-1',
|
||||
message: '__EMBEDDING__',
|
||||
sessionId: 'task-1',
|
||||
agentId: 'default',
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-1',
|
||||
status: WorkflowTaskStatus.processing,
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskUsageActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-1',
|
||||
inputTokens: 5,
|
||||
outputTokens: 5,
|
||||
model: 'clip',
|
||||
})
|
||||
|
||||
expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({
|
||||
commentId: 'placeholder-1',
|
||||
message: expect.stringContaining('successfully'),
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-1',
|
||||
status: WorkflowTaskStatus.completed,
|
||||
})
|
||||
})
|
||||
|
||||
it('should use agentId from payload if provided', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-1',
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.ai_embedding,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
teamId: 'team-1',
|
||||
output: null,
|
||||
payload: { agentId: 'real-agent-id' },
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'placeholder-1' })
|
||||
mockActivities.generateEmbeddingActivity.mockResolvedValue({
|
||||
inputTokens: 5,
|
||||
outputTokens: 5,
|
||||
model: 'clip',
|
||||
})
|
||||
|
||||
await aiEmbeddingMedia(task)
|
||||
|
||||
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-1',
|
||||
message: '__EMBEDDING__',
|
||||
sessionId: 'task-1',
|
||||
agentId: 'real-agent-id',
|
||||
})
|
||||
})
|
||||
|
||||
it('should handle failures and update task status with error', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-fail',
|
||||
assetId: 'asset-1',
|
||||
teamId: 'team-1',
|
||||
type: WorkflowTaskType.ai_embedding,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: {},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'placeholder-err' })
|
||||
mockActivities.generateEmbeddingActivity.mockRejectedValue(new Error('Embedding error'))
|
||||
|
||||
await expect(aiEmbeddingMedia(task)).rejects.toThrow('Embedding error')
|
||||
|
||||
expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({
|
||||
commentId: 'placeholder-err',
|
||||
message: expect.stringContaining('failed'),
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-fail',
|
||||
status: WorkflowTaskStatus.failed,
|
||||
output: { error: 'Embedding error' },
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,5 +1,5 @@
|
||||
export * from './ai-transcription'
|
||||
export * from './ai-embedding'
|
||||
export * from './ai-autofill'
|
||||
export * from './ai-chat'
|
||||
export * from './agent-embedding'
|
||||
export * from './agent-autofill'
|
||||
export * from './agent-chat'
|
||||
export * from '@/transcode/workflows/transcode'
|
||||
|
||||
Reference in New Issue
Block a user