mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-05 23:54:25 +00:00
Merge pull request #32 from shumaiOne/remove-generic-ai-providers
refactor(ai): remove generic providers and hardcode gemini-embedding-2
This commit is contained in:
@@ -79,14 +79,12 @@
|
|||||||
"extract-zip": "^2.0.1",
|
"extract-zip": "^2.0.1",
|
||||||
"hono": "^4.12.14",
|
"hono": "^4.12.14",
|
||||||
"input-otp": "1.4.1",
|
"input-otp": "1.4.1",
|
||||||
"install": "^0.13.0",
|
|
||||||
"jittered-fractional-indexing": "^1.0.1",
|
"jittered-fractional-indexing": "^1.0.1",
|
||||||
"konva": "^10.0.12",
|
"konva": "^10.0.12",
|
||||||
"lexical": "^0.42.0",
|
"lexical": "^0.42.0",
|
||||||
"loader-utils": "^3.3.1",
|
"loader-utils": "^3.3.1",
|
||||||
"lucide-react": "^0.454.0",
|
"lucide-react": "^0.454.0",
|
||||||
"next-themes": "^0.4.6",
|
"next-themes": "^0.4.6",
|
||||||
"openai": "^6.34.0",
|
|
||||||
"pg": "^8.20.0",
|
"pg": "^8.20.0",
|
||||||
"pino": "^10.3.1",
|
"pino": "^10.3.1",
|
||||||
"pino-pretty": "^13.1.3",
|
"pino-pretty": "^13.1.3",
|
||||||
@@ -106,8 +104,6 @@
|
|||||||
"tailwindcss-animate": "^1.0.7",
|
"tailwindcss-animate": "^1.0.7",
|
||||||
"ulid": "^3.0.2",
|
"ulid": "^3.0.2",
|
||||||
"use-image": "^1.1.4",
|
"use-image": "^1.1.4",
|
||||||
"uuid": "^13.0.0",
|
|
||||||
"uuidv7": "^1.2.1",
|
|
||||||
"vaul": "^0.9.9",
|
"vaul": "^0.9.9",
|
||||||
"video.js": "^8.23.4",
|
"video.js": "^8.23.4",
|
||||||
"vite": "^7.2.2",
|
"vite": "^7.2.2",
|
||||||
@@ -1946,8 +1942,6 @@
|
|||||||
|
|
||||||
"input-otp": ["input-otp@1.4.1", "", { "peerDependencies": { "react": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc" } }, "sha512-+yvpmKYKHi9jIGngxagY9oWiiblPB7+nEO75F2l2o4vs+6vpPZZmUl4tBNYuTCvQjhvEIbdNeJu70bhfYP2nbw=="],
|
"input-otp": ["input-otp@1.4.1", "", { "peerDependencies": { "react": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc" } }, "sha512-+yvpmKYKHi9jIGngxagY9oWiiblPB7+nEO75F2l2o4vs+6vpPZZmUl4tBNYuTCvQjhvEIbdNeJu70bhfYP2nbw=="],
|
||||||
|
|
||||||
"install": ["install@0.13.0", "", {}, "sha512-zDml/jzr2PKU9I8J/xyZBQn8rPCAY//UOYNmR01XwNwyfhEWObo2SWfSl1+0tm1u6PhxLwDnfsT/6jB7OUxqFA=="],
|
|
||||||
|
|
||||||
"internal-slot": ["internal-slot@1.1.0", "", { "dependencies": { "es-errors": "^1.3.0", "hasown": "^2.0.2", "side-channel": "^1.1.0" } }, "sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw=="],
|
"internal-slot": ["internal-slot@1.1.0", "", { "dependencies": { "es-errors": "^1.3.0", "hasown": "^2.0.2", "side-channel": "^1.1.0" } }, "sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw=="],
|
||||||
|
|
||||||
"internmap": ["internmap@2.0.3", "", {}, "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg=="],
|
"internmap": ["internmap@2.0.3", "", {}, "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg=="],
|
||||||
@@ -2356,7 +2350,7 @@
|
|||||||
|
|
||||||
"onetime": ["onetime@5.1.2", "", { "dependencies": { "mimic-fn": "^2.1.0" } }, "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg=="],
|
"onetime": ["onetime@5.1.2", "", { "dependencies": { "mimic-fn": "^2.1.0" } }, "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg=="],
|
||||||
|
|
||||||
"openai": ["openai@6.34.0", "", { "peerDependencies": { "ws": "^8.18.0", "zod": "^3.25 || ^4.0" }, "optionalPeers": ["ws", "zod"], "bin": { "openai": "bin/cli" } }, "sha512-yEr2jdGf4tVFYG6ohmr3pF6VJuveP0EA/sS8TBx+4Eq5NT10alu5zg2dmxMXMgqpihRDQlFGpRt2XwsGj+Fyxw=="],
|
"openai": ["openai@6.26.0", "", { "peerDependencies": { "ws": "^8.18.0", "zod": "^3.25 || ^4.0" }, "optionalPeers": ["ws", "zod"], "bin": { "openai": "bin/cli" } }, "sha512-zd23dbWTjiJ6sSAX6s0HrCZi41JwTA1bQVs0wLQPZ2/5o2gxOJA5wh7yOAUgwYybfhDXyhwlpeQf7Mlgx8EOCA=="],
|
||||||
|
|
||||||
"openapi-types": ["openapi-types@12.1.3", "", {}, "sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw=="],
|
"openapi-types": ["openapi-types@12.1.3", "", {}, "sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw=="],
|
||||||
|
|
||||||
@@ -2870,9 +2864,7 @@
|
|||||||
|
|
||||||
"utility-types": ["utility-types@3.11.0", "", {}, "sha512-6Z7Ma2aVEWisaL6TvBCy7P8rm2LQoPv6dJ7ecIaIixHcwfbJ0x7mWdbcwlIM5IGQxPZSFYeqRCqlOOeKoJYMkw=="],
|
"utility-types": ["utility-types@3.11.0", "", {}, "sha512-6Z7Ma2aVEWisaL6TvBCy7P8rm2LQoPv6dJ7ecIaIixHcwfbJ0x7mWdbcwlIM5IGQxPZSFYeqRCqlOOeKoJYMkw=="],
|
||||||
|
|
||||||
"uuid": ["uuid@13.0.0", "", { "bin": { "uuid": "dist-node/bin/uuid" } }, "sha512-XQegIaBTVUjSHliKqcnFqYypAd4S+WCYt5NIeRs6w/UAry7z8Y9j5ZwRRL4kzq9U3sD6v+85er9FvkEaBpji2w=="],
|
"uuid": ["uuid@11.1.0", "", { "bin": { "uuid": "dist/esm/bin/uuid" } }, "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A=="],
|
||||||
|
|
||||||
"uuidv7": ["uuidv7@1.2.1", "", { "bin": { "uuidv7": "cli.js" } }, "sha512-4kPkK3/XTQW9Hbm4CaqfICn+kY9LJtDVEOfgsRRra/+n2Ofg4NqzRFceAkxvQ/Ud/6BpHOPzj8cirqM7TzTN5Q=="],
|
|
||||||
|
|
||||||
"valibot": ["valibot@1.2.0", "", { "peerDependencies": { "typescript": ">=5" }, "optionalPeers": ["typescript"] }, "sha512-mm1rxUsmOxzrwnX5arGS+U4T25RdvpPjPN4yR0u9pUBov9+zGVtO84tif1eY4r6zWxVxu3KzIyknJy3rxfRZZg=="],
|
"valibot": ["valibot@1.2.0", "", { "peerDependencies": { "typescript": ">=5" }, "optionalPeers": ["typescript"] }, "sha512-mm1rxUsmOxzrwnX5arGS+U4T25RdvpPjPN4yR0u9pUBov9+zGVtO84tif1eY4r6zWxVxu3KzIyknJy3rxfRZZg=="],
|
||||||
|
|
||||||
@@ -3022,8 +3014,6 @@
|
|||||||
|
|
||||||
"@earendil-works/pi-ai/@google/genai": ["@google/genai@1.52.0", "", { "dependencies": { "google-auth-library": "^10.3.0", "p-retry": "^4.6.2", "protobufjs": "^7.5.4", "ws": "^8.18.0" }, "peerDependencies": { "@modelcontextprotocol/sdk": "^1.25.2" }, "optionalPeers": ["@modelcontextprotocol/sdk"] }, "sha512-gwSvbpiN/17O9TbsqSsE/OzZcpv5Fo4RQjdngGgogtuB9RsyJ8ZHhX5KjHj1bp5N9snN2eK8LDGXSaWW2hof8Q=="],
|
"@earendil-works/pi-ai/@google/genai": ["@google/genai@1.52.0", "", { "dependencies": { "google-auth-library": "^10.3.0", "p-retry": "^4.6.2", "protobufjs": "^7.5.4", "ws": "^8.18.0" }, "peerDependencies": { "@modelcontextprotocol/sdk": "^1.25.2" }, "optionalPeers": ["@modelcontextprotocol/sdk"] }, "sha512-gwSvbpiN/17O9TbsqSsE/OzZcpv5Fo4RQjdngGgogtuB9RsyJ8ZHhX5KjHj1bp5N9snN2eK8LDGXSaWW2hof8Q=="],
|
||||||
|
|
||||||
"@earendil-works/pi-ai/openai": ["openai@6.26.0", "", { "peerDependencies": { "ws": "^8.18.0", "zod": "^3.25 || ^4.0" }, "optionalPeers": ["ws", "zod"], "bin": { "openai": "bin/cli" } }, "sha512-zd23dbWTjiJ6sSAX6s0HrCZi41JwTA1bQVs0wLQPZ2/5o2gxOJA5wh7yOAUgwYybfhDXyhwlpeQf7Mlgx8EOCA=="],
|
|
||||||
|
|
||||||
"@eslint-community/eslint-utils/eslint-visitor-keys": ["eslint-visitor-keys@3.4.3", "", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="],
|
"@eslint-community/eslint-utils/eslint-visitor-keys": ["eslint-visitor-keys@3.4.3", "", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="],
|
||||||
|
|
||||||
"@eslint/eslintrc/globals": ["globals@14.0.0", "", {}, "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ=="],
|
"@eslint/eslintrc/globals": ["globals@14.0.0", "", {}, "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ=="],
|
||||||
@@ -3212,8 +3202,6 @@
|
|||||||
|
|
||||||
"@tanstack/router-plugin/zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
|
"@tanstack/router-plugin/zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
|
||||||
|
|
||||||
"@temporalio/client/uuid": ["uuid@11.1.0", "", { "bin": { "uuid": "dist/esm/bin/uuid" } }, "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A=="],
|
|
||||||
|
|
||||||
"@temporalio/common/ms": ["ms@3.0.0-canary.1", "", {}, "sha512-kh8ARjh8rMN7Du2igDRO9QJnqCb2xYTJxyQYK7vJJS4TvLLmsbyhiKpSW+t+y26gyOyMd0riphX0GeWKU3ky5g=="],
|
"@temporalio/common/ms": ["ms@3.0.0-canary.1", "", {}, "sha512-kh8ARjh8rMN7Du2igDRO9QJnqCb2xYTJxyQYK7vJJS4TvLLmsbyhiKpSW+t+y26gyOyMd0riphX0GeWKU3ky5g=="],
|
||||||
|
|
||||||
"@typescript-eslint/eslint-plugin/ignore": ["ignore@7.0.5", "", {}, "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg=="],
|
"@typescript-eslint/eslint-plugin/ignore": ["ignore@7.0.5", "", {}, "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg=="],
|
||||||
|
|||||||
@@ -90,14 +90,12 @@
|
|||||||
"extract-zip": "^2.0.1",
|
"extract-zip": "^2.0.1",
|
||||||
"hono": "^4.12.14",
|
"hono": "^4.12.14",
|
||||||
"input-otp": "1.4.1",
|
"input-otp": "1.4.1",
|
||||||
"install": "^0.13.0",
|
|
||||||
"jittered-fractional-indexing": "^1.0.1",
|
"jittered-fractional-indexing": "^1.0.1",
|
||||||
"konva": "^10.0.12",
|
"konva": "^10.0.12",
|
||||||
"lexical": "^0.42.0",
|
"lexical": "^0.42.0",
|
||||||
"loader-utils": "^3.3.1",
|
"loader-utils": "^3.3.1",
|
||||||
"lucide-react": "^0.454.0",
|
"lucide-react": "^0.454.0",
|
||||||
"next-themes": "^0.4.6",
|
"next-themes": "^0.4.6",
|
||||||
"openai": "^6.34.0",
|
|
||||||
"pg": "^8.20.0",
|
"pg": "^8.20.0",
|
||||||
"pino": "^10.3.1",
|
"pino": "^10.3.1",
|
||||||
"pino-pretty": "^13.1.3",
|
"pino-pretty": "^13.1.3",
|
||||||
@@ -117,8 +115,6 @@
|
|||||||
"tailwindcss-animate": "^1.0.7",
|
"tailwindcss-animate": "^1.0.7",
|
||||||
"ulid": "^3.0.2",
|
"ulid": "^3.0.2",
|
||||||
"use-image": "^1.1.4",
|
"use-image": "^1.1.4",
|
||||||
"uuid": "^13.0.0",
|
|
||||||
"uuidv7": "^1.2.1",
|
|
||||||
"vaul": "^0.9.9",
|
"vaul": "^0.9.9",
|
||||||
"video.js": "^8.23.4",
|
"video.js": "^8.23.4",
|
||||||
"vite": "^7.2.2",
|
"vite": "^7.2.2",
|
||||||
|
|||||||
@@ -1,41 +0,0 @@
|
|||||||
import { AiProviderSettings } from '@/dtos/ai'
|
|
||||||
import { Provider, Usage } from './provider'
|
|
||||||
|
|
||||||
export class ElevenLabsProvider implements Provider {
|
|
||||||
private config: AiProviderSettings
|
|
||||||
|
|
||||||
constructor(config: AiProviderSettings) {
|
|
||||||
this.config = config
|
|
||||||
}
|
|
||||||
|
|
||||||
async chat(
|
|
||||||
model: string,
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
||||||
_prompt: string,
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
||||||
_images: string[],
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unused-vars
|
|
||||||
_schema?: any,
|
|
||||||
): Promise<{ text: string; usage: Usage }> {
|
|
||||||
// TODO: Implement ElevenLabs chat
|
|
||||||
return {
|
|
||||||
text: 'elevenlabs response',
|
|
||||||
usage: { model, inputTokens: 0, outputTokens: 0 },
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
||||||
async generateImageEmbedding(_model: string, _imageBuffer: Buffer): Promise<number[]> {
|
|
||||||
throw new Error('Not implemented')
|
|
||||||
}
|
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
||||||
async generateVideoEmbedding(_model: string, _videoBuffer: Buffer): Promise<number[]> {
|
|
||||||
throw new Error('Not implemented')
|
|
||||||
}
|
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
||||||
async generateTextEmbedding(_model: string, _text: string): Promise<number[]> {
|
|
||||||
throw new Error('Not implemented')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
import { GoogleGenAI } from '@google/genai'
|
|
||||||
import { AiProviderSettings } from '@/dtos/ai'
|
|
||||||
import { Provider, Usage } from './provider'
|
|
||||||
|
|
||||||
export class GeminiProvider implements Provider {
|
|
||||||
private config: AiProviderSettings
|
|
||||||
private client: GoogleGenAI
|
|
||||||
|
|
||||||
constructor(config: AiProviderSettings) {
|
|
||||||
this.config = config
|
|
||||||
this.client = new GoogleGenAI({
|
|
||||||
apiKey: config.apiKey,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
private async downloadImage(url: string): Promise<{ data: Buffer; contentType: string }> {
|
|
||||||
const resp = await fetch(url)
|
|
||||||
if (!resp.ok) {
|
|
||||||
throw new Error(`Failed to download image, status: ${resp.status}`)
|
|
||||||
}
|
|
||||||
const arrayBuffer = await resp.arrayBuffer()
|
|
||||||
const contentType = resp.headers.get('content-type') || 'image/jpeg'
|
|
||||||
return { data: Buffer.from(arrayBuffer), contentType }
|
|
||||||
}
|
|
||||||
|
|
||||||
async chat(
|
|
||||||
model: string,
|
|
||||||
prompt: string,
|
|
||||||
images: string[],
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
schema?: any,
|
|
||||||
): Promise<{ text: string; usage: Usage }> {
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
const parts: any[] = []
|
|
||||||
|
|
||||||
for (const imgUrl of images) {
|
|
||||||
const { data, contentType } = await this.downloadImage(imgUrl)
|
|
||||||
parts.push({
|
|
||||||
inlineData: {
|
|
||||||
data: data.toString('base64'),
|
|
||||||
mimeType: contentType,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
parts.push({ text: prompt })
|
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
const config: any = {}
|
|
||||||
|
|
||||||
if (schema) {
|
|
||||||
config.responseMimeType = 'application/json'
|
|
||||||
config.responseSchema = schema
|
|
||||||
}
|
|
||||||
|
|
||||||
const result = await this.client.models.generateContent({
|
|
||||||
model,
|
|
||||||
contents: [{ role: 'user', parts }],
|
|
||||||
config,
|
|
||||||
})
|
|
||||||
|
|
||||||
const usage: Usage = { model, inputTokens: 0, outputTokens: 0 }
|
|
||||||
if (result.usageMetadata) {
|
|
||||||
usage.inputTokens = result.usageMetadata.promptTokenCount || 0
|
|
||||||
usage.outputTokens = result.usageMetadata.candidatesTokenCount || 0
|
|
||||||
}
|
|
||||||
|
|
||||||
return { text: result.text || '', usage }
|
|
||||||
}
|
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
||||||
async generateImageEmbedding(_model: string, _imageBuffer: Buffer): Promise<number[]> {
|
|
||||||
throw new Error('Not implemented')
|
|
||||||
}
|
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
||||||
async generateVideoEmbedding(_model: string, _videoBuffer: Buffer): Promise<number[]> {
|
|
||||||
throw new Error('Not implemented')
|
|
||||||
}
|
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
||||||
async generateTextEmbedding(_model: string, _text: string): Promise<number[]> {
|
|
||||||
throw new Error('Not implemented')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,93 +0,0 @@
|
|||||||
import OpenAI from 'openai'
|
|
||||||
|
|
||||||
import { AiProviderSettings } from '@/dtos/ai'
|
|
||||||
import { Provider, Usage } from './provider'
|
|
||||||
|
|
||||||
export class OpenAiProvider implements Provider {
|
|
||||||
private config: AiProviderSettings
|
|
||||||
private client: OpenAI
|
|
||||||
|
|
||||||
constructor(config: AiProviderSettings) {
|
|
||||||
this.config = config
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
const opts: any = {
|
|
||||||
apiKey: config.apiKey,
|
|
||||||
}
|
|
||||||
if (config.baseUrl) {
|
|
||||||
opts.baseUrl = config.baseUrl
|
|
||||||
}
|
|
||||||
this.client = new OpenAI(opts)
|
|
||||||
}
|
|
||||||
|
|
||||||
async chat(
|
|
||||||
model: string,
|
|
||||||
prompt: string,
|
|
||||||
images: string[],
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
schema?: any,
|
|
||||||
): Promise<{ text: string; usage: Usage }> {
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
const messages: any[] = []
|
|
||||||
|
|
||||||
if (images.length > 0) {
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
const contentParts: any[] = [{ type: 'text', text: prompt }]
|
|
||||||
for (const imgUrl of images) {
|
|
||||||
contentParts.push({
|
|
||||||
type: 'imageUrl',
|
|
||||||
imageUrl: { url: imgUrl },
|
|
||||||
})
|
|
||||||
}
|
|
||||||
messages.push({ role: 'user', content: contentParts })
|
|
||||||
} else {
|
|
||||||
messages.push({ role: 'user', content: prompt })
|
|
||||||
}
|
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
const params: any = {
|
|
||||||
model,
|
|
||||||
messages,
|
|
||||||
}
|
|
||||||
|
|
||||||
if (schema) {
|
|
||||||
params.response_format = {
|
|
||||||
type: 'jsonSchema',
|
|
||||||
jsonSchema: {
|
|
||||||
name: 'response',
|
|
||||||
description: 'Structured response',
|
|
||||||
schema: schema,
|
|
||||||
strict: true,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const chat = await this.client.chat.completions.create(params)
|
|
||||||
|
|
||||||
if (chat.choices.length === 0) {
|
|
||||||
throw new Error('No choices returned from openai')
|
|
||||||
}
|
|
||||||
|
|
||||||
const usage: Usage = {
|
|
||||||
model,
|
|
||||||
inputTokens: chat.usage?.prompt_tokens || 0,
|
|
||||||
outputTokens: chat.usage?.completion_tokens || 0,
|
|
||||||
}
|
|
||||||
|
|
||||||
return { text: chat.choices[0].message.content || '', usage }
|
|
||||||
}
|
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
||||||
async generateImageEmbedding(_model: string, _imageBuffer: Buffer): Promise<number[]> {
|
|
||||||
throw new Error('Not implemented')
|
|
||||||
}
|
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
||||||
async generateVideoEmbedding(_model: string, _videoBuffer: Buffer): Promise<number[]> {
|
|
||||||
throw new Error('Not implemented')
|
|
||||||
}
|
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
||||||
async generateTextEmbedding(_model: string, _text: string): Promise<number[]> {
|
|
||||||
throw new Error('Not implemented')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
export interface Usage {
|
|
||||||
inputTokens: number
|
|
||||||
outputTokens: number
|
|
||||||
model: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface Provider {
|
|
||||||
chat(
|
|
||||||
model: string,
|
|
||||||
prompt: string,
|
|
||||||
images: string[],
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
schema?: any,
|
|
||||||
): Promise<{ text: string; usage: Usage }>
|
|
||||||
|
|
||||||
generateImageEmbedding(model: string, imageBuffer: Buffer): Promise<number[]>
|
|
||||||
|
|
||||||
generateVideoEmbedding(model: string, videoBuffer: Buffer): Promise<number[]>
|
|
||||||
|
|
||||||
generateTextEmbedding(model: string, text: string): Promise<number[]>
|
|
||||||
}
|
|
||||||
@@ -4,8 +4,13 @@ import { logger } from '@/logger'
|
|||||||
import { s3Service } from '@/services/s3/s3'
|
import { s3Service } from '@/services/s3/s3'
|
||||||
import { type AgentTool } from '@earendil-works/pi-agent-core'
|
import { type AgentTool } from '@earendil-works/pi-agent-core'
|
||||||
import { type ImageContent } from '@earendil-works/pi-ai'
|
import { type ImageContent } from '@earendil-works/pi-ai'
|
||||||
import { type Usage } from '@/services/ai/provider/provider'
|
|
||||||
import { ApplicationFailure } from '@temporalio/activity'
|
import { ApplicationFailure } from '@temporalio/activity'
|
||||||
|
|
||||||
|
export interface Usage {
|
||||||
|
inputTokens: number
|
||||||
|
outputTokens: number
|
||||||
|
model: string
|
||||||
|
}
|
||||||
import type { Prisma, Skill } from '@/generated/prisma/client'
|
import type { Prisma, Skill } from '@/generated/prisma/client'
|
||||||
|
|
||||||
export type AgentWithProviderAndModel = Prisma.AgentGetPayload<{
|
export type AgentWithProviderAndModel = Prisma.AgentGetPayload<{
|
||||||
|
|||||||
@@ -11,10 +11,21 @@ vi.mock('@/services/s3/s3', () => ({
|
|||||||
},
|
},
|
||||||
}))
|
}))
|
||||||
|
|
||||||
vi.mock('@/services/ai/provider/gemini', () => {
|
const mockEmbedContent = vi.fn().mockResolvedValue({
|
||||||
|
embeddings: [
|
||||||
|
{
|
||||||
|
values: [0.1, 0.2, 0.3],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
|
||||||
|
vi.mock('@google/genai', () => {
|
||||||
return {
|
return {
|
||||||
GeminiProvider: class {
|
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||||
generateImageEmbedding = vi.fn().mockResolvedValue([0.1, 0.2, 0.3])
|
GoogleGenAI: class {
|
||||||
|
models = {
|
||||||
|
embedContent: mockEmbedContent,
|
||||||
|
}
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -22,6 +33,7 @@ vi.mock('@/services/ai/provider/gemini', () => {
|
|||||||
describe('AI Activities', () => {
|
describe('AI Activities', () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.clearAllMocks()
|
vi.clearAllMocks()
|
||||||
|
process.env.GEMINI_API_KEY = 'test-key'
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should generate image embedding', async () => {
|
it('should generate image embedding', async () => {
|
||||||
@@ -34,7 +46,6 @@ describe('AI Activities', () => {
|
|||||||
const context = {
|
const context = {
|
||||||
agent: { config: { provider: 'google', model: 'gemini' } },
|
agent: { config: { provider: 'google', model: 'gemini' } },
|
||||||
asset: { id: 'a1', mediaType: 'image/png', storageKey: { key: 'test.png' } },
|
asset: { id: 'a1', mediaType: 'image/png', storageKey: { key: 'test.png' } },
|
||||||
dbProvider: { config: { apiKey: 'key' } },
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const res = await generateEmbeddingActivity({
|
const res = await generateEmbeddingActivity({
|
||||||
|
|||||||
@@ -1,8 +1,4 @@
|
|||||||
import { ElevenLabsProvider } from '@/services/ai/provider/elevenlabs'
|
import { GoogleGenAI } from '@google/genai'
|
||||||
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 { s3Service } from '@/services/s3/s3'
|
||||||
import { transcodeService } from '@/transcode/transcode'
|
import { transcodeService } from '@/transcode/transcode'
|
||||||
import { exec } from 'child_process'
|
import { exec } from 'child_process'
|
||||||
@@ -14,41 +10,10 @@ import { ApplicationFailure } from '@temporalio/activity'
|
|||||||
|
|
||||||
const execAsync = promisify(exec)
|
const execAsync = promisify(exec)
|
||||||
|
|
||||||
function providerFactory(providerName: string, config: PrismaJson.AiProviderSettings): Provider {
|
export interface Usage {
|
||||||
let pKey: AiProvider
|
inputTokens: number
|
||||||
switch (providerName) {
|
outputTokens: number
|
||||||
case AiProvider.Google:
|
model: string
|
||||||
pKey = AiProvider.Google
|
|
||||||
break
|
|
||||||
case AiProvider.OpenAi:
|
|
||||||
pKey = AiProvider.OpenAi
|
|
||||||
break
|
|
||||||
case AiProvider.ElevenLabs:
|
|
||||||
pKey = AiProvider.ElevenLabs
|
|
||||||
break
|
|
||||||
default:
|
|
||||||
throw ApplicationFailure.create({
|
|
||||||
message: `Unsupported provider: ${providerName}`,
|
|
||||||
nonRetryable: true,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
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 ApplicationFailure.create({
|
|
||||||
message: `Provider implementation for ${providerName} not found`,
|
|
||||||
nonRetryable: true,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface GeneratedEmbedding {
|
export interface GeneratedEmbedding {
|
||||||
@@ -63,39 +28,61 @@ export interface GenerateEmbeddingParams {
|
|||||||
context: {
|
context: {
|
||||||
agent: unknown
|
agent: unknown
|
||||||
asset: unknown
|
asset: unknown
|
||||||
dbProvider: unknown
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function generateMultimodalEmbedding(
|
||||||
|
ai: GoogleGenAI,
|
||||||
|
buffer: Buffer,
|
||||||
|
mimeType: string,
|
||||||
|
): Promise<number[]> {
|
||||||
|
const response = await ai.models.embedContent({
|
||||||
|
model: 'gemini-embedding-2',
|
||||||
|
contents: [
|
||||||
|
{
|
||||||
|
inlineData: {
|
||||||
|
data: buffer.toString('base64'),
|
||||||
|
mimeType,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
config: {
|
||||||
|
outputDimensionality: 1536,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const values = response.embeddings?.[0]?.values
|
||||||
|
if (!values) {
|
||||||
|
throw new Error('No embedding values returned from gemini-embedding-2')
|
||||||
|
}
|
||||||
|
|
||||||
|
return values
|
||||||
|
}
|
||||||
|
|
||||||
export async function generateEmbeddingActivity(params: GenerateEmbeddingParams): Promise<{
|
export async function generateEmbeddingActivity(params: GenerateEmbeddingParams): Promise<{
|
||||||
embeddings: GeneratedEmbedding[]
|
embeddings: GeneratedEmbedding[]
|
||||||
usage: Usage
|
usage: Usage
|
||||||
}> {
|
}> {
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- context properties are fetched as JSON from the DB activity
|
// 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
|
const { asset } = params.context as any
|
||||||
|
|
||||||
const config = agent.config as unknown as PrismaJson.AgentConfig
|
|
||||||
if (!config.provider) {
|
|
||||||
throw ApplicationFailure.create({
|
|
||||||
message: 'embedding provider not configured',
|
|
||||||
nonRetryable: true,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
if (!config.model) {
|
|
||||||
throw ApplicationFailure.create({
|
|
||||||
message: 'embedding model not configured',
|
|
||||||
nonRetryable: true,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!asset.mediaType) {
|
if (!asset.mediaType) {
|
||||||
throw ApplicationFailure.create({ message: 'asset has no media type', nonRetryable: true })
|
throw ApplicationFailure.create({ message: 'asset has no media type', nonRetryable: true })
|
||||||
}
|
}
|
||||||
|
|
||||||
const p = providerFactory(config.provider, dbProvider.config as PrismaJson.AiProviderSettings)
|
const apiKey = process.env.GEMINI_API_KEY
|
||||||
|
if (!apiKey) {
|
||||||
|
throw ApplicationFailure.create({
|
||||||
|
message: 'GEMINI_API_KEY environment variable is not configured',
|
||||||
|
nonRetryable: true,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const resolvedApiKey = process.env[apiKey] || apiKey
|
||||||
|
const ai = new GoogleGenAI({ apiKey: resolvedApiKey })
|
||||||
|
|
||||||
const usage: Usage = {
|
const usage: Usage = {
|
||||||
model: config.model,
|
model: 'gemini-embedding-2',
|
||||||
inputTokens: 0,
|
inputTokens: 0,
|
||||||
outputTokens: 0,
|
outputTokens: 0,
|
||||||
}
|
}
|
||||||
@@ -120,7 +107,7 @@ export async function generateEmbeddingActivity(params: GenerateEmbeddingParams)
|
|||||||
const results: GeneratedEmbedding[] = []
|
const results: GeneratedEmbedding[] = []
|
||||||
|
|
||||||
if (isImage) {
|
if (isImage) {
|
||||||
const embVec = await p.generateImageEmbedding(config.model, data)
|
const embVec = await generateMultimodalEmbedding(ai, data, asset.mediaType)
|
||||||
results.push({ embedding: embVec })
|
results.push({ embedding: embVec })
|
||||||
} else if (isVideo) {
|
} else if (isVideo) {
|
||||||
const tmpFile = path.join(os.tmpdir(), `video-${Date.now()}.mp4`)
|
const tmpFile = path.join(os.tmpdir(), `video-${Date.now()}.mp4`)
|
||||||
@@ -152,7 +139,7 @@ export async function generateEmbeddingActivity(params: GenerateEmbeddingParams)
|
|||||||
fs.unlinkSync(chunkTmp)
|
fs.unlinkSync(chunkTmp)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const embVec = await p.generateVideoEmbedding(config.model, chunkData)
|
const embVec = await generateMultimodalEmbedding(ai, chunkData, 'video/mp4')
|
||||||
results.push({ embedding: embVec, startTime: start, endTime: end })
|
results.push({ embedding: embVec, startTime: start, endTime: end })
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
|
|||||||
@@ -463,20 +463,6 @@ export async function getEmbeddingContextActivity(params: GetEmbeddingContextPar
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
const config = agent.config as unknown as PrismaJson.AgentConfig
|
|
||||||
if (!config.provider) {
|
|
||||||
throw ApplicationFailure.create({
|
|
||||||
message: 'embedding provider not configured',
|
|
||||||
nonRetryable: true,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
if (!config.model) {
|
|
||||||
throw ApplicationFailure.create({
|
|
||||||
message: 'embedding model not configured',
|
|
||||||
nonRetryable: true,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
const asset = await prisma.asset.findUnique({
|
const asset = await prisma.asset.findUnique({
|
||||||
where: { id: params.assetId },
|
where: { id: params.assetId },
|
||||||
include: { storageKey: true },
|
include: { storageKey: true },
|
||||||
@@ -488,20 +474,9 @@ export async function getEmbeddingContextActivity(params: GetEmbeddingContextPar
|
|||||||
throw ApplicationFailure.create({ message: 'asset has no media type', nonRetryable: true })
|
throw ApplicationFailure.create({ message: 'asset has no media type', nonRetryable: true })
|
||||||
}
|
}
|
||||||
|
|
||||||
const dbProvider = await prisma.provider.findFirst({
|
|
||||||
where: { teamId: params.teamId, name: config.provider },
|
|
||||||
})
|
|
||||||
if (!dbProvider) {
|
|
||||||
throw ApplicationFailure.create({
|
|
||||||
message: `Provider ${config.provider} not found in database`,
|
|
||||||
nonRetryable: true,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
agent,
|
agent,
|
||||||
asset,
|
asset,
|
||||||
dbProvider,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user