feat: add initial model provider adapters
This commit is contained in:
1 parent
7f35960ba6
commit
547f7c0977
16 files changed
+577
-21
No files matched your search
@@ -0,0 +1,67 @@
|
||||
export interface OpenAICompatibleMessage {
|
||||
role: string
|
||||
content: unknown
|
||||
}
|
||||
|
||||
export interface OpenAICompatibleResponse {
|
||||
id?: string
|
||||
object?: string
|
||||
created?: number
|
||||
model?: string
|
||||
choices?: Array<{ index?: number; message?: { role?: string; content?: string }; finish_reason?: string | null }>
|
||||
usage?: { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number }
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export interface OpenAICompatibleProviderOptions {
|
||||
providerName: string
|
||||
apiKey: string
|
||||
baseUrl: string
|
||||
timeoutMs?: number
|
||||
fetcher?: typeof fetch
|
||||
}
|
||||
|
||||
export class OpenAICompatibleProviderError extends Error {
|
||||
constructor(message: string, readonly statusCode?: number) {
|
||||
super(message)
|
||||
}
|
||||
}
|
||||
|
||||
export class OpenAICompatibleProvider {
|
||||
private readonly baseUrl: string
|
||||
private readonly timeoutMs: number
|
||||
private readonly fetcher: typeof fetch
|
||||
|
||||
constructor(private readonly options: OpenAICompatibleProviderOptions) {
|
||||
if (!options.apiKey.trim()) throw new OpenAICompatibleProviderError(`${options.providerName} API Key 未配置`)
|
||||
this.baseUrl = options.baseUrl.replace(/\/$/, '')
|
||||
this.timeoutMs = options.timeoutMs ?? 45_000
|
||||
this.fetcher = options.fetcher || fetch
|
||||
}
|
||||
|
||||
async chatCompletion(input: { model: string; messages: OpenAICompatibleMessage[]; stream?: boolean }) {
|
||||
const controller = new AbortController()
|
||||
const timer = setTimeout(() => controller.abort(), this.timeoutMs)
|
||||
try {
|
||||
const response = await this.fetcher(`${this.baseUrl}/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
Authorization: `Bearer ${this.options.apiKey}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ model: input.model, messages: input.messages, stream: input.stream ?? false }),
|
||||
signal: controller.signal,
|
||||
})
|
||||
const payload = await response.json().catch(() => ({})) as OpenAICompatibleResponse & { error?: { message?: string } }
|
||||
if (!response.ok) throw new OpenAICompatibleProviderError(payload.error?.message || `${this.options.providerName} 请求失败(HTTP ${response.status})`, response.status)
|
||||
return payload
|
||||
} catch (error) {
|
||||
if (error instanceof OpenAICompatibleProviderError) throw error
|
||||
if (error instanceof Error && error.name === 'AbortError') throw new OpenAICompatibleProviderError(`${this.options.providerName} 请求超时`)
|
||||
throw new OpenAICompatibleProviderError(error instanceof Error ? error.message : `${this.options.providerName} 请求失败`)
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
export type SeedanceTaskStatus = 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelled'
|
||||
|
||||
export interface SeedanceTask {
|
||||
id: string
|
||||
model?: string
|
||||
status: string
|
||||
created_at?: string | number
|
||||
updated_at?: string | number
|
||||
content?: { video_url?: string }
|
||||
error?: { code?: string | number; message?: string }
|
||||
usage?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export interface SeedanceProviderOptions {
|
||||
apiKey: string
|
||||
baseUrl?: string
|
||||
timeoutMs?: number
|
||||
fetcher?: typeof fetch
|
||||
}
|
||||
|
||||
export interface SeedanceTaskView {
|
||||
id: string
|
||||
provider: 'seedance'
|
||||
status: SeedanceTaskStatus
|
||||
progress: number
|
||||
model?: string
|
||||
output?: { videoUrl?: string }
|
||||
error?: { code?: string | number; message?: string }
|
||||
createdAt?: string
|
||||
updatedAt?: string
|
||||
}
|
||||
|
||||
export class SeedanceProviderError extends Error {
|
||||
constructor(message: string, readonly statusCode?: number) {
|
||||
super(message)
|
||||
}
|
||||
}
|
||||
|
||||
export class SeedanceProvider {
|
||||
private readonly baseUrl: string
|
||||
private readonly timeoutMs: number
|
||||
private readonly fetcher: typeof fetch
|
||||
|
||||
constructor(private readonly options: SeedanceProviderOptions) {
|
||||
if (!options.apiKey.trim()) throw new SeedanceProviderError('Seedance API Key 未配置')
|
||||
this.baseUrl = (options.baseUrl || 'https://ark.cn-beijing.volces.com/api/v3').replace(/\/$/, '')
|
||||
this.timeoutMs = options.timeoutMs ?? 60_000
|
||||
this.fetcher = options.fetcher || fetch
|
||||
}
|
||||
|
||||
async createTextToVideo(input: { model: string; prompt: string }) {
|
||||
const prompt = input.prompt.trim()
|
||||
if (!prompt) throw new SeedanceProviderError('Seedance 提示词不能为空')
|
||||
const response = await this.request<SeedanceTask>('/contents/generations/tasks', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ model: input.model, content: [{ type: 'text', text: prompt }] }),
|
||||
})
|
||||
if (!response.id) throw new SeedanceProviderError('Seedance 未返回任务 ID')
|
||||
return response.id
|
||||
}
|
||||
|
||||
async getTask(taskId: string): Promise<SeedanceTaskView> {
|
||||
if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{7,127}$/.test(taskId)) throw new SeedanceProviderError('Seedance task ID 格式无效')
|
||||
const task = await this.request<SeedanceTask>(`/contents/generations/tasks/${encodeURIComponent(taskId)}`)
|
||||
return mapSeedanceTask(task)
|
||||
}
|
||||
|
||||
private async request<T>(path: string, init: { method?: string; body?: string } = {}) {
|
||||
const controller = new AbortController()
|
||||
const timer = setTimeout(() => controller.abort(), this.timeoutMs)
|
||||
try {
|
||||
const response = await this.fetcher(`${this.baseUrl}${path}`, {
|
||||
method: init.method || 'GET',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
Authorization: `Bearer ${this.options.apiKey}`,
|
||||
...(init.body ? { 'Content-Type': 'application/json' } : {}),
|
||||
},
|
||||
...(init.body ? { body: init.body } : {}),
|
||||
signal: controller.signal,
|
||||
})
|
||||
const payload = await response.json().catch(() => ({})) as T & { error?: { message?: string } }
|
||||
if (!response.ok) throw new SeedanceProviderError(payload.error?.message || `Seedance 请求失败(HTTP ${response.status})`, response.status)
|
||||
return payload as T
|
||||
} catch (error) {
|
||||
if (error instanceof SeedanceProviderError) throw error
|
||||
if (error instanceof Error && error.name === 'AbortError') throw new SeedanceProviderError('Seedance 请求超时')
|
||||
throw new SeedanceProviderError(error instanceof Error ? error.message : 'Seedance 请求失败')
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function isoDate(value?: string | number) {
|
||||
if (value === undefined) return undefined
|
||||
const numeric = typeof value === 'number' || /^\d+$/.test(value) ? Number(value) : NaN
|
||||
const date = Number.isFinite(numeric) ? new Date(numeric < 10_000_000_000 ? numeric * 1000 : numeric) : new Date(value)
|
||||
return Number.isNaN(date.getTime()) ? undefined : date.toISOString()
|
||||
}
|
||||
|
||||
export function mapSeedanceTask(task: SeedanceTask): SeedanceTaskView {
|
||||
const statusText = task.status.toLowerCase()
|
||||
const status: SeedanceTaskStatus = statusText === 'succeeded' || statusText === 'success' ? 'succeeded' : statusText === 'failed' ? 'failed' : statusText === 'cancelled' || statusText === 'canceled' ? 'cancelled' : statusText === 'running' ? 'running' : 'queued'
|
||||
const createdAt = isoDate(task.created_at)
|
||||
const updatedAt = isoDate(task.updated_at)
|
||||
return {
|
||||
id: task.id,
|
||||
provider: 'seedance',
|
||||
status,
|
||||
progress: status === 'succeeded' ? 100 : status === 'running' ? 50 : 0,
|
||||
...(task.model ? { model: task.model } : {}),
|
||||
...(task.content?.video_url ? { output: { videoUrl: task.content.video_url } } : {}),
|
||||
...(task.error ? { error: task.error } : {}),
|
||||
...(createdAt ? { createdAt } : {}),
|
||||
...(updatedAt ? { updatedAt } : {}),
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user