Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

💄 style: support video input for SiliconCloud provider (#9988)

WangYK473bc4e00505
diff --git a/docs/self-hosting/environment-variables/s3.mdx b/docs/self-hosting/environment-variables/s3.mdx
index 8c1eb9cd85b..2fc97b05631 100644
--- a/docs/self-hosting/environment-variables/s3.mdx
+++ b/docs/self-hosting/environment-variables/s3.mdx
@@ -86,3 +86,12 @@ When set to `1`, LobeHub will convert images to base64 encoding before uploading
```log
Route: [xai] ProviderBizError: Fetching images over plain http:// is not supported.
```
+
+### `LLM_VISION_VIDEO_USE_BASE64`
+
+- Type: Optional
+- Description: Set to `1` to use base64 encoding for video upload.
+- Default: undefined
+- Example: `1`
+
+When set to `1`, LobeChat will convert videos to base64 encoding before uploading them to the LLM model.
diff --git a/docs/self-hosting/environment-variables/s3.zh-CN.mdx b/docs/self-hosting/environment-variables/s3.zh-CN.mdx
index 9c44e6a8074..0a5f58f5f6a 100644
--- a/docs/self-hosting/environment-variables/s3.zh-CN.mdx
+++ b/docs/self-hosting/environment-variables/s3.zh-CN.mdx
@@ -84,3 +84,12 @@ LobeHub 支持多模态的 AI 会话,包括将图片、文件等非结构化
```log
Route: [xai] ProviderBizError: Fetching images over plain http:// is not supported.
```
+
+### `LLM_VISION_VIDEO_USE_BASE64`
+
+- 类型:可选
+- 描述:设置为 1 则使用 base64 编码上传视频
+- 默认值:undefined
+- 示例:`1`
+
+当设置为 `1` 时,LobeChat 会将视频转换为 base64 编码后上传到 LLM 模型中。
diff --git a/packages/model-bank/src/aiModels/siliconcloud.ts b/packages/model-bank/src/aiModels/siliconcloud.ts
index b44cde10077..15cb8e521fa 100644
--- a/packages/model-bank/src/aiModels/siliconcloud.ts
+++ b/packages/model-bank/src/aiModels/siliconcloud.ts
@@ -155,6 +155,30 @@ const siliconcloudChatModels: AIChatModelCard[] = [
functionCall: true,
reasoning: true,
vision: true,
+ video: true,
+ },
+ contextWindowTokens: 131_072,
+ description:
+ 'GLM-4.6V achieves SOTA visual understanding accuracy for its parameter scale and is the first to natively integrate Function Call capabilities into the vision model architecture, bridging the gap from "visual perception" to "executable actions" and providing a unified technical foundation for multimodal agents in real business scenarios. The visual context window is extended to 128k, supporting long video stream processing and high-resolution multi-image analysis.',
+ displayName: 'GLM-4.6V',
+ id: 'zai-org/GLM-4.6V',
+ pricing: {
+ currency: 'CNY',
+ units: [
+ { name: 'textInput', rate: 1, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'textOutput', rate: 3, strategy: 'fixed', unit: 'millionTokens' },
+ ],
+ },
+ releasedAt: '2025-12-08',
+ settings: {
+ extendParams: ['reasoningBudgetToken'],
+ },
+ type: 'chat',
+ },
+ {
+ abilities: {
+ functionCall: true,
+ reasoning: true,
},
contextWindowTokens: 262_144,
description:
@@ -407,6 +431,7 @@ const siliconcloudChatModels: AIChatModelCard[] = [
{
abilities: {
functionCall: true,
+ video: true,
vision: true,
},
contextWindowTokens: 65_536,
@@ -428,6 +453,7 @@ const siliconcloudChatModels: AIChatModelCard[] = [
abilities: {
functionCall: true,
reasoning: true,
+ video: true,
vision: true,
},
contextWindowTokens: 65_536,
@@ -451,6 +477,7 @@ const siliconcloudChatModels: AIChatModelCard[] = [
{
abilities: {
functionCall: true,
+ video: true,
vision: true,
},
contextWindowTokens: 65_536,
@@ -568,6 +595,7 @@ const siliconcloudChatModels: AIChatModelCard[] = [
{
abilities: {
functionCall: true,
+ video: true,
vision: true,
},
contextWindowTokens: 256_000,
@@ -588,6 +616,7 @@ const siliconcloudChatModels: AIChatModelCard[] = [
abilities: {
functionCall: true,
reasoning: true,
+ video: true,
vision: true,
},
contextWindowTokens: 256_000,
@@ -607,6 +636,7 @@ const siliconcloudChatModels: AIChatModelCard[] = [
{
abilities: {
functionCall: true,
+ video: true,
vision: true,
},
contextWindowTokens: 256_000,
@@ -627,6 +657,7 @@ const siliconcloudChatModels: AIChatModelCard[] = [
abilities: {
functionCall: true,
reasoning: true,
+ video: true,
vision: true,
},
contextWindowTokens: 256_000,
@@ -690,6 +721,7 @@ const siliconcloudChatModels: AIChatModelCard[] = [
{
abilities: {
functionCall: true,
+ video: true,
vision: true,
},
contextWindowTokens: 256_000,
@@ -712,6 +744,7 @@ const siliconcloudChatModels: AIChatModelCard[] = [
abilities: {
functionCall: true,
reasoning: true,
+ video: true,
vision: true,
},
contextWindowTokens: 256_000,
@@ -1196,30 +1229,6 @@ const siliconcloudChatModels: AIChatModelCard[] = [
},
type: 'chat',
},
- {
- abilities: {
- functionCall: true,
- reasoning: true,
- },
- contextWindowTokens: 131_072,
- description:
- 'Qwen3 is a next-gen Tongyi Qwen model with major gains in reasoning, general ability, agent capability, and multilingual performance, and supports switching thinking modes.',
- displayName: 'Qwen3 30B A3B',
- id: 'Qwen/Qwen3-30B-A3B',
- organization: 'Qwen',
- pricing: {
- currency: 'CNY',
- units: [
- { name: 'textInput', rate: 0.7, strategy: 'fixed', unit: 'millionTokens' },
- { name: 'textOutput', rate: 2.8, strategy: 'fixed', unit: 'millionTokens' },
- ],
- },
- releasedAt: '2025-04-28',
- settings: {
- extendParams: ['enableReasoning', 'reasoningBudgetToken'],
- },
- type: 'chat',
- },
{
abilities: {
functionCall: true,
@@ -1308,28 +1317,6 @@ const siliconcloudChatModels: AIChatModelCard[] = [
releasedAt: '2025-07-02',
type: 'chat',
},
- {
- abilities: {
- reasoning: true,
- },
- contextWindowTokens: 131_072,
- description:
- 'GLM-Z1-Rumination-32B-0414 is a deep reasoning model with rumination capabilities (benchmarked against OpenAI Deep Research). Unlike typical deep-thinking models, it spends longer deliberation to solve more open and complex problems.',
- displayName: 'GLM-Z1-Rumination 32B 0414',
- id: 'THUDM/GLM-Z1-Rumination-32B-0414',
- pricing: {
- currency: 'CNY',
- units: [
- { name: 'textInput', rate: 1, strategy: 'fixed', unit: 'millionTokens' },
- { name: 'textOutput', rate: 4, strategy: 'fixed', unit: 'millionTokens' },
- ],
- },
- releasedAt: '2025-04-14',
- settings: {
- extendParams: ['reasoningBudgetToken'],
- },
- type: 'chat',
- },
{
abilities: {
functionCall: true,
diff --git a/packages/model-runtime/src/core/contextBuilders/siliconcloud.test.ts b/packages/model-runtime/src/core/contextBuilders/siliconcloud.test.ts
new file mode 100644
index 00000000000..c8a72257316
--- /dev/null
+++ b/packages/model-runtime/src/core/contextBuilders/siliconcloud.test.ts
@@ -0,0 +1,170 @@
+/// <reference types="vitest" />
+import { videoUrlToBase64 } from '@lobechat/utils/videoToBase64';
+import OpenAI from 'openai';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { convertSiliconCloudMessageContent, transformSiliconCloudMessages } from './siliconcloud';
+
+// Mock videoUrlToBase64
+vi.mock('@lobechat/utils/videoToBase64', () => ({
+ videoUrlToBase64: vi.fn(),
+}));
+
+describe('siliconcloud context builder', () => {
+ const originalEnv = process.env;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ process.env = { ...originalEnv };
+ });
+
+ describe('convertSiliconCloudMessageContent', () => {
+ it('should return content unchanged when not video_url', async () => {
+ const content: OpenAI.ChatCompletionContentPart = {
+ type: 'text',
+ text: 'Hello world',
+ };
+
+ const result = await convertSiliconCloudMessageContent(content);
+ expect(result).toBe(content);
+ });
+
+ it('should return base64 content unchanged', async () => {
+ const content: any = {
+ type: 'video_url',
+ video_url: {
+ url: 'data:video/mp4;base64,somebase64data',
+ },
+ };
+
+ const result = await convertSiliconCloudMessageContent(content);
+ expect(result).toBe(content);
+ });
+
+ it('should return URL content unchanged when env is not set', async () => {
+ delete process.env.LLM_VISION_VIDEO_USE_BASE64;
+
+ const content: any = {
+ type: 'video_url',
+ video_url: {
+ url: 'https://example.com/video.mp4',
+ },
+ };
+
+ const result = await convertSiliconCloudMessageContent(content);
+ expect(result).toBe(content);
+ });
+
+ it('should return URL content unchanged when env is not 1', async () => {
+ process.env.LLM_VISION_VIDEO_USE_BASE64 = '0';
+
+ const content: any = {
+ type: 'video_url',
+ video_url: {
+ url: 'https://example.com/video.mp4',
+ },
+ };
+
+ const result = await convertSiliconCloudMessageContent(content);
+ expect(result).toBe(content);
+ });
+
+ it('should convert video URL to base64 when env is 1', async () => {
+ process.env.LLM_VISION_VIDEO_USE_BASE64 = '1';
+
+ vi.mocked(videoUrlToBase64).mockResolvedValue({
+ base64: 'mockBase64Data',
+ mimeType: 'video/mp4',
+ });
+
+ const content: any = {
+ type: 'video_url',
+ video_url: {
+ url: 'https://example.com/video.mp4',
+ },
+ };
+
+ const result = await convertSiliconCloudMessageContent(content);
+
+ expect(videoUrlToBase64).toHaveBeenCalledWith('https://example.com/video.mp4');
+ expect((result as any).video_url.url).toBe('data:video/mp4;base64,mockBase64Data');
+ });
+
+ it('should return original content when conversion fails', async () => {
+ process.env.LLM_VISION_VIDEO_USE_BASE64 = '1';
+
+ vi.mocked(videoUrlToBase64).mockRejectedValue(new Error('Conversion error'));
+
+ const content: any = {
+ type: 'video_url',
+ video_url: {
+ url: 'https://example.com/video.mp4',
+ },
+ };
+
+ const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ const result = await convertSiliconCloudMessageContent(content);
+
+ expect(result).toBe(content);
+ expect(consoleWarnSpy).toHaveBeenCalledWith(
+ 'Failed to convert video to base64:',
+ expect.any(Error),
+ );
+
+ consoleWarnSpy.mockRestore();
+ });
+ });
+
+ describe('transformSiliconCloudMessages', () => {
+ it('should transform messages with video content', async () => {
+ process.env.LLM_VISION_VIDEO_USE_BASE64 = '1';
+
+ vi.mocked(videoUrlToBase64).mockResolvedValue({
+ base64: 'mockBase64Data',
+ mimeType: 'video/mp4',
+ });
+
+ const messages: OpenAI.ChatCompletionMessageParam[] = [
+ {
+ role: 'user',
+ content: [
+ {
+ type: 'text',
+ text: 'Please analyze this video',
+ } as OpenAI.ChatCompletionContentPart,
+ {
+ type: 'video_url',
+ video_url: {
+ url: 'https://example.com/video.mp4',
+ },
+ } as any,
+ ],
+ },
+ ];
+
+ const result = await transformSiliconCloudMessages(messages);
+
+ expect(result).toHaveLength(1);
+ expect(result[0].content).toHaveLength(2);
+ expect((result[0].content as any[])[1].video_url.url).toBe(
+ 'data:video/mp4;base64,mockBase64Data',
+ );
+ expect(videoUrlToBase64).toHaveBeenCalledWith('https://example.com/video.mp4');
+ });
+
+ it('should handle string content unchanged', async () => {
+ const messages: OpenAI.ChatCompletionMessageParam[] = [
+ {
+ role: 'user',
+ content: 'Hello world',
+ },
+ ];
+
+ const result = await transformSiliconCloudMessages(messages);
+
+ expect(result).toHaveLength(1);
+ expect(result[0].content).toBe('Hello world');
+ });
+ });
+});
diff --git a/packages/model-runtime/src/core/contextBuilders/siliconcloud.ts b/packages/model-runtime/src/core/contextBuilders/siliconcloud.ts
new file mode 100644
index 00000000000..cbaeea2e384
--- /dev/null
+++ b/packages/model-runtime/src/core/contextBuilders/siliconcloud.ts
@@ -0,0 +1,60 @@
+import { videoUrlToBase64 } from '@lobechat/utils/videoToBase64';
+import OpenAI from 'openai';
+
+import { parseDataUri } from '../../utils/uriParser';
+
+interface SiliconCloudChatCompletionContentPartVideo {
+ type: 'video_url';
+ video_url: {
+ url: string;
+ };
+}
+
+type SiliconCloudChatCompletionContentPart =
+ | OpenAI.ChatCompletionContentPart
+ | SiliconCloudChatCompletionContentPartVideo;
+
+export const convertSiliconCloudMessageContent = async (
+ content: SiliconCloudChatCompletionContentPart,
+) => {
+ if (content.type === 'video_url') {
+ const { type } = parseDataUri(content.video_url.url);
+
+ if (type === 'url' && process.env.LLM_VISION_VIDEO_USE_BASE64 === '1') {
+ try {
+ const { base64, mimeType } = await videoUrlToBase64(content.video_url.url);
+
+ return {
+ ...content,
+ video_url: { ...content.video_url, url: `data:${mimeType};base64,${base64}` },
+ };
+ } catch (error) {
+ console.warn('Failed to convert video to base64:', error);
+ // Return original content if conversion fails
+ return content;
+ }
+ }
+ }
+
+ return content;
+};
+
+export const transformSiliconCloudMessages = async (
+ messages: OpenAI.ChatCompletionMessageParam[],
+): Promise<OpenAI.ChatCompletionMessageParam[]> => {
+ return (await Promise.all(
+ messages.map(async (message) => ({
+ ...message,
+ content:
+ typeof message.content === 'string'
+ ? message.content
+ : await Promise.all(
+ (message.content || []).map((c) => {
+ return convertSiliconCloudMessageContent(
+ c as SiliconCloudChatCompletionContentPart,
+ );
+ }),
+ ),
+ })),
+ )) as OpenAI.ChatCompletionMessageParam[];
+};
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
index 0a97d0a6438..2cf63a54da7 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
@@ -111,6 +111,12 @@ export interface OpenAICompatibleFactoryOptions<T extends Record<string, any> =
data: OpenAI.ChatCompletion,
) => ReadableStream<OpenAI.ChatCompletionChunk>;
noUserId?: boolean;
+ /**
+ * Custom message converter for provider-specific message transformations
+ */
+ transformMessages?: (
+ messages: OpenAI.ChatCompletionMessageParam[],
+ ) => Promise<OpenAI.ChatCompletionMessageParam[]> | OpenAI.ChatCompletionMessageParam[];
/**
* If true, route chat requests to Responses API path directly
*/
@@ -425,9 +431,11 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
this.baseURL = targetBaseURL;
}
- const messages = await convertOpenAIMessages(postPayload.messages, {
- forceImageBase64: chatCompletion?.forceImageBase64,
- });
+ const messages = chatCompletion?.transformMessages
+ ? await chatCompletion.transformMessages(postPayload.messages)
+ : await convertOpenAIMessages(postPayload.messages, {
+ forceImageBase64: chatCompletion?.forceImageBase64,
+ });
let response: Stream<OpenAI.Chat.Completions.ChatCompletionChunk>;
diff --git a/packages/model-runtime/src/providers/siliconcloud/index.ts b/packages/model-runtime/src/providers/siliconcloud/index.ts
index b5eb9302d62..af575b0ac38 100644
--- a/packages/model-runtime/src/providers/siliconcloud/index.ts
+++ b/packages/model-runtime/src/providers/siliconcloud/index.ts
@@ -1,5 +1,6 @@
import { ModelProvider } from 'model-bank';
+import { transformSiliconCloudMessages } from '../../core/contextBuilders/siliconcloud';
import type { OpenAICompatibleFactoryOptions } from '../../core/openaiCompatibleFactory';
import { createOpenAICompatibleRuntime } from '../../core/openaiCompatibleFactory';
import type { ChatCompletionErrorPayload } from '../../types';
@@ -68,8 +69,7 @@ export const params = {
return {
error: status,
errorType: AgentRuntimeErrorType.ProviderBizError,
- message:
- '请检查 API Key 余额是否充足,或者是否在用未实名的 API Key 访问需要实名的模型。',
+ message: '请检查 API Key 余额是否充足,或者是否在用未实名的 API Key 访问需要实名的模型。',
};
}
@@ -115,6 +115,7 @@ export const params = {
}
return result;
},
+ transformMessages: transformSiliconCloudMessages,
},
constructorOptions: {
fetch: siliconFetch,
diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts
index bc208b09fba..cb034a47038 100644
--- a/packages/utils/src/index.ts
+++ b/packages/utils/src/index.ts
@@ -21,3 +21,4 @@ export * from './sleep';
export * from './uriParser';
export * from './url';
export * from './uuid';
+export * from './videoToBase64';
diff --git a/packages/utils/src/videoToBase64.test.ts b/packages/utils/src/videoToBase64.test.ts
new file mode 100644
index 00000000000..d83aebc516d
--- /dev/null
+++ b/packages/utils/src/videoToBase64.test.ts
@@ -0,0 +1,176 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { videoUrlToBase64 } from './videoToBase64';
+
+// Mock @lobechat/ssrf-safe-fetch module
+const mockSsrfSafeFetch = vi.fn();
+vi.mock('@lobechat/ssrf-safe-fetch', () => ({
+ ssrfSafeFetch: mockSsrfSafeFetch,
+}));
+
+describe('videoUrlToBase64', () => {
+ const originalWindow = global.window;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ // Mock server environment by removing window
+ // @ts-ignore
+ delete global.window;
+ });
+
+ afterEach(() => {
+ // Restore window
+ global.window = originalWindow;
+ });
+
+ it('should convert video URL to base64 successfully', async () => {
+ const mockArrayBuffer = new ArrayBuffer(16);
+ const mockResponse = {
+ ok: true,
+ status: 200,
+ headers: {
+ get: vi.fn().mockReturnValue('video/mp4'),
+ },
+ arrayBuffer: vi.fn().mockResolvedValue(mockArrayBuffer),
+ };
+
+ mockSsrfSafeFetch.mockResolvedValue(mockResponse);
+
+ const result = await videoUrlToBase64('https://example.com/video.mp4');
+
+ expect(mockSsrfSafeFetch).toHaveBeenCalledWith(
+ 'https://example.com/video.mp4',
+ expect.objectContaining({
+ signal: expect.any(AbortSignal),
+ }),
+ );
+ expect(result).toEqual({
+ base64: Buffer.from(mockArrayBuffer).toString('base64'),
+ mimeType: 'video/mp4',
+ });
+ });
+
+ it('should handle different video mime types', async () => {
+ const mockArrayBuffer = new ArrayBuffer(16);
+ const mockResponse = {
+ ok: true,
+ status: 200,
+ headers: {
+ get: vi.fn().mockReturnValue('video/webm'),
+ },
+ arrayBuffer: vi.fn().mockResolvedValue(mockArrayBuffer),
+ };
+
+ mockSsrfSafeFetch.mockResolvedValue(mockResponse);
+
+ const result = await videoUrlToBase64('https://example.com/video.webm');
+
+ expect(result.mimeType).toBe('video/webm');
+ });
+
+ it('should throw error when response is not ok', async () => {
+ const mockResponse = {
+ ok: false,
+ status: 404,
+ statusText: 'Not Found',
+ };
+
+ mockSsrfSafeFetch.mockResolvedValue(mockResponse);
+
+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ await expect(videoUrlToBase64('https://example.com/video.mp4')).rejects.toThrow(
+ 'Failed to fetch video: 404 Not Found',
+ );
+
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
+ 'Error converting video to base64:',
+ expect.any(Error),
+ );
+
+ consoleErrorSpy.mockRestore();
+ });
+
+ it('should throw error when content-type is not video', async () => {
+ const mockResponse = {
+ ok: true,
+ status: 200,
+ headers: {
+ get: vi.fn().mockReturnValue('image/png'),
+ },
+ };
+
+ mockSsrfSafeFetch.mockResolvedValue(mockResponse);
+
+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ await expect(videoUrlToBase64('https://example.com/image.png')).rejects.toThrow(
+ 'URL does not point to a valid video file',
+ );
+
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
+ 'Error converting video to base64:',
+ expect.any(Error),
+ );
+
+ consoleErrorSpy.mockRestore();
+ });
+
+ it('should throw error when content-type is missing', async () => {
+ const mockResponse = {
+ ok: true,
+ status: 200,
+ headers: {
+ get: vi.fn().mockReturnValue(null),
+ },
+ };
+
+ mockSsrfSafeFetch.mockResolvedValue(mockResponse);
+
+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ await expect(videoUrlToBase64('https://example.com/file')).rejects.toThrow(
+ 'URL does not point to a valid video file',
+ );
+
+ consoleErrorSpy.mockRestore();
+ });
+
+ it('should throw error when fetch fails', async () => {
+ const mockError = new Error('Network error');
+ mockSsrfSafeFetch.mockRejectedValue(mockError);
+
+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ await expect(videoUrlToBase64('https://example.com/video.mp4')).rejects.toThrow(
+ 'Network error',
+ );
+
+ expect(consoleErrorSpy).toHaveBeenCalledWith('Error converting video to base64:', mockError);
+
+ consoleErrorSpy.mockRestore();
+ });
+
+ it('should use 30 second timeout', async () => {
+ const mockArrayBuffer = new ArrayBuffer(16);
+ const mockResponse = {
+ ok: true,
+ status: 200,
+ headers: {
+ get: vi.fn().mockReturnValue('video/mp4'),
+ },
+ arrayBuffer: vi.fn().mockResolvedValue(mockArrayBuffer),
+ };
+
+ mockSsrfSafeFetch.mockResolvedValue(mockResponse);
+
+ await videoUrlToBase64('https://example.com/video.mp4');
+
+ expect(mockSsrfSafeFetch).toHaveBeenCalledWith(
+ 'https://example.com/video.mp4',
+ expect.objectContaining({
+ signal: expect.any(AbortSignal),
+ }),
+ );
+ });
+});
diff --git a/packages/utils/src/videoToBase64.ts b/packages/utils/src/videoToBase64.ts
new file mode 100644
index 00000000000..54417e6a13b
--- /dev/null
+++ b/packages/utils/src/videoToBase64.ts
@@ -0,0 +1,44 @@
+/**
+ * Convert video URL to base64 data URL with SSRF protection
+ * Uses SSRF-safe fetch to prevent SSRF attacks
+ */
+export const videoUrlToBase64 = async (
+ videoUrl: string,
+): Promise<{ base64: string; mimeType: string }> => {
+ try {
+ const isServer = typeof window === 'undefined';
+
+ // Use SSRF-safe fetch to prevent SSRF attacks
+ const response = isServer
+ ? await import('@lobechat/ssrf-safe-fetch').then((m) =>
+ m.ssrfSafeFetch(videoUrl, {
+ signal: AbortSignal.timeout(30_000), // 30 seconds
+ }),
+ )
+ : await fetch(videoUrl);
+
+ if (!response.ok) {
+ throw new Error(`Failed to fetch video: ${response.status} ${response.statusText}`);
+ }
+
+ const contentType = response.headers.get('content-type');
+ if (!contentType || !contentType.startsWith('video/')) {
+ throw new Error('URL does not point to a valid video file');
+ }
+
+ const arrayBuffer = await response.arrayBuffer();
+ const base64 = isServer
+ ? Buffer.from(arrayBuffer).toString('base64')
+ : btoa(
+ new Uint8Array(arrayBuffer).reduce((data, byte) => data + String.fromCharCode(byte), ''),
+ );
+
+ return {
+ base64,
+ mimeType: contentType,
+ };
+ } catch (error) {
+ console.error('Error converting video to base64:', error);
+ throw error;
+ }
+};