mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-03 14:34:40 +00:00
refactor(agent): decouple agent orchestration and relocate workflows
Decoupled high-level agent orchestration (chat, chatWithAgent, autofill) from sandbox execution in `src/agent` to `src/services/agent/agent.ts`. Relocated all related workflows and activities to `src/workflow`.
This commit is contained in:
@@ -1,250 +0,0 @@
|
|||||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
|
||||||
import { prisma } from '@/db'
|
|
||||||
import { setupTestDbHooks } from '@/db-test-hooks'
|
|
||||||
import { agentExecutor, type AutofillField } from './executor'
|
|
||||||
import * as piAgent from '@mariozechner/pi-coding-agent'
|
|
||||||
|
|
||||||
vi.mock('@mariozechner/pi-coding-agent', async () => {
|
|
||||||
const actual = await vi.importActual('@mariozechner/pi-coding-agent')
|
|
||||||
return {
|
|
||||||
...actual,
|
|
||||||
createAgentSession: vi.fn(),
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
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('AgentExecutor', () => {
|
|
||||||
setupTestDbHooks()
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
vi.clearAllMocks()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('autofills with agent', async () => {
|
|
||||||
const team = await prisma.team.create({
|
|
||||||
data: {
|
|
||||||
name: 'Autofill Team',
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const provider = await prisma.provider.create({
|
|
||||||
data: {
|
|
||||||
name: 'openai',
|
|
||||||
teamId: team.id,
|
|
||||||
config: mockProviderConfig,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const model = await prisma.model.create({
|
|
||||||
data: {
|
|
||||||
modelId: 'gpt-4',
|
|
||||||
name: 'GPT-4',
|
|
||||||
providerId: provider.id,
|
|
||||||
config: mockModelConfig,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
await prisma.user.create({
|
|
||||||
data: {
|
|
||||||
name: 'Autofiller',
|
|
||||||
email: `autofiller-${Date.now()}@shumai.ai`,
|
|
||||||
type: 'agent',
|
|
||||||
agent: {
|
|
||||||
create: {
|
|
||||||
type: 'autofill',
|
|
||||||
enabled: true,
|
|
||||||
providerId: provider.id,
|
|
||||||
modelId: model.id,
|
|
||||||
config: {
|
|
||||||
provider: 'openai',
|
|
||||||
model: 'gpt-4',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
teamMembers: {
|
|
||||||
create: {
|
|
||||||
teamId: team.id,
|
|
||||||
role: 'reviewer',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const mockSession = {
|
|
||||||
sendUserMessage: vi.fn().mockImplementation(async () => {
|
|
||||||
// Find the tool in the session's customTools and call its execute
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
const tool = (mockSession as any).customTools.find(
|
|
||||||
(t: unknown) => (t as { name: string }).name === 'autofill_metadata',
|
|
||||||
)
|
|
||||||
if (tool) {
|
|
||||||
await tool.execute('call_1', { data: 1 })
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
getSessionStats: vi.fn().mockReturnValue({ tokens: { input: 5, output: 5 } }),
|
|
||||||
getLastAssistantText: vi.fn().mockReturnValue('{"data": 1}'),
|
|
||||||
state: { tools: [], systemPrompt: '', messages: [] },
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
customTools: [] as any[],
|
|
||||||
}
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
;(piAgent.createAgentSession as any).mockImplementation(async (config: any) => {
|
|
||||||
mockSession.customTools = config.customTools
|
|
||||||
return { session: mockSession }
|
|
||||||
})
|
|
||||||
|
|
||||||
const fields: AutofillField[] = [{ id: 'f1', config: { name: 'Field 1', type: 'text' } }]
|
|
||||||
const resp = await agentExecutor.autofill(team.id, 'extract data', [], fields)
|
|
||||||
expect(resp.text).toBe('{"data":1}')
|
|
||||||
expect(resp.usage.inputTokens).toBe(5)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('chats with bot', async () => {
|
|
||||||
const team = await prisma.team.create({
|
|
||||||
data: {
|
|
||||||
name: 'Chat Bot Team',
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const provider = await prisma.provider.create({
|
|
||||||
data: {
|
|
||||||
name: 'google',
|
|
||||||
teamId: team.id,
|
|
||||||
config: mockProviderConfig,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const model = await prisma.model.create({
|
|
||||||
data: {
|
|
||||||
modelId: 'gemini',
|
|
||||||
name: 'Gemini',
|
|
||||||
providerId: provider.id,
|
|
||||||
config: mockModelConfig,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
await prisma.user.create({
|
|
||||||
data: {
|
|
||||||
name: 'Chatter',
|
|
||||||
email: `chatter-${Date.now()}@shumai.ai`,
|
|
||||||
type: 'agent',
|
|
||||||
agent: {
|
|
||||||
create: {
|
|
||||||
type: 'chat',
|
|
||||||
enabled: true,
|
|
||||||
providerId: provider.id,
|
|
||||||
modelId: model.id,
|
|
||||||
config: {
|
|
||||||
provider: 'google',
|
|
||||||
model: 'gemini',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
teamMembers: {
|
|
||||||
create: {
|
|
||||||
teamId: team.id,
|
|
||||||
role: 'reviewer',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const mockSession = {
|
|
||||||
sendUserMessage: vi.fn().mockResolvedValue(undefined),
|
|
||||||
getSessionStats: vi.fn().mockReturnValue({ tokens: { input: 5, output: 5 } }),
|
|
||||||
getLastAssistantText: vi.fn().mockReturnValue('mock text'),
|
|
||||||
state: { tools: [], systemPrompt: '', messages: [] },
|
|
||||||
}
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
;(piAgent.createAgentSession as any).mockResolvedValue({ session: mockSession })
|
|
||||||
|
|
||||||
const resp = await agentExecutor.chat(team.id, 'hello')
|
|
||||||
expect(resp.text).toBe('mock text')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('chat with instruction', async () => {
|
|
||||||
const team = await prisma.team.create({
|
|
||||||
data: {
|
|
||||||
name: 'Pirate Team',
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const provider = await prisma.provider.create({
|
|
||||||
data: {
|
|
||||||
name: 'google',
|
|
||||||
teamId: team.id,
|
|
||||||
config: mockProviderConfig,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const model = await prisma.model.create({
|
|
||||||
data: {
|
|
||||||
modelId: 'gemini-pro',
|
|
||||||
name: 'Gemini Pro',
|
|
||||||
providerId: provider.id,
|
|
||||||
config: mockModelConfig,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const botUser = await prisma.user.create({
|
|
||||||
data: { name: 'Pirate', email: 'pirate@shumai.ai', type: 'agent' },
|
|
||||||
})
|
|
||||||
|
|
||||||
const agent = await prisma.agent.create({
|
|
||||||
data: {
|
|
||||||
id: botUser.id,
|
|
||||||
type: 'chat',
|
|
||||||
enabled: true,
|
|
||||||
providerId: provider.id,
|
|
||||||
modelId: model.id,
|
|
||||||
soul: 'You are a pirate',
|
|
||||||
config: {
|
|
||||||
provider: 'google',
|
|
||||||
model: 'gemini-pro',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
await prisma.teamMember.create({
|
|
||||||
data: { teamId: team.id, userId: botUser.id, role: 'reviewer' },
|
|
||||||
})
|
|
||||||
|
|
||||||
const mockSession = {
|
|
||||||
sendUserMessage: vi.fn().mockResolvedValue(undefined),
|
|
||||||
getSessionStats: vi.fn().mockReturnValue({ tokens: { input: 10, output: 20 } }),
|
|
||||||
getLastAssistantText: vi.fn().mockReturnValue('Arr matey!'),
|
|
||||||
state: { tools: [], systemPrompt: '', messages: [] },
|
|
||||||
}
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
;(piAgent.createAgentSession as any).mockResolvedValue({ session: mockSession })
|
|
||||||
|
|
||||||
const resp = await agentExecutor.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)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
@@ -1,366 +0,0 @@
|
|||||||
import { prisma } from '@/db'
|
|
||||||
import { logger } from '@/logger'
|
|
||||||
import { Usage } from '@/services/ai/provider/provider'
|
|
||||||
import { s3Service } from '@/services/s3/s3'
|
|
||||||
import { SandboxManager } from '@anthropic-ai/sandbox-runtime'
|
|
||||||
import { getModel, type ImageContent, type TextContent } from '@mariozechner/pi-ai'
|
|
||||||
import {
|
|
||||||
AuthStorage,
|
|
||||||
createAgentSession,
|
|
||||||
DefaultResourceLoader,
|
|
||||||
defineTool,
|
|
||||||
ModelRegistry,
|
|
||||||
SessionManager,
|
|
||||||
SettingsManager,
|
|
||||||
type ToolDefinition,
|
|
||||||
} from '@mariozechner/pi-coding-agent'
|
|
||||||
import { Type, type TSchema } from '@sinclair/typebox'
|
|
||||||
import * as fs from 'fs'
|
|
||||||
import * as path from 'path'
|
|
||||||
import { DatabaseSessionManager } from './database-session-manager'
|
|
||||||
import { analyzeAssetMediaTool } from './tools/analyze-asset-media'
|
|
||||||
import { createReadSkillTool } from './tools/read-skill'
|
|
||||||
import { createSandboxedBashTool } from './tools/sandboxed-bash'
|
|
||||||
|
|
||||||
export interface AutofillField {
|
|
||||||
id: string
|
|
||||||
config: PrismaJson.FieldConfig
|
|
||||||
description?: string | null
|
|
||||||
}
|
|
||||||
|
|
||||||
export class AgentExecutor {
|
|
||||||
constructor(private readonly prismaClient: typeof prisma = prisma) {}
|
|
||||||
|
|
||||||
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,
|
|
||||||
user: {
|
|
||||||
teamMembers: {
|
|
||||||
some: { 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: ToolDefinition[] = [],
|
|
||||||
): 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
|
|
||||||
|
|
||||||
const agentDir = path.join(process.cwd(), '.pi', 'agents', agent.id)
|
|
||||||
if (!fs.existsSync(agentDir)) fs.mkdirSync(agentDir, { recursive: true })
|
|
||||||
|
|
||||||
const authStorage = AuthStorage.create(path.join(agentDir, 'auth.json'))
|
|
||||||
const modelRegistry = ModelRegistry.create(authStorage)
|
|
||||||
modelRegistry.getAll()
|
|
||||||
|
|
||||||
// Fetch and register the required provider from database
|
|
||||||
const dbProviders = await this.prismaClient.provider.findMany({
|
|
||||||
where: { teamId, name: providerName },
|
|
||||||
include: { models: true },
|
|
||||||
})
|
|
||||||
for (const p of dbProviders) {
|
|
||||||
// Ensure each model has a name (fallback to ID) to satisfy registerProvider's strict requirement
|
|
||||||
const config = {
|
|
||||||
...p.config,
|
|
||||||
models: p.models.map((m) => ({
|
|
||||||
...m.config,
|
|
||||||
id: m.modelId,
|
|
||||||
name: m.name || m.modelId,
|
|
||||||
})),
|
|
||||||
}
|
|
||||||
modelRegistry.registerProvider(p.name, config)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Setup credentials
|
|
||||||
const dbProvider = dbProviders[0]
|
|
||||||
if (dbProvider?.config.apiKey) {
|
|
||||||
authStorage.set(providerName, { type: 'api_key', key: dbProvider.config.apiKey })
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fetch team skills
|
|
||||||
const teamSkills = await this.prismaClient.skill.findMany({
|
|
||||||
where: { teamId },
|
|
||||||
})
|
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
const model = (getModel as any)(providerName, modelId)
|
|
||||||
|
|
||||||
const settingsManager = SettingsManager.create(process.cwd(), agentDir)
|
|
||||||
const resourceLoader = new DefaultResourceLoader({
|
|
||||||
cwd: process.cwd(),
|
|
||||||
agentDir,
|
|
||||||
settingsManager,
|
|
||||||
systemPromptOverride: () => {
|
|
||||||
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(', ')}.`
|
|
||||||
}
|
|
||||||
|
|
||||||
if (teamSkills.length > 0) {
|
|
||||||
systemPrompt += '\n\nAvailable Skills:\n'
|
|
||||||
for (const s of teamSkills) {
|
|
||||||
systemPrompt += `- ${s.name} (ID: ${s.id}): ${s.description || 'No description'}\n`
|
|
||||||
}
|
|
||||||
systemPrompt +=
|
|
||||||
'\nTo use a skill, first use the "read_skill" tool with the skill ID to read its instructions.'
|
|
||||||
}
|
|
||||||
|
|
||||||
return systemPrompt
|
|
||||||
},
|
|
||||||
noContextFiles: true,
|
|
||||||
})
|
|
||||||
await resourceLoader.reload()
|
|
||||||
const sessionManager = await DatabaseSessionManager.create({
|
|
||||||
agentId,
|
|
||||||
userId,
|
|
||||||
sessionId,
|
|
||||||
cwd: process.cwd(),
|
|
||||||
})
|
|
||||||
|
|
||||||
const sandbox = await this.getSandbox(teamId)
|
|
||||||
const allowedDomains = sandbox?.allowedDomains || []
|
|
||||||
|
|
||||||
const piDir = path.join(process.cwd(), '.pi')
|
|
||||||
if (!fs.existsSync(piDir)) fs.mkdirSync(piDir, { recursive: true })
|
|
||||||
|
|
||||||
const allowWrite = [piDir, '/tmp']
|
|
||||||
|
|
||||||
// NOTE: SandboxManager.initialize is a global operation that applies to the entire process.
|
|
||||||
// anthropic-experimental/sandbox-runtime currently does not support separate managers per session/team.
|
|
||||||
// Since this application is not designed for multi-tenancy at the process level (i.e. only one
|
|
||||||
// team's chat happens at a time per worker instance), re-initializing here with current team's
|
|
||||||
// settings is acceptable.
|
|
||||||
await SandboxManager.initialize({
|
|
||||||
network: {
|
|
||||||
allowedDomains,
|
|
||||||
deniedDomains: [],
|
|
||||||
},
|
|
||||||
filesystem: {
|
|
||||||
allowWrite,
|
|
||||||
denyWrite: ['.env', '.env.*', '*.pem', '*.key'],
|
|
||||||
denyRead: ['~/.ssh', '~/.aws', '~/.gnupg'],
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const sandboxedBash = createSandboxedBashTool(process.cwd(), sessionManager)
|
|
||||||
|
|
||||||
const { session } = await createAgentSession({
|
|
||||||
cwd: process.cwd(),
|
|
||||||
agentDir,
|
|
||||||
authStorage,
|
|
||||||
modelRegistry,
|
|
||||||
model,
|
|
||||||
resourceLoader,
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
sessionManager: sessionManager as any as SessionManager,
|
|
||||||
customTools: [
|
|
||||||
analyzeAssetMediaTool,
|
|
||||||
createReadSkillTool(sessionManager),
|
|
||||||
sandboxedBash,
|
|
||||||
...tools,
|
|
||||||
],
|
|
||||||
})
|
|
||||||
const content: (TextContent | ImageContent)[] = []
|
|
||||||
|
|
||||||
if (agentsInstruction) {
|
|
||||||
session.state.systemPrompt = `${session.state.systemPrompt}\n\nContext and Instructions:\n${agentsInstruction}`
|
|
||||||
}
|
|
||||||
content.push({ type: 'text', text: prompt })
|
|
||||||
|
|
||||||
if (images && images.length > 0) {
|
|
||||||
for (const key of images) {
|
|
||||||
const { buffer, contentType } = await s3Service.getObject(
|
|
||||||
process.env.S3_BUCKET || 'shumai',
|
|
||||||
key,
|
|
||||||
)
|
|
||||||
content.push({
|
|
||||||
type: 'image',
|
|
||||||
data: buffer.toString('base64'),
|
|
||||||
mimeType: contentType,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
await session.sendUserMessage(content)
|
|
||||||
|
|
||||||
session.state.messages.forEach((msg) => {
|
|
||||||
if (msg.role === 'toolResult') {
|
|
||||||
// For tool results, log details (metadata) instead of content (which may have large images)
|
|
||||||
const logMsg = { ...msg, content: undefined }
|
|
||||||
logger.debug(logMsg, 'agent message')
|
|
||||||
} else {
|
|
||||||
logger.debug(msg, 'agent message')
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
const stats = session.getSessionStats()
|
|
||||||
const text = session.getLastAssistantText() || ''
|
|
||||||
|
|
||||||
if (!text) {
|
|
||||||
const lastMessage = session.messages[session.messages.length - 1]
|
|
||||||
if (lastMessage && lastMessage.role === 'assistant' && lastMessage.errorMessage) {
|
|
||||||
throw new Error(`AI error: ${lastMessage.errorMessage}`)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const usage: Usage = {
|
|
||||||
model: modelId,
|
|
||||||
inputTokens: stats.tokens.input || 0,
|
|
||||||
outputTokens: stats.tokens.output || 0,
|
|
||||||
}
|
|
||||||
|
|
||||||
await sessionManager.waitForSync()
|
|
||||||
|
|
||||||
return { text, usage, sessionId: sessionManager.getDbSessionId() }
|
|
||||||
} finally {
|
|
||||||
// Cleanup handled by agent session if needed
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async autofill(
|
|
||||||
teamId: string,
|
|
||||||
prompt: string,
|
|
||||||
images: string[],
|
|
||||||
fields: AutofillField[],
|
|
||||||
): Promise<{ text: string; usage: Usage }> {
|
|
||||||
const agent = await this.prismaClient.agent.findFirst({
|
|
||||||
where: {
|
|
||||||
type: 'autofill',
|
|
||||||
enabled: true,
|
|
||||||
user: {
|
|
||||||
teamMembers: {
|
|
||||||
some: { 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 = defineTool({
|
|
||||||
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 } = await this.chatWithAgent(
|
|
||||||
teamId,
|
|
||||||
agent.id,
|
|
||||||
fullPrompt,
|
|
||||||
images,
|
|
||||||
'',
|
|
||||||
undefined,
|
|
||||||
undefined,
|
|
||||||
[autofillTool],
|
|
||||||
)
|
|
||||||
|
|
||||||
return {
|
|
||||||
text: capturedData ? JSON.stringify(capturedData) : '{}',
|
|
||||||
usage,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export const agentExecutor = new AgentExecutor()
|
|
||||||
|
|
||||||
export function fieldsToTypeBoxSchema(fields: AutofillField[]) {
|
|
||||||
const properties: Record<string, TSchema> = {}
|
|
||||||
for (const f of fields) {
|
|
||||||
let schema: TSchema
|
|
||||||
switch (f.config.type) {
|
|
||||||
case 'text':
|
|
||||||
case 'longText':
|
|
||||||
schema = Type.String()
|
|
||||||
break
|
|
||||||
case 'number':
|
|
||||||
case 'rating':
|
|
||||||
schema = Type.Number()
|
|
||||||
break
|
|
||||||
case 'toggle':
|
|
||||||
schema = Type.Boolean()
|
|
||||||
break
|
|
||||||
case 'select':
|
|
||||||
schema = Type.String({
|
|
||||||
enum: f.config.select?.options?.map((o) => o.id) || [],
|
|
||||||
})
|
|
||||||
break
|
|
||||||
default:
|
|
||||||
schema = Type.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
if (f.description) {
|
|
||||||
schema.description = f.description
|
|
||||||
}
|
|
||||||
properties[f.id] = schema
|
|
||||||
}
|
|
||||||
|
|
||||||
return Type.Object(properties)
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,185 @@
|
|||||||
|
import { SandboxManager } from '@anthropic-ai/sandbox-runtime'
|
||||||
|
import { getModel } from '@mariozechner/pi-ai'
|
||||||
|
import {
|
||||||
|
AuthStorage,
|
||||||
|
createAgentSession as piCreateAgentSession,
|
||||||
|
DefaultResourceLoader,
|
||||||
|
ModelRegistry,
|
||||||
|
SessionManager,
|
||||||
|
SettingsManager,
|
||||||
|
type ToolDefinition,
|
||||||
|
} from '@mariozechner/pi-coding-agent'
|
||||||
|
import { Type, type TSchema } from '@sinclair/typebox'
|
||||||
|
import * as fs from 'fs'
|
||||||
|
import * as path from 'path'
|
||||||
|
import type { DatabaseSessionManager } from './database-session-manager'
|
||||||
|
import { analyzeAssetMediaTool } from './tools/analyze-asset-media'
|
||||||
|
import { createReadSkillTool } from './tools/read-skill'
|
||||||
|
import { createSandboxedBashTool } from './tools/sandboxed-bash'
|
||||||
|
|
||||||
|
export interface CreateAgentSessionParams {
|
||||||
|
agentId: string
|
||||||
|
providerName: string
|
||||||
|
modelId: string
|
||||||
|
apiKey?: string
|
||||||
|
systemPrompt: string
|
||||||
|
teamSkills: Array<{ id: string; name: string; description?: string | null }>
|
||||||
|
allowedDomains: string[]
|
||||||
|
sessionManager: DatabaseSessionManager
|
||||||
|
customTools?: ToolDefinition[]
|
||||||
|
providers: Array<{
|
||||||
|
name: string
|
||||||
|
config: Record<string, unknown>
|
||||||
|
models: Array<{
|
||||||
|
modelId: string
|
||||||
|
name: string | null
|
||||||
|
config: Record<string, unknown>
|
||||||
|
}>
|
||||||
|
}>
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||||
|
const {
|
||||||
|
agentId,
|
||||||
|
providerName,
|
||||||
|
modelId,
|
||||||
|
apiKey,
|
||||||
|
systemPrompt,
|
||||||
|
teamSkills,
|
||||||
|
allowedDomains,
|
||||||
|
sessionManager,
|
||||||
|
customTools = [],
|
||||||
|
providers,
|
||||||
|
} = params
|
||||||
|
|
||||||
|
const agentDir = path.join(process.cwd(), '.pi', 'agents', agentId)
|
||||||
|
if (!fs.existsSync(agentDir)) fs.mkdirSync(agentDir, { recursive: true })
|
||||||
|
|
||||||
|
const authStorage = AuthStorage.create(path.join(agentDir, 'auth.json'))
|
||||||
|
const modelRegistry = ModelRegistry.create(authStorage)
|
||||||
|
modelRegistry.getAll()
|
||||||
|
|
||||||
|
for (const p of providers) {
|
||||||
|
// Ensure each model has a name (fallback to ID) to satisfy registerProvider's strict requirement
|
||||||
|
const config = {
|
||||||
|
...p.config,
|
||||||
|
models: p.models.map((m) => ({
|
||||||
|
...m.config,
|
||||||
|
id: m.modelId,
|
||||||
|
name: m.name || m.modelId,
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
// We cast to any because the third-party library's ProviderConfigInput type expects highly specific properties
|
||||||
|
// like reasoning, input, and cost on each model config, which are stored dynamically in the database
|
||||||
|
// and loaded as arbitrary Record<string, unknown> JSON values.
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
modelRegistry.registerProvider(p.name, config as any)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (apiKey) {
|
||||||
|
authStorage.set(providerName, { type: 'api_key', key: apiKey })
|
||||||
|
}
|
||||||
|
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
const model = (getModel as any)(providerName, modelId)
|
||||||
|
|
||||||
|
const settingsManager = SettingsManager.create(process.cwd(), agentDir)
|
||||||
|
const resourceLoader = new DefaultResourceLoader({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
agentDir,
|
||||||
|
settingsManager,
|
||||||
|
systemPromptOverride: () => {
|
||||||
|
let prompt = systemPrompt
|
||||||
|
if (teamSkills.length > 0) {
|
||||||
|
prompt += '\n\nAvailable Skills:\n'
|
||||||
|
for (const s of teamSkills) {
|
||||||
|
prompt += `- ${s.name} (ID: ${s.id}): ${s.description || 'No description'}\n`
|
||||||
|
}
|
||||||
|
prompt +=
|
||||||
|
'\nTo use a skill, first use the "read_skill" tool with the skill ID to read its instructions.'
|
||||||
|
}
|
||||||
|
return prompt
|
||||||
|
},
|
||||||
|
noContextFiles: true,
|
||||||
|
})
|
||||||
|
await resourceLoader.reload()
|
||||||
|
|
||||||
|
const piDir = path.join(process.cwd(), '.pi')
|
||||||
|
if (!fs.existsSync(piDir)) fs.mkdirSync(piDir, { recursive: true })
|
||||||
|
|
||||||
|
const allowWrite = [piDir, '/tmp']
|
||||||
|
|
||||||
|
// SandboxManager.initialize is a global operation that applies to the entire process.
|
||||||
|
await SandboxManager.initialize({
|
||||||
|
network: {
|
||||||
|
allowedDomains,
|
||||||
|
deniedDomains: [],
|
||||||
|
},
|
||||||
|
filesystem: {
|
||||||
|
allowWrite,
|
||||||
|
denyWrite: ['.env', '.env.*', '*.pem', '*.key'],
|
||||||
|
denyRead: ['~/.ssh', '~/.aws', '~/.gnupg'],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const sandboxedBash = createSandboxedBashTool(process.cwd(), sessionManager)
|
||||||
|
|
||||||
|
const { session } = await piCreateAgentSession({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
agentDir,
|
||||||
|
authStorage,
|
||||||
|
modelRegistry,
|
||||||
|
model,
|
||||||
|
resourceLoader,
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
sessionManager: sessionManager as any as SessionManager,
|
||||||
|
customTools: [
|
||||||
|
analyzeAssetMediaTool,
|
||||||
|
createReadSkillTool(sessionManager),
|
||||||
|
sandboxedBash,
|
||||||
|
...customTools,
|
||||||
|
],
|
||||||
|
})
|
||||||
|
|
||||||
|
return session
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AutofillField {
|
||||||
|
id: string
|
||||||
|
config: PrismaJson.FieldConfig
|
||||||
|
description?: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function fieldsToTypeBoxSchema(fields: AutofillField[]) {
|
||||||
|
const properties: Record<string, TSchema> = {}
|
||||||
|
for (const f of fields) {
|
||||||
|
let schema: TSchema
|
||||||
|
switch (f.config.type) {
|
||||||
|
case 'text':
|
||||||
|
case 'longText':
|
||||||
|
schema = Type.String()
|
||||||
|
break
|
||||||
|
case 'number':
|
||||||
|
case 'rating':
|
||||||
|
schema = Type.Number()
|
||||||
|
break
|
||||||
|
case 'toggle':
|
||||||
|
schema = Type.Boolean()
|
||||||
|
break
|
||||||
|
case 'select':
|
||||||
|
schema = Type.String({
|
||||||
|
enum: f.config.select?.options?.map((o) => o.id) || [],
|
||||||
|
})
|
||||||
|
break
|
||||||
|
default:
|
||||||
|
schema = Type.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
if (f.description) {
|
||||||
|
schema.description = f.description
|
||||||
|
}
|
||||||
|
properties[f.id] = schema
|
||||||
|
}
|
||||||
|
|
||||||
|
return Type.Object(properties)
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { describe, it, expect } from 'vitest'
|
import { describe, it, expect } from 'vitest'
|
||||||
import { fieldsToTypeBoxSchema, type AutofillField } from './executor'
|
import { fieldsToTypeBoxSchema, type AutofillField } from './index'
|
||||||
|
|
||||||
describe('fieldsToTypeBoxSchema', () => {
|
describe('fieldsToTypeBoxSchema', () => {
|
||||||
it('converts text fields', () => {
|
it('converts text fields', () => {
|
||||||
|
|||||||
@@ -1,7 +1,17 @@
|
|||||||
import { describe, expect, test } from 'vitest'
|
import { describe, expect, test, vi, beforeEach } from 'vitest'
|
||||||
import { AgentService } from './agent'
|
import { AgentService } from './agent'
|
||||||
import { prisma } from '@/db'
|
import { prisma } from '@/db'
|
||||||
import { setupTestDbHooks } from '@/db-test-hooks'
|
import { setupTestDbHooks } from '@/db-test-hooks'
|
||||||
|
import * as piAgent from '@mariozechner/pi-coding-agent'
|
||||||
|
import { type AutofillField } from '@/agent'
|
||||||
|
|
||||||
|
vi.mock('@mariozechner/pi-coding-agent', async () => {
|
||||||
|
const actual = await vi.importActual('@mariozechner/pi-coding-agent')
|
||||||
|
return {
|
||||||
|
...actual,
|
||||||
|
createAgentSession: vi.fn(),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
describe('AgentService', () => {
|
describe('AgentService', () => {
|
||||||
setupTestDbHooks()
|
setupTestDbHooks()
|
||||||
@@ -219,4 +229,241 @@ describe('AgentService', () => {
|
|||||||
expect(agents[0].modelRef).toBeDefined()
|
expect(agents[0].modelRef).toBeDefined()
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('agent execution', () => {
|
||||||
|
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,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('autofills with agent', 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: 'openai',
|
||||||
|
teamId: team.id,
|
||||||
|
config: mockProviderConfig,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const model = await db.model.create({
|
||||||
|
data: {
|
||||||
|
modelId: 'gpt-4',
|
||||||
|
name: 'GPT-4',
|
||||||
|
providerId: provider.id,
|
||||||
|
config: mockModelConfig,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
await db.user.create({
|
||||||
|
data: {
|
||||||
|
name: 'Autofiller',
|
||||||
|
email: `autofiller-${Date.now()}@shumai.ai`,
|
||||||
|
type: 'agent',
|
||||||
|
agent: {
|
||||||
|
create: {
|
||||||
|
type: 'autofill',
|
||||||
|
enabled: true,
|
||||||
|
providerId: provider.id,
|
||||||
|
modelId: model.id,
|
||||||
|
config: {
|
||||||
|
provider: 'openai',
|
||||||
|
model: 'gpt-4',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
teamMembers: {
|
||||||
|
create: {
|
||||||
|
teamId: team.id,
|
||||||
|
role: 'reviewer',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const mockSession = {
|
||||||
|
sendUserMessage: vi.fn().mockImplementation(async () => {
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
const tool = (mockSession as any).customTools.find(
|
||||||
|
(t: unknown) => (t as { name: string }).name === 'autofill_metadata',
|
||||||
|
)
|
||||||
|
if (tool) {
|
||||||
|
await tool.execute('call_1', { data: 1 })
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
getSessionStats: vi.fn().mockReturnValue({ tokens: { input: 5, output: 5 } }),
|
||||||
|
getLastAssistantText: vi.fn().mockReturnValue('{"data": 1}'),
|
||||||
|
state: { tools: [], systemPrompt: '', messages: [] },
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
customTools: [] as any[],
|
||||||
|
}
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
;(piAgent.createAgentSession as any).mockImplementation(async (config: any) => {
|
||||||
|
mockSession.customTools = config.customTools
|
||||||
|
return { session: mockSession }
|
||||||
|
})
|
||||||
|
|
||||||
|
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('{"data":1}')
|
||||||
|
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: mockProviderConfig,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const model = await db.model.create({
|
||||||
|
data: {
|
||||||
|
modelId: 'gemini',
|
||||||
|
name: 'Gemini',
|
||||||
|
providerId: provider.id,
|
||||||
|
config: mockModelConfig,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
await db.user.create({
|
||||||
|
data: {
|
||||||
|
name: 'Chatter',
|
||||||
|
email: `chatter-${Date.now()}@shumai.ai`,
|
||||||
|
type: 'agent',
|
||||||
|
agent: {
|
||||||
|
create: {
|
||||||
|
type: 'chat',
|
||||||
|
enabled: true,
|
||||||
|
providerId: provider.id,
|
||||||
|
modelId: model.id,
|
||||||
|
config: {
|
||||||
|
provider: 'google',
|
||||||
|
model: 'gemini',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
teamMembers: {
|
||||||
|
create: {
|
||||||
|
teamId: team.id,
|
||||||
|
role: 'reviewer',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const mockSession = {
|
||||||
|
sendUserMessage: vi.fn().mockResolvedValue(undefined),
|
||||||
|
getSessionStats: vi.fn().mockReturnValue({ tokens: { input: 5, output: 5 } }),
|
||||||
|
getLastAssistantText: vi.fn().mockReturnValue('mock text'),
|
||||||
|
state: { tools: [], systemPrompt: '', messages: [] },
|
||||||
|
}
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
;(piAgent.createAgentSession as any).mockResolvedValue({ session: mockSession })
|
||||||
|
|
||||||
|
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: mockProviderConfig,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const model = await db.model.create({
|
||||||
|
data: {
|
||||||
|
modelId: 'gemini-pro',
|
||||||
|
name: 'Gemini Pro',
|
||||||
|
providerId: provider.id,
|
||||||
|
config: mockModelConfig,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
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,
|
||||||
|
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 mockSession = {
|
||||||
|
sendUserMessage: vi.fn().mockResolvedValue(undefined),
|
||||||
|
getSessionStats: vi.fn().mockReturnValue({ tokens: { input: 10, output: 20 } }),
|
||||||
|
getLastAssistantText: vi.fn().mockReturnValue('Arr matey!'),
|
||||||
|
state: { tools: [], systemPrompt: '', messages: [] },
|
||||||
|
}
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
;(piAgent.createAgentSession as any).mockResolvedValue({ session: mockSession })
|
||||||
|
|
||||||
|
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,6 +6,13 @@ import {
|
|||||||
UpdateAgentParams,
|
UpdateAgentParams,
|
||||||
} from '@/dtos/agent'
|
} from '@/dtos/agent'
|
||||||
import '@/prisma-json-types'
|
import '@/prisma-json-types'
|
||||||
|
import { createAgentSession, fieldsToTypeBoxSchema, type AutofillField } from '@/agent'
|
||||||
|
import { DatabaseSessionManager } from '@/agent/database-session-manager'
|
||||||
|
import { logger } from '@/logger'
|
||||||
|
import { Usage } from '@/services/ai/provider/provider'
|
||||||
|
import { s3Service } from '@/services/s3/s3'
|
||||||
|
import { defineTool, type ToolDefinition } from '@mariozechner/pi-coding-agent'
|
||||||
|
import { type TextContent, type ImageContent } from '@mariozechner/pi-ai'
|
||||||
|
|
||||||
export class AgentService {
|
export class AgentService {
|
||||||
constructor(private readonly prismaClient: typeof prisma = prisma) {}
|
constructor(private readonly prismaClient: typeof prisma = prisma) {}
|
||||||
@@ -247,6 +254,243 @@ 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,
|
||||||
|
user: {
|
||||||
|
teamMembers: {
|
||||||
|
some: { 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: ToolDefinition[] = [],
|
||||||
|
): 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 },
|
||||||
|
})
|
||||||
|
|
||||||
|
// Setup credentials
|
||||||
|
const dbProvider = dbProviders[0]
|
||||||
|
const apiKey = dbProvider?.config.apiKey as string | undefined
|
||||||
|
|
||||||
|
// Fetch team skills
|
||||||
|
const teamSkills = await this.prismaClient.skill.findMany({
|
||||||
|
where: { teamId },
|
||||||
|
})
|
||||||
|
|
||||||
|
const sandbox = await this.getSandbox(teamId)
|
||||||
|
const allowedDomains = sandbox?.allowedDomains || []
|
||||||
|
|
||||||
|
const sessionManager = await DatabaseSessionManager.create({
|
||||||
|
agentId,
|
||||||
|
userId,
|
||||||
|
sessionId,
|
||||||
|
cwd: process.cwd(),
|
||||||
|
})
|
||||||
|
|
||||||
|
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 = await createAgentSession({
|
||||||
|
agentId,
|
||||||
|
providerName,
|
||||||
|
modelId,
|
||||||
|
apiKey,
|
||||||
|
systemPrompt,
|
||||||
|
teamSkills: teamSkills.map((s) => ({
|
||||||
|
id: s.id,
|
||||||
|
name: s.name,
|
||||||
|
description: s.description,
|
||||||
|
})),
|
||||||
|
allowedDomains,
|
||||||
|
sessionManager,
|
||||||
|
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 content: (TextContent | ImageContent)[] = []
|
||||||
|
|
||||||
|
if (agentsInstruction) {
|
||||||
|
session.state.systemPrompt = `${session.state.systemPrompt}\n\nContext and Instructions:\n${agentsInstruction}`
|
||||||
|
}
|
||||||
|
content.push({ type: 'text', text: prompt })
|
||||||
|
|
||||||
|
if (images && images.length > 0) {
|
||||||
|
for (const key of images) {
|
||||||
|
const { buffer, contentType } = await s3Service.getObject(
|
||||||
|
process.env.S3_BUCKET || 'shumai',
|
||||||
|
key,
|
||||||
|
)
|
||||||
|
content.push({
|
||||||
|
type: 'image',
|
||||||
|
data: buffer.toString('base64'),
|
||||||
|
mimeType: contentType,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await session.sendUserMessage(content)
|
||||||
|
|
||||||
|
session.state.messages.forEach((msg) => {
|
||||||
|
if (msg.role === 'toolResult') {
|
||||||
|
const logMsg = { ...msg, content: undefined }
|
||||||
|
logger.debug(logMsg, 'agent message')
|
||||||
|
} else {
|
||||||
|
logger.debug(msg, 'agent message')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const stats = session.getSessionStats()
|
||||||
|
const text = session.getLastAssistantText() || ''
|
||||||
|
|
||||||
|
if (!text) {
|
||||||
|
const lastMessage = session.messages[session.messages.length - 1]
|
||||||
|
if (lastMessage && lastMessage.role === 'assistant' && lastMessage.errorMessage) {
|
||||||
|
throw new Error(`AI error: ${lastMessage.errorMessage}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const usage: Usage = {
|
||||||
|
model: modelId,
|
||||||
|
inputTokens: stats.tokens.input || 0,
|
||||||
|
outputTokens: stats.tokens.output || 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
await sessionManager.waitForSync()
|
||||||
|
|
||||||
|
return { text, usage, sessionId: sessionManager.getDbSessionId() }
|
||||||
|
} finally {
|
||||||
|
// Cleanup handled by agent session if needed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async autofill(
|
||||||
|
teamId: string,
|
||||||
|
prompt: string,
|
||||||
|
images: string[],
|
||||||
|
fields: AutofillField[],
|
||||||
|
): Promise<{ text: string; usage: Usage }> {
|
||||||
|
const agent = await this.prismaClient.agent.findFirst({
|
||||||
|
where: {
|
||||||
|
type: 'autofill',
|
||||||
|
enabled: true,
|
||||||
|
user: {
|
||||||
|
teamMembers: {
|
||||||
|
some: { 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 = defineTool({
|
||||||
|
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 } = await this.chatWithAgent(
|
||||||
|
teamId,
|
||||||
|
agent.id,
|
||||||
|
fullPrompt,
|
||||||
|
images,
|
||||||
|
'',
|
||||||
|
undefined,
|
||||||
|
undefined,
|
||||||
|
[autofillTool],
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
text: capturedData ? JSON.stringify(capturedData) : '{}',
|
||||||
|
usage,
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const agentService = new AgentService()
|
export const agentService = new AgentService()
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||||
import { setupTestDbHooks } from '@/db-test-hooks'
|
import { setupTestDbHooks } from '@/db-test-hooks'
|
||||||
import { aiChatActivity } from './agent'
|
import { aiChatActivity } from './agent'
|
||||||
import { agentExecutor } from '../executor'
|
import { agentService } from '@/services/agent/agent'
|
||||||
|
|
||||||
vi.mock('../executor', () => ({
|
vi.mock('@/services/agent/agent', () => ({
|
||||||
agentExecutor: {
|
agentService: {
|
||||||
chatWithAgent: vi.fn(),
|
chatWithAgent: vi.fn(),
|
||||||
},
|
},
|
||||||
}))
|
}))
|
||||||
@@ -17,7 +17,7 @@ describe('Agent Activities', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
it('should call aiChatActivity', async () => {
|
it('should call aiChatActivity', async () => {
|
||||||
vi.mocked(agentExecutor.chatWithAgent).mockResolvedValue({
|
vi.mocked(agentService.chatWithAgent).mockResolvedValue({
|
||||||
text: 'AI response',
|
text: 'AI response',
|
||||||
usage: { inputTokens: 1, outputTokens: 1, model: 'gpt-4' },
|
usage: { inputTokens: 1, outputTokens: 1, model: 'gpt-4' },
|
||||||
sessionId: 'mock-session-id',
|
sessionId: 'mock-session-id',
|
||||||
@@ -32,7 +32,7 @@ describe('Agent Activities', () => {
|
|||||||
folderId: 'f1',
|
folderId: 'f1',
|
||||||
})
|
})
|
||||||
|
|
||||||
expect(agentExecutor.chatWithAgent).toHaveBeenCalledWith(
|
expect(agentService.chatWithAgent).toHaveBeenCalledWith(
|
||||||
't1',
|
't1',
|
||||||
'b1',
|
'b1',
|
||||||
'Hi',
|
'Hi',
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { agentExecutor, AutofillField } from '../executor'
|
import { agentService } from '@/services/agent/agent'
|
||||||
|
import type { AutofillField } from '@/agent'
|
||||||
import { prisma } from '@/db'
|
import { prisma } from '@/db'
|
||||||
|
|
||||||
export interface AutofillAiParams {
|
export interface AutofillAiParams {
|
||||||
@@ -9,7 +10,7 @@ export interface AutofillAiParams {
|
|||||||
|
|
||||||
export async function autofillAiActivity(params: AutofillAiParams) {
|
export async function autofillAiActivity(params: AutofillAiParams) {
|
||||||
const prompt = 'Analyze the provided images and extract metadata.'
|
const prompt = 'Analyze the provided images and extract metadata.'
|
||||||
return agentExecutor.autofill(params.teamId, prompt, params.images, params.fields)
|
return agentService.autofill(params.teamId, prompt, params.images, params.fields)
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AiChatParams {
|
export interface AiChatParams {
|
||||||
@@ -26,7 +27,7 @@ export interface AiChatParams {
|
|||||||
|
|
||||||
export async function aiChatActivity(params: AiChatParams) {
|
export async function aiChatActivity(params: AiChatParams) {
|
||||||
const cleanMessage = params.message.replace(/<@[A-Z0-9]+>/g, '').trim()
|
const cleanMessage = params.message.replace(/<@[A-Z0-9]+>/g, '').trim()
|
||||||
return agentExecutor.chatWithAgent(
|
return agentService.chatWithAgent(
|
||||||
params.teamId,
|
params.teamId,
|
||||||
params.agentId,
|
params.agentId,
|
||||||
cleanMessage,
|
cleanMessage,
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import * as taskActivities from './task'
|
import * as taskActivities from './task'
|
||||||
import * as aiActivities from './ai'
|
import * as aiActivities from './ai'
|
||||||
import * as transcodeActivities from '@/transcode/activities/transcode'
|
import * as transcodeActivities from '@/transcode/activities/transcode'
|
||||||
import * as agentActivities from '@/agent/activities/agent'
|
import * as agentActivities from './agent'
|
||||||
|
|
||||||
export const activities = {
|
export const activities = {
|
||||||
...taskActivities,
|
...taskActivities,
|
||||||
|
|||||||
@@ -3,8 +3,8 @@ import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@/generated/
|
|||||||
import { Executor } from './executor'
|
import { Executor } from './executor'
|
||||||
import { aiTranscriptionMedia } from './workflows/ai-transcription'
|
import { aiTranscriptionMedia } from './workflows/ai-transcription'
|
||||||
import { aiEmbeddingMedia } from './workflows/ai-embedding'
|
import { aiEmbeddingMedia } from './workflows/ai-embedding'
|
||||||
import { aiAutofillMedia } from '@/agent/workflows/ai-autofill'
|
import { aiAutofillMedia } from './workflows/ai-autofill'
|
||||||
import { aiChat } from '@/agent/workflows/ai-chat'
|
import { aiChat } from './workflows/ai-chat'
|
||||||
import { transcodeMedia } from '@/transcode/workflows/transcode'
|
import { transcodeMedia } from '@/transcode/workflows/transcode'
|
||||||
import { activities } from './activities/index'
|
import { activities } from './activities/index'
|
||||||
import { logger } from '@/logger'
|
import { logger } from '@/logger'
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
export * from './ai-transcription'
|
export * from './ai-transcription'
|
||||||
export * from './ai-embedding'
|
export * from './ai-embedding'
|
||||||
export * from '@/agent/workflows/ai-autofill'
|
export * from './ai-autofill'
|
||||||
export * from '@/agent/workflows/ai-chat'
|
export * from './ai-chat'
|
||||||
export * from '@/transcode/workflows/transcode'
|
export * from '@/transcode/workflows/transcode'
|
||||||
|
|||||||
Reference in New Issue
Block a user