feat: integrate Tripo 3D provider
This commit is contained in:
1 parent
ec51e8c802
commit
18a55346c6
9 files changed
+306
-6
No files matched your search
@@ -0,0 +1,174 @@
|
||||
export type TripoTaskStatus = 'queued' | 'running' | 'success' | 'failed' | 'cancelled'
|
||||
|
||||
export interface TripoTaskOutput {
|
||||
model_url?: string
|
||||
rendered_image_url?: string
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export interface TripoTask {
|
||||
task_id: string
|
||||
type: string
|
||||
status: TripoTaskStatus
|
||||
progress: number
|
||||
output?: TripoTaskOutput
|
||||
error_code?: number
|
||||
error_message?: string
|
||||
credits_consumed?: number
|
||||
created_at?: string
|
||||
completed_at?: string
|
||||
}
|
||||
|
||||
export interface TripoApiResponse<T> {
|
||||
code: number
|
||||
message?: string
|
||||
data?: T
|
||||
}
|
||||
|
||||
export interface TripoTextToModelInput {
|
||||
prompt: string
|
||||
model?: string
|
||||
negative_prompt?: string
|
||||
model_seed?: number
|
||||
image_seed?: number
|
||||
face_limit?: number
|
||||
texture?: boolean
|
||||
pbr?: boolean
|
||||
texture_quality?: 'standard' | 'detailed' | 'extreme'
|
||||
geometry_quality?: 'standard' | 'detailed'
|
||||
auto_size?: boolean
|
||||
quad?: boolean
|
||||
smart_low_poly?: boolean
|
||||
generate_parts?: boolean
|
||||
compress?: 'geometry'
|
||||
export_uv?: boolean
|
||||
}
|
||||
|
||||
export interface MoyiTaskView {
|
||||
id: string
|
||||
provider: 'tripo'
|
||||
status: 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelled'
|
||||
progress: number
|
||||
model?: string
|
||||
output?: { modelUrl?: string; previewUrl?: string }
|
||||
creditsConsumed?: number
|
||||
error?: { code?: number; message?: string }
|
||||
createdAt?: string
|
||||
completedAt?: string
|
||||
}
|
||||
|
||||
export interface TripoProviderOptions {
|
||||
apiKey: string
|
||||
baseUrl?: string
|
||||
timeoutMs?: number
|
||||
fetcher?: typeof fetch
|
||||
}
|
||||
|
||||
export class TripoProviderError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
readonly statusCode?: number,
|
||||
readonly providerCode?: number,
|
||||
) {
|
||||
super(message)
|
||||
}
|
||||
}
|
||||
|
||||
export class TripoProvider {
|
||||
private readonly baseUrl: string
|
||||
private readonly timeoutMs: number
|
||||
private readonly fetcher: typeof fetch
|
||||
|
||||
constructor(private readonly options: TripoProviderOptions) {
|
||||
if (!options.apiKey.trim()) throw new TripoProviderError('TRIPO_API_KEY 未配置')
|
||||
this.baseUrl = (options.baseUrl || 'https://openapi.tripo3d.com/v3').replace(/\/$/, '')
|
||||
this.timeoutMs = options.timeoutMs ?? 30_000
|
||||
this.fetcher = options.fetcher || fetch
|
||||
}
|
||||
|
||||
async createTextToModel(input: TripoTextToModelInput) {
|
||||
const prompt = input.prompt.trim()
|
||||
if (!prompt) throw new TripoProviderError('Tripo prompt 不能为空')
|
||||
if (prompt.length > 1024) throw new TripoProviderError('Tripo prompt 不能超过 1024 个字符')
|
||||
const response = await this.request<TripoTask>('/generation/text-to-model', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
model: input.model || 'v3.1-20260211',
|
||||
texture: true,
|
||||
pbr: true,
|
||||
...input,
|
||||
prompt,
|
||||
}),
|
||||
})
|
||||
if (!response.data?.task_id) throw new TripoProviderError(response.message || 'Tripo 未返回任务 ID', undefined, response.code)
|
||||
return response.data.task_id
|
||||
}
|
||||
|
||||
async getTask(taskId: string): Promise<MoyiTaskView> {
|
||||
if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{7,127}$/.test(taskId)) throw new TripoProviderError('Tripo task_id 格式无效')
|
||||
const response = await this.request<TripoTask>(`/tasks/${encodeURIComponent(taskId)}`)
|
||||
if (!response.data) throw new TripoProviderError(response.message || 'Tripo 未返回任务数据', undefined, response.code)
|
||||
return mapTripoTask(response.data)
|
||||
}
|
||||
|
||||
async waitForTask(taskId: string, options: { intervalMs?: number; timeoutMs?: number } = {}) {
|
||||
const intervalMs = options.intervalMs ?? 3_000
|
||||
const timeoutMs = options.timeoutMs ?? 10 * 60_000
|
||||
const deadline = Date.now() + timeoutMs
|
||||
while (Date.now() <= deadline) {
|
||||
const task = await this.getTask(taskId)
|
||||
if (task.status === 'succeeded' || task.status === 'failed' || task.status === 'cancelled') return task
|
||||
await new Promise((resolve) => setTimeout(resolve, intervalMs))
|
||||
}
|
||||
throw new TripoProviderError(`Tripo 任务轮询超时:${taskId}`)
|
||||
}
|
||||
|
||||
private async request<T>(path: string, init: { method?: string; body?: string } = {}): Promise<TripoApiResponse<T>> {
|
||||
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 TripoApiResponse<T>
|
||||
if (!response.ok || payload.code !== 0) {
|
||||
throw new TripoProviderError(payload.message || `Tripo 请求失败(HTTP ${response.status})`, response.status, payload.code)
|
||||
}
|
||||
return payload
|
||||
} catch (error) {
|
||||
if (error instanceof TripoProviderError) throw error
|
||||
if (error instanceof Error && error.name === 'AbortError') throw new TripoProviderError('Tripo 请求超时')
|
||||
throw new TripoProviderError(error instanceof Error ? error.message : 'Tripo 请求失败')
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function mapTripoTask(task: TripoTask): MoyiTaskView {
|
||||
const status = task.status === 'success' ? 'succeeded' : task.status
|
||||
return {
|
||||
id: task.task_id,
|
||||
provider: 'tripo',
|
||||
status,
|
||||
progress: Math.max(0, Math.min(100, Number(task.progress) || 0)),
|
||||
...(task.output ? { output: {
|
||||
...(task.output.model_url ? { modelUrl: task.output.model_url } : {}),
|
||||
...(task.output.rendered_image_url ? { previewUrl: task.output.rendered_image_url } : {}),
|
||||
} } : {}),
|
||||
...(task.credits_consumed !== undefined ? { creditsConsumed: task.credits_consumed } : {}),
|
||||
...(task.error_code || task.error_message ? { error: {
|
||||
...(task.error_code !== undefined ? { code: task.error_code } : {}),
|
||||
...(task.error_message ? { message: task.error_message } : {}),
|
||||
} } : {}),
|
||||
...(task.created_at ? { createdAt: task.created_at } : {}),
|
||||
...(task.completed_at ? { completedAt: task.completed_at } : {}),
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user