# Text Video Agent API 工具库 基于 `https://bowongai-dev--text-video-agent-fastapi-app.modal.run` API 的完整 TypeScript 工具库封装。 ## 📋 目录 - [功能特性](#功能特性) - [安装使用](#安装使用) - [API 文档](#api-文档) - [React Hook](#react-hook) - [组件示例](#组件示例) - [类型定义](#类型定义) - [使用示例](#使用示例) ## 🚀 功能特性 ### 核心功能 - ✅ **图片生成**: 基于 Midjourney 的高质量图片生成 - ✅ **视频生成**: 基于极梦的视频生成功能 - ✅ **文件上传**: 支持文件上传到云存储 - ✅ **图片描述**: AI 图片内容分析和描述 - ✅ **任务管理**: 异步任务创建、查询和管理 ### 高级特性 - ✅ **重试机制**: 自动重试失败的请求 - ✅ **进度跟踪**: 实时进度更新和状态监控 - ✅ **类型安全**: 完整的 TypeScript 类型定义 - ✅ **React 集成**: 专用的 React Hook 和组件 - ✅ **错误处理**: 完善的错误处理和用户反馈 ## 📦 安装使用 ### 基础安装 ```bash # 复制相关文件到你的项目 cp src/services/textVideoAgentAPI.ts your-project/src/services/ cp src/services/textVideoAgentTypes.ts your-project/src/services/ cp src/hooks/useTextVideoAgent.ts your-project/src/hooks/ cp src/components/TextVideoGenerator.tsx your-project/src/components/ ``` ### 依赖要求 ```json { "dependencies": { "react": "^18.0.0", "lucide-react": "^0.263.1" }, "devDependencies": { "typescript": "^5.0.0" } } ``` ## 🔧 API 文档 ### 基础用法 ```typescript import { textVideoAgentAPI } from './services/textVideoAgentAPI' // 健康检查 const health = await textVideoAgentAPI.healthCheck() // 生成图片 const imageResult = await textVideoAgentAPI.generateImageSync({ prompt: '一个美丽的风景', max_wait_time: 120 }) // 生成视频 const videoResult = await textVideoAgentAPI.generateVideoSync({ prompt: '动态的自然风光', img_url: 'https://example.com/image.jpg', duration: '5' }) ``` ### 主要方法 #### 图片生成 ```typescript // 同步生成(推荐) generateImageSync(params: ImageGenerationParams): Promise // 异步生成 generateImageAsync(prompt: string, imgFile?: File): Promise // 带重试的生成 generateImageWithRetry(params: ImageGenerationParams, maxRetries?: number): Promise ``` #### 视频生成 ```typescript // 同步生成 generateVideoSync(params: VideoGenerationParams): Promise // 异步生成 generateVideoAsync(params: VideoGenerationParams): Promise // 带重试的生成 generateVideoWithRetry(params: VideoGenerationParams, maxRetries?: number): Promise ``` #### 任务管理 ```typescript // 创建任务 createTask(request: TaskRequest): Promise // 查询任务状态 getTaskStatusAsync(taskId: string): Promise // 同步等待任务完成 getTaskResultSync(taskId: string): Promise ``` #### 高级功能 ```typescript // 端到端内容生成 generateContentEndToEnd(prompt: string, options?: GenerationOptions): Promise // 轮询任务直到完成 pollTaskUntilComplete(taskId: string, options?: PollingOptions): Promise ``` ## 🎣 React Hook ### useTextVideoAgent ```typescript import { useTextVideoAgent } from './hooks/useTextVideoAgent' function MyComponent() { const { state, generateImage, generateVideo, generateContentEndToEnd, reset, cancel } = useTextVideoAgent() const handleGenerate = async () => { const result = await generateContentEndToEnd('美丽的风景', { taskType: TaskType.VLOG, aspectRatio: AspectRatio.PORTRAIT, generateVideo: true }) console.log('生成结果:', result) } return (
{state.isLoading && (

{state.currentStep}

)} {state.error && (
{state.error}
)}
) } ``` ### useTaskPolling ```typescript import { useTaskPolling } from './hooks/useTextVideoAgent' function TaskMonitor({ taskId }: { taskId: string }) { const { status, isPolling } = useTaskPolling(taskId, { onComplete: (result) => { console.log('任务完成:', result) }, onError: (error) => { console.error('任务失败:', error) }, onProgress: (status) => { console.log('进度更新:', status) } }) return (
{isPolling &&

任务进行中...

} {status &&
{JSON.stringify(status, null, 2)}
}
) } ``` ## 🧩 组件示例 ### TextVideoGenerator 组件 ```typescript import TextVideoGenerator from './components/TextVideoGenerator' function App() { return ( { console.log('图片生成完成:', imageUrl) }} onVideoGenerated={(videoUrl) => { console.log('视频生成完成:', videoUrl) }} /> ) } ``` ## 📝 类型定义 ### 主要接口 ```typescript // API 响应 interface APIResponse { status: boolean msg: string data?: T } // 图片生成参数 interface ImageGenerationParams { prompt: string img_file?: File max_wait_time?: number poll_interval?: number } // 视频生成参数 interface VideoGenerationParams { prompt: string img_url?: string img_file?: File duration?: string max_wait_time?: number poll_interval?: number } // 任务请求 interface TaskRequest { task_type?: string prompt: string img_url?: string ar?: string } ``` ### 枚举类型 ```typescript enum TaskType { TEA = 'tea', CHOP = 'chop', LADY = 'lady', VLOG = 'vlog' } enum AspectRatio { SQUARE = '1:1', PORTRAIT = '9:16', LANDSCAPE = '16:9' } enum VideoDuration { SHORT = '3', MEDIUM = '5', LONG = '10' } ``` ## 💡 使用示例 ### 示例1: 基础图片生成 ```typescript import { textVideoAgentAPI, TaskType, AspectRatio } from './services/textVideoAgentAPI' async function generateImage() { try { const result = await textVideoAgentAPI.generateImageSync({ prompt: '一个现代化的咖啡厅,温暖的灯光,舒适的环境', max_wait_time: 120 }) if (result.status) { console.log('图片URL:', result.data.image_url) } } catch (error) { console.error('生成失败:', error) } } ``` ### 示例2: 端到端内容生成 ```typescript async function generateContent() { try { const result = await textVideoAgentAPI.generateContentEndToEnd( '制作一个关于健康生活的短视频', { taskType: TaskType.VLOG, aspectRatio: AspectRatio.PORTRAIT, videoDuration: VideoDuration.MEDIUM, generateVideo: true, onProgress: (step, progress) => { console.log(`${step}: ${progress}%`) } } ) console.log('生成完成:', result) } catch (error) { console.error('生成失败:', error) } } ``` ### 示例3: 批量处理 ```typescript async function batchGenerate() { const prompts = [ '春天的樱花', '夏日的海滩', '秋天的枫叶', '冬日的雪景' ] const results = await Promise.allSettled( prompts.map(prompt => textVideoAgentAPI.generateImageSync({ prompt }) ) ) results.forEach((result, index) => { if (result.status === 'fulfilled') { console.log(`图片 ${index + 1} 生成成功:`, result.value.data?.image_url) } else { console.error(`图片 ${index + 1} 生成失败:`, result.reason) } }) } ``` ## 🔧 配置选项 ### 预设配置 ```typescript import { PRESET_CONFIGS } from './services/textVideoAgentTypes' // 快速生成(低质量) const fastConfig = PRESET_CONFIGS.FAST // 标准生成 const standardConfig = PRESET_CONFIGS.STANDARD // 高质量生成 const highQualityConfig = PRESET_CONFIGS.HIGH_QUALITY ``` ### 自定义配置 ```typescript const customAPI = new TextVideoAgentAPI('https://your-custom-endpoint.com') ``` ## 🚨 错误处理 ```typescript try { const result = await textVideoAgentAPI.generateImageSync(params) } catch (error) { if (error instanceof Error) { console.error('错误信息:', error.message) } // 处理特定错误类型 if (error.message.includes('timeout')) { // 处理超时错误 } else if (error.message.includes('quota')) { // 处理配额不足错误 } } ``` ## 📊 性能优化 ### 缓存策略 - 图片生成结果自动缓存 - 任务状态智能轮询 - 网络请求去重 ### 最佳实践 - 使用适当的超时时间 - 合理设置轮询间隔 - 及时取消不需要的请求 - 使用预设配置提高效率 ## 🤝 贡献指南 1. Fork 项目 2. 创建功能分支 3. 提交更改 4. 推送到分支 5. 创建 Pull Request ## 📄 许可证 MIT License ## 🆘 支持 如有问题或建议,请创建 Issue 或联系开发团队。