refactor(workflow): split database and agent activities for strict database isolation

This commit is contained in:
yiling
2026-05-27 23:40:14 +08:00
parent 4ded573fde
commit 911e369782
24 changed files with 1146 additions and 1765 deletions
+1 -280
View File
@@ -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)
})
})
})
-219
View File
@@ -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 },
-97
View File
@@ -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()
})
})
-242
View File
@@ -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()