ComfyUI本地API调用指南:从基础到高级实践

发布时间:2026/7/23 3:03:20

ComfyUI本地API调用指南:从基础到高级实践 1. ComfyUI本地API调用概述ComfyUI作为当前最热门的AI创作工具之一其API调用能力让开发者能够将可视化工作流转化为可编程接口。本地部署的ComfyUI通过API暴露工作流执行能力可以实现自动化批量生成图片/视频动态修改工作流参数与企业现有系统集成定时任务触发等场景与云端API相比本地API调用的优势在于数据隐私性敏感数据无需上传第三方服务器模型自主性可自由使用自定义模型和插件成本可控避免云服务按量计费网络稳定性内网调用不受外网波动影响2. 本地环境准备2.1 基础环境配置推荐使用秋叶整合包建议v9.5及以上版本快速搭建环境# 下载整合包假设已配置Python3.10 git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui cd stable-diffusion-webui/extensions git clone https://github.com/ltdrdata/ComfyUI-Manager.git关键目录说明ComfyUI/workflows存放工作流JSON文件ComfyUI/models模型存放路径ComfyUI/output默认输出目录2.2 API服务启动启动时添加--api参数启用API服务python main.py --listen 127.0.0.1 --port 8188 --api验证服务可用性curl http://127.0.0.1:8188/history3. API核心调用流程3.1 工作流准备通过UI设计工作流后获取工作流JSON的两种方式通过Save (API Format)按钮导出从prompt字段提取含完整节点数据典型工作流结构示例{ prompt: { 3: { inputs: { seed: 123456, steps: 20, cfg: 7, sampler_name: euler, positive: best quality, masterpiece, negative: blurry, lowres }, class_type: KSampler } } }3.2 基础API调用POST请求格式curl -X POST http://127.0.0.1:8188/prompt \ -H Content-Type: application/json \ -d { prompt: {...}, client_id: your_client_id }响应处理import requests response requests.post( http://localhost:8188/prompt, json{prompt: workflow_json} ) prompt_id response.json()[prompt_id]3.3 动态参数注入通过extra_data字段覆盖默认值{ prompt: workflow_json, extra_data: { 3: { inputs: { seed: 654321, positive: sunset landscape } } } }4. 高级调用技巧4.1 实时进度监控建立WebSocket连接获取实时状态import websockets async def track_progress(): async with websockets.connect(ws://localhost:8188/ws?clientId123) as ws: while True: msg await ws.recv() print(json.loads(msg))4.2 批量任务处理使用batch_id关联任务组batch_id str(uuid.uuid4()) for i in range(10): requests.post( http://localhost:8188/prompt, json{ prompt: workflow, extra_data: {seed: random.randint(0,999999)}, batch_id: batch_id } )4.3 输出结果获取通过历史记录API检索def get_output(prompt_id): history requests.get(http://localhost:8188/history).json() return history[prompt_id][outputs]5. 常见问题排查5.1 错误代码处理错误码原因解决方案400参数格式错误检查JSON结构是否符合API规范403访问权限不足确认--listen参数配置正确500工作流执行错误检查节点配置和模型路径5.2 性能优化建议启用--highvram参数减少显存交换对静态工作流使用--disable-xformers提升稳定性定期清理temp目录释放磁盘空间5.3 显卡适配方案对于1066等旧显卡添加--lowvram启动参数使用--precision full避免精度问题降低工作流中的分辨率设置6. 企业级应用实践6.1 安全加固措施通过Nginx添加HTTPS加密location / { proxy_pass http://127.0.0.1:8188; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection upgrade; }IP白名单控制python main.py --listen 127.0.0.1 --api-auth user:pass6.2 高可用部署方案使用Supervisor守护进程[program:comfyapi] commandpython /path/to/main.py --listen 0.0.0.0 --port 8188 --api autostarttrue autorestarttrue stderr_logfile/var/log/comfyapi.err.log stdout_logfile/var/log/comfyapi.out.log6.3 监控指标采集Prometheus监控示例配置scrape_configs: - job_name: comfyui metrics_path: /metrics static_configs: - targets: [localhost:8188]

相关新闻