mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-23 01:20:04 +00:00
refactor(ai): remove generic providers and hardcode gemini-embedding-2 in embedding activity
This commit is contained in:
@@ -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 { type AgentTool } from '@earendil-works/pi-agent-core'
|
||||
import { type ImageContent } from '@earendil-works/pi-ai'
|
||||
import { type Usage } from '@/services/ai/provider/provider'
|
||||
import { ApplicationFailure } from '@temporalio/activity'
|
||||
|
||||
export interface Usage {
|
||||
inputTokens: number
|
||||
outputTokens: number
|
||||
model: string
|
||||
}
|
||||
import type { Prisma, Skill } from '@/generated/prisma/client'
|
||||
|
||||
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 {
|
||||
GeminiProvider: class {
|
||||
generateImageEmbedding = vi.fn().mockResolvedValue([0.1, 0.2, 0.3])
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
GoogleGenAI: class {
|
||||
models = {
|
||||
embedContent: mockEmbedContent,
|
||||
}
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
import { ElevenLabsProvider } from '@/services/ai/provider/elevenlabs'
|
||||
import { GeminiProvider } from '@/services/ai/provider/gemini'
|
||||
import { OpenAiProvider } from '@/services/ai/provider/openai'
|
||||
import { Provider, Usage } from '@/services/ai/provider/provider'
|
||||
import { AiProvider } from '@/dtos/ai'
|
||||
import { GoogleGenAI } from '@google/genai'
|
||||
import { s3Service } from '@/services/s3/s3'
|
||||
import { transcodeService } from '@/transcode/transcode'
|
||||
import { exec } from 'child_process'
|
||||
@@ -14,41 +10,10 @@ import { ApplicationFailure } from '@temporalio/activity'
|
||||
|
||||
const execAsync = promisify(exec)
|
||||
|
||||
function providerFactory(providerName: string, config: PrismaJson.AiProviderSettings): Provider {
|
||||
let pKey: AiProvider
|
||||
switch (providerName) {
|
||||
case AiProvider.Google:
|
||||
pKey = AiProvider.Google
|
||||
break
|
||||
case AiProvider.OpenAi:
|
||||
pKey = AiProvider.OpenAi
|
||||
break
|
||||
case AiProvider.ElevenLabs:
|
||||
pKey = AiProvider.ElevenLabs
|
||||
break
|
||||
default:
|
||||
throw 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 Usage {
|
||||
inputTokens: number
|
||||
outputTokens: number
|
||||
model: string
|
||||
}
|
||||
|
||||
export interface GeneratedEmbedding {
|
||||
@@ -67,35 +32,55 @@ export interface GenerateEmbeddingParams {
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
},
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
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<{
|
||||
embeddings: GeneratedEmbedding[]
|
||||
usage: Usage
|
||||
}> {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- context properties are fetched as JSON from the DB activity
|
||||
const { agent, asset, dbProvider } = params.context as any
|
||||
|
||||
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, dbProvider } = params.context as any
|
||||
|
||||
if (!asset.mediaType) {
|
||||
throw ApplicationFailure.create({ message: 'asset has no media type', nonRetryable: true })
|
||||
}
|
||||
|
||||
const p = providerFactory(config.provider, dbProvider.config as PrismaJson.AiProviderSettings)
|
||||
const apiKey = dbProvider?.config?.apiKey
|
||||
if (!apiKey) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Google GenAI apiKey not found in provider config',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const resolvedApiKey = process.env[apiKey] || apiKey
|
||||
const ai = new GoogleGenAI({ apiKey: resolvedApiKey })
|
||||
|
||||
const usage: Usage = {
|
||||
model: config.model,
|
||||
model: 'gemini-embedding-2',
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
@@ -120,7 +105,7 @@ export async function generateEmbeddingActivity(params: GenerateEmbeddingParams)
|
||||
const results: GeneratedEmbedding[] = []
|
||||
|
||||
if (isImage) {
|
||||
const embVec = await p.generateImageEmbedding(config.model, data)
|
||||
const embVec = await generateMultimodalEmbedding(ai, data, asset.mediaType)
|
||||
results.push({ embedding: embVec })
|
||||
} else if (isVideo) {
|
||||
const tmpFile = path.join(os.tmpdir(), `video-${Date.now()}.mp4`)
|
||||
@@ -152,7 +137,7 @@ export async function generateEmbeddingActivity(params: GenerateEmbeddingParams)
|
||||
fs.unlinkSync(chunkTmp)
|
||||
|
||||
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 })
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} catch (e: any) {
|
||||
|
||||
Reference in New Issue
Block a user