-
Notifications
You must be signed in to change notification settings - Fork 3.6k
Feat/voyageai: adding voyageai integration #4070
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
fzowl
wants to merge
9
commits into
simstudioai:main
Choose a base branch
from
fzowl:feat/voyageai-mongodb-atlas
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+2,725
−0
Open
Changes from 1 commit
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
22662b3
feat: add VoyageAI embeddings/rerank integration and MongoDB Atlas co…
fzowl 3d2cb8e
test: comprehensive unit tests (160), integration tests (13) for Voya…
fzowl 0db15ec
chore: add .playwright-mcp to gitignore
fzowl 1bf99c0
feat: update VoyageAI to latest models (v4, 3.5, rerank-2.5)
fzowl e729a82
feat: add multimodal embeddings (text + image + video) to VoyageAI in…
fzowl 1836124
style: fix code review issues in VoyageAI integration
fzowl 375703b
revert: drop all MongoDB connection string changes
fzowl 604ee02
fix: resolve PR review comments
fzowl 6394764
fix: add response.ok guard to multimodal-embeddings transformResponse
fzowl File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
feat: add multimodal embeddings (text + image + video) to VoyageAI in…
…tegration - New tool: voyageai_multimodal_embeddings using voyage-multimodal-3.5 model - New API route: /api/tools/voyageai/multimodal-embeddings for server-side file handling - Supports text, image files/URLs, video files/URLs in a single embedding - Uses file-upload subBlocks with basic/advanced mode for images and video - Internal proxy pattern: downloads UserFiles via downloadFileFromStorage, converts to base64 - URL validation via validateUrlWithDNS for SSRF protection - 14 new unit tests (tool metadata, body, response transform) - 5 new integration tests (text-only, image URL, text+image, dimensions, auth) - 8 new block tests (multimodal operation, params, subBlocks)
- Loading branch information
commit e729a82dad823eb97cf7d2b029c40eedb5cd15ab
There are no files selected for viewing
211 changes: 211 additions & 0 deletions
211
apps/sim/app/api/tools/voyageai/multimodal-embeddings/route.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,211 @@ | ||
| import { createLogger } from '@sim/logger' | ||
| import { type NextRequest, NextResponse } from 'next/server' | ||
| import { z } from 'zod' | ||
| import { checkInternalAuth } from '@/lib/auth/hybrid' | ||
| import { validateUrlWithDNS } from '@/lib/core/security/input-validation.server' | ||
| import { generateRequestId } from '@/lib/core/utils/request' | ||
| import { RawFileInputArraySchema, RawFileInputSchema } from '@/lib/uploads/utils/file-schemas' | ||
| import { processSingleFileToUserFile } from '@/lib/uploads/utils/file-utils' | ||
| import { downloadFileFromStorage } from '@/lib/uploads/utils/file-utils.server' | ||
|
|
||
| export const dynamic = 'force-dynamic' | ||
|
|
||
| const logger = createLogger('VoyageAIMultimodalAPI') | ||
|
|
||
| const MultimodalEmbeddingsSchema = z.object({ | ||
| apiKey: z.string().min(1, 'API key is required'), | ||
| input: z.string().optional().nullable(), | ||
| imageFiles: z.union([RawFileInputSchema, RawFileInputArraySchema]).optional().nullable(), | ||
| imageUrls: z.string().optional().nullable(), | ||
| videoFile: RawFileInputSchema.optional().nullable(), | ||
| videoUrl: z.string().optional().nullable(), | ||
| model: z.string().optional().default('voyage-multimodal-3.5'), | ||
| inputType: z.enum(['query', 'document']).optional().nullable(), | ||
| }) | ||
|
|
||
| export async function POST(request: NextRequest) { | ||
| const requestId = generateRequestId() | ||
|
|
||
| try { | ||
| const authResult = await checkInternalAuth(request, { requireWorkflowId: false }) | ||
| if (!authResult.success) { | ||
| logger.warn(`[${requestId}] Unauthorized multimodal embeddings attempt`) | ||
| return NextResponse.json( | ||
| { success: false, error: authResult.error || 'Authentication required' }, | ||
| { status: 401 } | ||
| ) | ||
| } | ||
|
|
||
| const body = await request.json() | ||
| const params = MultimodalEmbeddingsSchema.parse(body) | ||
|
|
||
| const content: Array<Record<string, string>> = [] | ||
|
|
||
| // Add text content | ||
| if (params.input?.trim()) { | ||
| content.push({ type: 'text', text: params.input }) | ||
| } | ||
|
|
||
| // Process image files → base64 | ||
| if (params.imageFiles) { | ||
| const files = Array.isArray(params.imageFiles) ? params.imageFiles : [params.imageFiles] | ||
| for (const rawFile of files) { | ||
| try { | ||
| const userFile = processSingleFileToUserFile(rawFile, requestId, logger) | ||
| let base64 = userFile.base64 | ||
| if (!base64) { | ||
| const buffer = await downloadFileFromStorage(userFile, requestId, logger) | ||
| base64 = buffer.toString('base64') | ||
| logger.info(`[${requestId}] Converted image to base64 (${buffer.length} bytes)`) | ||
| } | ||
| const mimeType = userFile.type || 'image/jpeg' | ||
| content.push({ | ||
| type: 'image_base64', | ||
| image_base64: `data:${mimeType};base64,${base64}`, | ||
| }) | ||
| } catch (error) { | ||
| logger.error(`[${requestId}] Failed to process image file:`, error) | ||
| return NextResponse.json( | ||
| { success: false, error: `Failed to process image file: ${error instanceof Error ? error.message : 'Unknown error'}` }, | ||
| { status: 400 } | ||
| ) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Process image URLs | ||
| if (params.imageUrls?.trim()) { | ||
| let urls: string[] | ||
| try { | ||
| urls = JSON.parse(params.imageUrls) | ||
| } catch { | ||
| urls = params.imageUrls | ||
| .split(/[,\n]/) | ||
| .map((u) => u.trim()) | ||
| .filter(Boolean) | ||
| } | ||
|
|
||
| for (const url of urls) { | ||
| const validation = await validateUrlWithDNS(url, 'imageUrl') | ||
| if (!validation.isValid) { | ||
| return NextResponse.json( | ||
| { success: false, error: `Invalid image URL: ${validation.error}` }, | ||
| { status: 400 } | ||
| ) | ||
| } | ||
| content.push({ type: 'image_url', image_url: url }) | ||
| } | ||
| } | ||
|
|
||
| // Process video file → base64 | ||
| if (params.videoFile) { | ||
| try { | ||
| const userFile = processSingleFileToUserFile(params.videoFile, requestId, logger) | ||
| let base64 = userFile.base64 | ||
| if (!base64) { | ||
| const buffer = await downloadFileFromStorage(userFile, requestId, logger) | ||
| base64 = buffer.toString('base64') | ||
| logger.info(`[${requestId}] Converted video to base64 (${buffer.length} bytes)`) | ||
| } | ||
| const mimeType = userFile.type || 'video/mp4' | ||
| content.push({ | ||
| type: 'video_base64', | ||
| video_base64: `data:${mimeType};base64,${base64}`, | ||
| }) | ||
| } catch (error) { | ||
| logger.error(`[${requestId}] Failed to process video file:`, error) | ||
| return NextResponse.json( | ||
| { success: false, error: `Failed to process video file: ${error instanceof Error ? error.message : 'Unknown error'}` }, | ||
| { status: 400 } | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| // Process video URL | ||
| if (params.videoUrl?.trim()) { | ||
| const validation = await validateUrlWithDNS(params.videoUrl, 'videoUrl') | ||
| if (!validation.isValid) { | ||
| return NextResponse.json( | ||
| { success: false, error: `Invalid video URL: ${validation.error}` }, | ||
| { status: 400 } | ||
| ) | ||
| } | ||
| content.push({ type: 'video_url', video_url: params.videoUrl }) | ||
| } | ||
|
|
||
| if (content.length === 0) { | ||
| return NextResponse.json( | ||
| { success: false, error: 'At least one input (text, image, or video) is required' }, | ||
| { status: 400 } | ||
| ) | ||
| } | ||
|
|
||
| logger.info(`[${requestId}] Calling VoyageAI multimodal embeddings`, { | ||
| contentTypes: content.map((c) => c.type), | ||
| model: params.model, | ||
| }) | ||
|
|
||
| // Build VoyageAI request | ||
| const voyageBody: Record<string, unknown> = { | ||
| inputs: [{ content }], | ||
| model: params.model, | ||
| } | ||
| if (params.inputType) { | ||
| voyageBody.input_type = params.inputType | ||
| } | ||
|
|
||
| const voyageResponse = await fetch('https://api.voyageai.com/v1/multimodalembeddings', { | ||
| method: 'POST', | ||
| headers: { | ||
| Authorization: `Bearer ${params.apiKey}`, | ||
| 'Content-Type': 'application/json', | ||
| }, | ||
| body: JSON.stringify(voyageBody), | ||
| }) | ||
|
|
||
| if (!voyageResponse.ok) { | ||
| const errorText = await voyageResponse.text() | ||
| logger.error(`[${requestId}] VoyageAI API error: ${voyageResponse.status}`, { errorText }) | ||
| return NextResponse.json( | ||
| { success: false, error: `VoyageAI API error: ${voyageResponse.status} - ${errorText}` }, | ||
| { status: voyageResponse.status } | ||
| ) | ||
| } | ||
|
|
||
| const data = await voyageResponse.json() | ||
|
|
||
| logger.info(`[${requestId}] Multimodal embeddings generated successfully`, { | ||
| embeddingsCount: data.data?.length, | ||
| totalTokens: data.usage?.total_tokens, | ||
| }) | ||
|
|
||
| return NextResponse.json({ | ||
| success: true, | ||
| output: { | ||
| embeddings: data.data.map((item: { embedding: number[] }) => item.embedding), | ||
| model: data.model, | ||
| usage: { | ||
| text_tokens: data.usage?.text_tokens, | ||
| image_pixels: data.usage?.image_pixels, | ||
| video_pixels: data.usage?.video_pixels, | ||
| total_tokens: data.usage?.total_tokens, | ||
| }, | ||
| }, | ||
| }) | ||
| } catch (error) { | ||
| if (error instanceof z.ZodError) { | ||
| logger.warn(`[${requestId}] Invalid request data`, { errors: error.errors }) | ||
| return NextResponse.json( | ||
| { success: false, error: 'Invalid request data', details: error.errors }, | ||
| { status: 400 } | ||
| ) | ||
| } | ||
|
|
||
| const errorMessage = error instanceof Error ? error.message : 'Unknown error' | ||
| logger.error(`[${requestId}] Multimodal embeddings failed:`, error) | ||
| return NextResponse.json( | ||
| { success: false, error: `Multimodal embeddings failed: ${errorMessage}` }, | ||
| { status: 500 } | ||
| ) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.