mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-26 04:07:58 +00:00
feat(agent): migrate to pi-agent-core harness and implement DatabaseSessionStorage
This commit is contained in:
@@ -2,11 +2,11 @@ import { describe, expect, test, vi, beforeEach } from 'vitest'
|
||||
import { AgentService } from './agent'
|
||||
import { prisma } from '@/db'
|
||||
import { setupTestDbHooks } from '@/db-test-hooks'
|
||||
import * as piAgent from '@mariozechner/pi-coding-agent'
|
||||
import * as piAgent from '@/agent'
|
||||
import { type AutofillField } from '@/agent'
|
||||
|
||||
vi.mock('@mariozechner/pi-coding-agent', async () => {
|
||||
const actual = await vi.importActual('@mariozechner/pi-coding-agent')
|
||||
vi.mock('@/agent', async () => {
|
||||
const actual = await vi.importActual('@/agent')
|
||||
return {
|
||||
...actual,
|
||||
createAgentSession: vi.fn(),
|
||||
@@ -231,9 +231,7 @@ describe('AgentService', () => {
|
||||
})
|
||||
|
||||
describe('agent execution', () => {
|
||||
const mockProviderConfig: PrismaJson.ProviderConfig = {
|
||||
api: 'openai-completions',
|
||||
baseUrl: 'http://localhost:11434/v1',
|
||||
const mockProviderConfig: PrismaJson.AiProviderSettings = {
|
||||
apiKey: 'test-key',
|
||||
}
|
||||
|
||||
@@ -254,7 +252,7 @@ describe('AgentService', () => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
test('autofills with agent', async () => {
|
||||
test('autofill extracts metadata', async () => {
|
||||
const db = prisma
|
||||
const svc = new AgentService()
|
||||
|
||||
@@ -266,18 +264,22 @@ describe('AgentService', () => {
|
||||
|
||||
const provider = await db.provider.create({
|
||||
data: {
|
||||
name: 'openai',
|
||||
name: 'google',
|
||||
teamId: team.id,
|
||||
config: mockProviderConfig,
|
||||
// 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: 'gpt-4',
|
||||
name: 'GPT-4',
|
||||
modelId: 'gemini',
|
||||
name: 'Gemini',
|
||||
providerId: provider.id,
|
||||
config: mockModelConfig,
|
||||
// Config is generic Json in Prisma
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
config: mockModelConfig as any,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -293,8 +295,8 @@ describe('AgentService', () => {
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
config: {
|
||||
provider: 'openai',
|
||||
model: 'gpt-4',
|
||||
provider: 'google',
|
||||
model: 'gemini',
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -307,35 +309,34 @@ describe('AgentService', () => {
|
||||
},
|
||||
})
|
||||
|
||||
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 })
|
||||
}
|
||||
const mockHarness = {
|
||||
prompt: vi.fn().mockResolvedValue({
|
||||
content: [{ type: 'text', text: 'Metadata captured successfully.' }],
|
||||
usage: { input: 5, output: 5 },
|
||||
}),
|
||||
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[],
|
||||
}
|
||||
const mockSessionManager = {
|
||||
waitForSync: vi.fn().mockResolvedValue(undefined),
|
||||
getDbSessionId: vi.fn().mockReturnValue('mock-session-id'),
|
||||
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: any) => {
|
||||
mockSession.customTools = config.customTools
|
||||
return { session: mockSession, sessionManager: mockSessionManager }
|
||||
;(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('{"data":1}')
|
||||
expect(resp.text).toBe('{"f1":"data-val"}')
|
||||
expect(resp.usage.inputTokens).toBe(5)
|
||||
})
|
||||
|
||||
@@ -353,7 +354,9 @@ describe('AgentService', () => {
|
||||
data: {
|
||||
name: 'google',
|
||||
teamId: team.id,
|
||||
config: mockProviderConfig,
|
||||
// Config is generic Json in Prisma
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
config: mockProviderConfig as any,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -362,7 +365,9 @@ describe('AgentService', () => {
|
||||
modelId: 'gemini',
|
||||
name: 'Gemini',
|
||||
providerId: provider.id,
|
||||
config: mockModelConfig,
|
||||
// Config is generic Json in Prisma
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
config: mockModelConfig as any,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -392,20 +397,21 @@ describe('AgentService', () => {
|
||||
},
|
||||
})
|
||||
|
||||
const mockHarness = {
|
||||
prompt: vi.fn().mockResolvedValue({
|
||||
content: [{ type: 'text', text: 'mock text' }],
|
||||
usage: { input: 5, output: 5 },
|
||||
}),
|
||||
}
|
||||
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: [] },
|
||||
}
|
||||
const mockSessionManager = {
|
||||
waitForSync: vi.fn().mockResolvedValue(undefined),
|
||||
getDbSessionId: vi.fn().mockReturnValue('mock-session-id'),
|
||||
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,
|
||||
sessionManager: mockSessionManager,
|
||||
harness: mockHarness,
|
||||
})
|
||||
|
||||
const resp = await svc.chat(team.id, 'hello')
|
||||
@@ -426,7 +432,9 @@ describe('AgentService', () => {
|
||||
data: {
|
||||
name: 'google',
|
||||
teamId: team.id,
|
||||
config: mockProviderConfig,
|
||||
// Config is generic Json in Prisma
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
config: mockProviderConfig as any,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -435,7 +443,9 @@ describe('AgentService', () => {
|
||||
modelId: 'gemini-pro',
|
||||
name: 'Gemini Pro',
|
||||
providerId: provider.id,
|
||||
config: mockModelConfig,
|
||||
// Config is generic Json in Prisma
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
config: mockModelConfig as any,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -462,20 +472,21 @@ describe('AgentService', () => {
|
||||
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 = {
|
||||
sendUserMessage: vi.fn().mockResolvedValue(undefined),
|
||||
getSessionStats: vi.fn().mockReturnValue({ tokens: { input: 10, output: 20 } }),
|
||||
getLastAssistantText: vi.fn().mockReturnValue('Arr matey!'),
|
||||
state: { tools: [], systemPrompt: '', messages: [] },
|
||||
}
|
||||
const mockSessionManager = {
|
||||
waitForSync: vi.fn().mockResolvedValue(undefined),
|
||||
getDbSessionId: vi.fn().mockReturnValue('mock-session-id'),
|
||||
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,
|
||||
sessionManager: mockSessionManager,
|
||||
harness: mockHarness,
|
||||
})
|
||||
|
||||
const resp = await svc.chatWithAgent(team.id, agent.id, 'hello', [], 'Talk like a pirate')
|
||||
|
||||
+28
-39
@@ -10,8 +10,8 @@ import { createAgentSession, fieldsToTypeBoxSchema, type AutofillField } from '@
|
||||
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'
|
||||
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) {}
|
||||
@@ -293,7 +293,7 @@ export class AgentService {
|
||||
agentsInstruction: string,
|
||||
sessionId?: string,
|
||||
userId?: string,
|
||||
tools: ToolDefinition[] = [],
|
||||
tools: AgentTool[] = [],
|
||||
): Promise<{ text: string; usage: Usage; sessionId: string }> {
|
||||
const t = await this.getTeam(teamId)
|
||||
if (!t) throw new Error('failed to get team')
|
||||
@@ -322,10 +322,6 @@ export class AgentService {
|
||||
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 },
|
||||
@@ -344,11 +340,10 @@ export class AgentService {
|
||||
systemPrompt += `\n\nYour current model supports the following input types: ${modelConfig.input.join(', ')}.`
|
||||
}
|
||||
|
||||
const { session, sessionManager } = await createAgentSession({
|
||||
const { session, harness } = await createAgentSession({
|
||||
agentId,
|
||||
providerName,
|
||||
modelId,
|
||||
apiKey,
|
||||
systemPrompt,
|
||||
teamSkills: teamSkills.map((s) => ({
|
||||
id: s.id,
|
||||
@@ -370,12 +365,7 @@ export class AgentService {
|
||||
})),
|
||||
})
|
||||
|
||||
const content: (TextContent | ImageContent)[] = []
|
||||
|
||||
if (agentsInstruction) {
|
||||
session.state.systemPrompt = `${session.state.systemPrompt}\n\nContext and Instructions:\n${agentsInstruction}`
|
||||
}
|
||||
content.push({ type: 'text', text: prompt })
|
||||
const imagesToPass: ImageContent[] = []
|
||||
|
||||
if (images && images.length > 0) {
|
||||
for (const key of images) {
|
||||
@@ -383,7 +373,7 @@ export class AgentService {
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
key,
|
||||
)
|
||||
content.push({
|
||||
imagesToPass.push({
|
||||
type: 'image',
|
||||
data: buffer.toString('base64'),
|
||||
mimeType: contentType,
|
||||
@@ -392,36 +382,35 @@ export class AgentService {
|
||||
}
|
||||
|
||||
try {
|
||||
await session.sendUserMessage(content)
|
||||
const assistantMessage = await harness.prompt(prompt, { images: imagesToPass })
|
||||
|
||||
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 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 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 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: stats.tokens.input || 0,
|
||||
outputTokens: stats.tokens.output || 0,
|
||||
inputTokens: assistantMessage.usage?.input || 0,
|
||||
outputTokens: assistantMessage.usage?.output || 0,
|
||||
}
|
||||
|
||||
await sessionManager.waitForSync()
|
||||
|
||||
return { text, usage, sessionId: sessionManager.getDbSessionId() }
|
||||
// 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
|
||||
}
|
||||
@@ -452,7 +441,7 @@ export class AgentService {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let capturedData: any = null
|
||||
|
||||
const autofillTool = defineTool({
|
||||
const autofillTool: AgentTool = {
|
||||
name: 'autofill_metadata',
|
||||
label: 'Autofill Metadata',
|
||||
description: 'Extract metadata from the images.',
|
||||
@@ -464,7 +453,7 @@ export class AgentService {
|
||||
details: {},
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const fullPrompt = `${prompt}\n\nPlease use the "autofill_metadata" tool to provide the extracted metadata.`
|
||||
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
import { prisma } from '@/db'
|
||||
import { SkillInfo, UpsertSkillRequest } from '@/dtos/skill'
|
||||
import { s3Service } from '@/services/s3/s3'
|
||||
import { parseFrontmatter, SkillFrontmatter } from '@mariozechner/pi-coding-agent'
|
||||
import AdmZip from 'adm-zip'
|
||||
import * as crypto from 'crypto'
|
||||
import { ulid } from 'ulid'
|
||||
import { parse } from 'yaml'
|
||||
|
||||
interface SkillFrontmatter {
|
||||
name?: string
|
||||
description?: string
|
||||
}
|
||||
|
||||
export class SkillService {
|
||||
constructor(private readonly prismaClient: typeof prisma = prisma) {}
|
||||
@@ -253,7 +258,15 @@ export class SkillService {
|
||||
}
|
||||
|
||||
private parseSkillMd(content: string): { name: string; description: string } {
|
||||
const { frontmatter } = parseFrontmatter<SkillFrontmatter>(content)
|
||||
const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n([\s\S]*))?$/)
|
||||
let frontmatter: SkillFrontmatter = {}
|
||||
if (match) {
|
||||
try {
|
||||
frontmatter = parse(match[1])
|
||||
} catch (e) {
|
||||
console.error('Failed to parse skill frontmatter', e)
|
||||
}
|
||||
}
|
||||
const name = frontmatter.name || 'Unnamed Skill'
|
||||
const description = frontmatter.description || ''
|
||||
|
||||
|
||||
Reference in New Issue
Block a user