diff --git a/apps/api/src/opendirector_api/main.py b/apps/api/src/opendirector_api/main.py index 1a5d95024..3a3662527 100644 --- a/apps/api/src/opendirector_api/main.py +++ b/apps/api/src/opendirector_api/main.py @@ -39,6 +39,7 @@ from opendirector_api.localization import localized_error from opendirector_api.models import (ModelConfigInput, ModelConfigPublic, AgentModelTest, ModelCapabilityRequest, ModelDiscoveryRequest, ModelBatchInput, + ConnectionDiscoveryRequest, ConnectionSaveRequest, ToolTaskCreate, ToolPlacement, ImageSelectionCreate, AvailabilityRefresh, AvailabilityCatalog, ModelAvailability as ModelAvailabilityResponse) @@ -282,6 +283,23 @@ async def discover_models(value: ModelDiscoveryRequest): protocol=value.protocol, auth_mode=value.authMode, proxy_mode=value.proxyMode) return {'models': models} + @app.post('/api/model-configs/discover-many') + async def discover_connection_models(value: ConnectionDiscoveryRequest): + return {'results': await catalog.discover_many( + [{'kind': entry.kind, 'protocol': entry.protocol} for entry in value.kinds], + value.url, value.apiKey.get_secret_value(), connection_type=value.connectionType, + auth_mode=value.authMode, proxy_mode=value.proxyMode)} + + @app.post('/api/model-configs/connections') + def save_connection(value: ConnectionSaveRequest): + return catalog.save_connection( + [{'kind': entry.kind, 'protocol': entry.protocol, 'modelIds': entry.modelIds, + 'modelOptions': entry.modelOptions} for entry in value.entries], + value.url, value.apiKey.get_secret_value(), connection_type=value.connectionType, + auth_mode=value.authMode, proxy_mode=value.proxyMode, + capability_auto_check=value.capabilityAutoCheck, + provider_id=str(value.providerId) if value.providerId else None) + @app.post('/api/model-configs/test-agent') async def test_agent_model(value: AgentModelTest): elapsed = await catalog.test_agent(value.url, value.modelId, value.apiKey.get_secret_value(), diff --git a/apps/api/src/opendirector_api/models.py b/apps/api/src/opendirector_api/models.py index 889dde41a..e21d27dc3 100644 --- a/apps/api/src/opendirector_api/models.py +++ b/apps/api/src/opendirector_api/models.py @@ -12,6 +12,9 @@ class Model(BaseModel): model_config = ConfigDict(extra="forbid") +Protocol = Literal['openai', 'volcengine', 'higgsfield_open', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'vllm_omni_segmentation', 'vllm_omni_music', 'vllm_omni_depth', 'vllm_omni_score', 'vllm_omni_bodies'] + + class Session(Model): projectId: UUID @@ -29,7 +32,7 @@ class UrlSource(Model): class ModelConnection(Model): connectionType: Literal['api', 'self_hosted'] = 'api' - protocol: Literal['openai', 'volcengine', 'higgsfield_open', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'vllm_omni_segmentation', 'vllm_omni_music', 'vllm_omni_depth', 'vllm_omni_score', 'vllm_omni_bodies'] | None = None + protocol: "Protocol" = None authMode: Literal['none', 'bearer'] | None = None proxyMode: Literal['system', 'direct'] | None = None capabilityAutoCheck: bool | None = Field(default=None, strict=True, exclude_if=lambda value: value is None) @@ -68,6 +71,43 @@ class ModelDiscoveryRequest(ModelConfigInput): configId: UUID | None = None +MODEL_KIND = Literal["agent", "image", "video", "audio", "vision"] + + +class ConnectionDiscoveryKind(Model): + kind: MODEL_KIND + protocol: "Protocol" = None + + +class ConnectionDiscoveryRequest(Model): + """Discover models for several modalities of one address and credential.""" + url: str = Field(max_length=2048) + apiKey: SecretStr = SecretStr("") + connectionType: Literal['api', 'self_hosted'] = 'api' + authMode: Literal['none', 'bearer'] | None = None + proxyMode: Literal['system', 'direct'] | None = None + kinds: list[ConnectionDiscoveryKind] = Field(min_length=1, max_length=5) + + +class ConnectionEntry(Model): + """One modality saved as part of a connection.""" + kind: MODEL_KIND + protocol: "Protocol" = None + modelIds: list[str] = Field(min_length=1, max_length=200) + modelOptions: dict[str, ModelOptions] = Field(default_factory=dict, max_length=200) + + +class ConnectionSaveRequest(Model): + url: str = Field(max_length=2048) + apiKey: SecretStr = SecretStr("") + connectionType: Literal['api', 'self_hosted'] = 'api' + authMode: Literal['none', 'bearer'] | None = None + proxyMode: Literal['system', 'direct'] | None = None + capabilityAutoCheck: bool | None = Field(default=None, strict=True) + providerId: UUID | None = None + entries: list[ConnectionEntry] = Field(min_length=1, max_length=5) + + class AgentModelTest(ModelConfigInput): kind: Literal["agent"] = "agent" configId: UUID | None = None diff --git a/docs/README.md b/docs/README.md index 86cc0fe69..2aea43fd9 100644 --- a/docs/README.md +++ b/docs/README.md @@ -13,6 +13,7 @@ This directory is the entry point for the repository's shared documentation. The | [Desktop architecture](architecture/desktop.md) ([中文](architecture/desktop.zh-CN.md)) | Electron, the Python Host, project storage, and shutdown behavior | Process, request, storage, or lifecycle boundaries change | | [Test contracts](architecture/test-contracts.md) | Test/production boundaries, how to avoid stale assertions and environment-dependent red runs | Test infrastructure, capability gates, or contract ownership change | | [Capability mapping contract](architecture/capability-contract.md) | Evidenced upstream vocabulary, the `(operation, profile) → capability` table, the untranslatable declarations, and how it feeds discovery | Upstream vocabulary, capability ids, or discovery matching change | +| [Multimodal model connections](architecture/model-connection-multimodal.md) | One connection (address + credentials) that adds text, image, video and audio models in one pass, with per-kind discovery and partial-save semantics | The connection object, its endpoints, or multi-kind save rules change | | [Roadmap](development/roadmap.md) | Capability dependencies and delivery criteria | Scope, dependencies, or acceptance criteria change | | [Validation guide](development/validation.md) | Reproducible checks and evidence requirements | Tools, runtime requirements, or validation entry points change | | [Agent turn timing](development/agent-timing.md) ([中文](development/agent-timing.zh-CN.md)) | Where one agent turn spends its time, and the pre-registered bands that decide the next optimization | The ledger, its reader, or a decision band changes | diff --git a/docs/architecture/model-connection-multimodal.md b/docs/architecture/model-connection-multimodal.md new file mode 100644 index 000000000..04f2f144d --- /dev/null +++ b/docs/architecture/model-connection-multimodal.md @@ -0,0 +1,128 @@ +# Multimodal model connections + +## 摘要(中文) + +同一 API Key 往往同时提供语言、图片、视频、语音模型,但当前配置流程是「按模态建服务」:语言、图片、视频、音频各填一次地址与密钥、各自发现模型、各自保存。本文设计「连接(connection)」为第一次类对象:一次填写地址与凭据,按模态分别发现并分组的模型,一次保存为多个 `model-configs`(同一 `providerId`),并对部分失败、能力检查、协议差异和兼容性给出明确语义。本文只描述设计,不代表已实现。 + +Status: implemented for the settings entry point; the first-run wizard and the business CLI still use the per-kind form (see “Delivered scope”). + +## Delivered scope + +Implemented in this repository: + +- `POST /api/model-configs/discover-many` and `POST /api/model-configs/connections`, backed by + `ModelCatalog.discover_many` / `ModelCatalog.save_connection` (`packages/core/src/opendirector/application/model_catalog.py`) + and `ModelConfigs.save_connection` (`packages/core/src/opendirector/infrastructure/model_configs.py`). +- Per-kind saving now replaces only rows of that kind, so a connection can grow kind by kind without + dropping its peers (`save_many` filters `previous` by kind). +- `src/canvas/ModelConnectionForm.tsx`, reachable from Settings → model connections → + “Add a connection (multi-modal)” and from the per-kind service list. +- Tests: `tests/test_model_catalog.py` (discovery isolation), `tests/test_model_configs.py` + (one providerId across kinds, partial failure, retry reusing the connection, rejected input) and the + browser workflow `tests/browser/model_connection.mjs`. + +Not delivered yet: first-run wizard entry, CLI/agent tool parity, reusing an existing connection to add +only a missing kind from the settings list, and translating the panel into the per-kind forms. + +## Problem + +Configuration is currently kind-scoped end to end: + +- UI: `src/canvas/ModelServiceForm.tsx` holds one `kind`; entering the first-run wizard for a MiniMax account with text, image, video and speech models means repeating the same URL and key four times. +- Discovery: `POST /api/model-configs/discover` takes a single `kind` and derives one protocol via `connection_fields()` (`packages/core/src/opendirector/domain/model_connection.py`), so `/models` is read under one protocol only. +- Save: `POST /api/model-configs/batch` accepts one `kind` plus `modelIds` (`apps/api/src/opendirector_api/main.py`). + +The storage layer already models the missing concept: `providerId` groups configurations of different kinds that share `url`, `apiKey`, `connectionType`, `authMode` and `proxyMode` (`packages/core/src/opendirector/infrastructure/model_configs.py`). Today a user can only reach a shared connection by editing an existing configuration, never by creating one. + +## Goals + +1. One form fills address, authentication, proxy mode, capability-check policy, then adds models for several kinds in one pass. +2. Everything saved in that pass belongs to one `providerId`, so later credential edits apply to all kinds. +3. Model ability remains per-kind: a connection is not a claim that every model supports every operation. +4. Partial success is explicit: the user sees which kinds saved, which were rejected and why, and can retry only the failed part. +5. UI, CLI and agent tools keep using the same application service; no entry point gets a private shortcut. + +Non-goals: automatic protocol guessing for self-hosted servers, cross-kind capability inference from model names, credential storage changes, migration of existing configurations. + +## Object model + +``` +Connection (draft or stored providerId) + url, apiKey, connectionType, authMode, proxyMode, capabilityAutoCheck + └── KindEntry (kind, protocol, modelIds[]) # one per kind in this pass + └── ModelConfig (existing object, unchanged) # id, kind, modelId, protocol, ... +``` + +- A connection is identified by `providerId` only after the first successful save; drafts never persist identity. +- `protocol` stays on the kind entry, not on the connection: `openai` for agent/image/audio and `minimax_video_v2`/`kling_video`/`bigmodel_video`/`vllm_omni` for video are not interchangeable. +- A connection may exist with only some kinds configured. Missing kinds are absent, not empty. + +## Discovery + +For each kind the client asks the server to discover models for that kind's candidate protocol: + +- `openai` kinds use `GET {url}/models` through `read_service_models()` (`packages/core/src/opendirector/integrations/model_capabilities.py`). +- Built-in-declaration protocols (`minimax_video_v2`, `kling_video`, `bigmodel_video`, `higgsfield_open`) return the declared list without a network call, as they do today. +- Model ids that appear in several kinds are kept per kind; a shared id is not evidence of shared input rules. + +New endpoint: `POST /api/model-configs/discover-many` with `{url, apiKey, connectionType, authMode, proxyMode, kinds: [{kind, protocol}]}` returning +`{results: [{kind, protocol, models: [id], error: null | {code, message}}]}`. + +Rules: + +- One kind failing does not abort the others; each result carries its own error. +- Total discovery is bounded (kinds requested, response sizes, timeout) so a hung upstream cannot block the form. +- The draft is never written to disk; a failed discovery leaves configuration untouched (same contract as `read_service_models` today). + +## Save + +New endpoint: `POST /api/model-configs/connections` with +`{url, apiKey, connectionType, authMode, proxyMode, capabilityAutoCheck, providerId?, entries: [{kind, protocol, modelIds, modelOptions?}]}`. + +Server behavior: + +1. Validate the connection once (`model_fields`, `connection_fields` per entry). +2. Allocate or reuse `providerId`. +3. Save each entry through the existing `save_many()` path so per-kind rules, duplicate checks and capability declarations still apply. +4. Apply the connection fields to every peer carrying that `providerId`, as `save()` already does. +5. Return `{providerId, saved: [ModelConfig], rejected: [{kind, code, message}], remaining: [...]}`. + +Failure semantics: entries are independent commits. A rejected entry (invalid model id, missing capability declaration, key rejected for that kind) does not roll back the saved ones; the response reports both sets and the UI offers "retry failed kinds" which reuses the same connection fields. This must not be described as all-or-nothing success. + +Idempotency: the request carries an operation id; replaying it with identical input returns the original receipt, and replaying it with different input is rejected, consistent with other mutations. + +## Capability checks + +- `capabilityAutoCheck` stays a connection-level default but each model keeps its own availability record (`docs/guides/model-availability.md`). +- A saved model never blocks on capability probing; probing failure produces an explainable unavailable state, not a failed save. +- Video entries keep explicit `videoCapabilities` requirements; a connection with video models still needs output declarations or manual configuration. + +## UI flow + +1. `添加服务` becomes `添加连接`: provider preset, address, auth, proxy, capability-check policy. +2. `获取模型` runs discovery for every supported kind in one request; results render as collapsible kind sections with per-kind counts and errors. +3. Selecting models across sections enables one `保存连接` action; the footer reports `将启用 N 个模型(语言 x、图片 y、视频 z)`. +4. Save result screen lists saved kinds and rejected kinds with reasons, each with `重试` and `编辑`. +5. First-run wizard (`src/canvas/WelcomeScreen.tsx`) reuses the same component: after saving, the task step only asks for kinds the connection did not provide. +6. Settings → model access lists connections with their kinds, so the user can add a missing kind to an existing connection instead of creating a duplicate service. + +Existing single-kind editing stays available for configurations that are not part of a connection and for self-hosted servers. + +## Bilingual and accessibility + +- Every new message key ships in `zh-CN` and `en-US`; stable values (`providerId`, kind ids, protocol ids) are never translated. +- Kind counts and partial-failure summaries use plural messages, not string concatenation. +- The save footer and the partial-failure list are announced via `role="status"`/`role="alert"`; focus moves to the first rejected entry. + +## Testing + +- Application tests: connection save creates one `providerId` across kinds; credential edit propagates to peers; duplicate model ids within a kind rejected; partially failing entries report saved/rejected sets and stay retryable. +- Discovery tests: one kind returning HTTP 401 while another succeeds; built-in declaration protocols skip the network; oversized responses rejected. +- Browser workflow: `tests/browser/first_run.mjs`-style isolated journey that configures text+image through one connection and asserts the assistant and image selections point at different kinds of the same `providerId`. +- CLI/agent parity: creating the same connection through the business CLI produces identical configuration rows. + +## Compatibility and rollout + +- Existing per-kind endpoints and configurations keep working; no migration, no rewriting of stored `providerId` values. +- The new connection entry point ships behind the same capability contract, so agent tools and CLI gain it only after the application service exists. +- Open question: whether `audio` and `vision` kinds should appear in the default multi-kind discovery, or only after the user picks a task that needs them. diff --git a/docs/development/video-agent-benchmark-landscape.md b/docs/development/video-agent-benchmark-landscape.md new file mode 100644 index 000000000..bdaa43e25 --- /dev/null +++ b/docs/development/video-agent-benchmark-landscape.md @@ -0,0 +1,123 @@ +# 视频生成 Agent Benchmark 版图 + +调研时间 2026-11-29。**仅供选型与自建决策**,不含实现状态。 + +--- + +## 1. 两个物种,不能混 + +| | 模型榜 | Agent 榜 | +| --- | --- | --- | +| 测什么 | 一次调用的产物 | 多步交付的成片 | +| 判定 | 打分(Elo / MOS) | 达标(resolution rate) | +| 代表 | VBench、Artificial Analysis | Timeline-Bench、StudioBench | + +**两者几乎不相关**:Timeline-Bench 里 96.3% 过格式、78.4% 过 brief 明写要求,**只有 15.9% 过质量线**。用 VBench 分数论证 Agent 能力是跨物种推断。 + +--- + +## 2. 四轴定位 + +- **A 控制层级**(2609.06758):L0 固定管线 → L1 调输入 → L2 选操作 → **L3 观察中间产物并改后续** → L4 跨任务积累经验。多数「视频 Agent」停在 L2。 +- **B 流水线**:脚本 → 分镜 → 关键帧/参考 → 镜头视频 → 音频 → 剪辑 → 交付 +- **C 方法学**:自动指标 → VLM judge → 逐样本 checklist → agentic judge → 可执行测试 → 专家校准门槛 +- **D 成本**:$/分钟、首抽率、重试、人工介入 + +--- + +## 3. 学术侧(按层) + +**L0 生成质量**(已饱和):VBench/VBench-2.0、T2V-CompBench、Video-Bench、AVGen-Bench、VTR-Bench、OmniVBench、Physics-IQ + +**多镜/电影语言**(最活跃): +- **MSBench** 脚本可控多镜头,14 系统,ρ=0.87;画质区分度小、多镜头控制区分度大 +- **FilmBench** 北电共建,3 轴 12 构件 35 子指标,ρ=0.95 +- **CutCraft** 唯一专测剪辑技法(J/L-cut),结论:连贯性 ≠ 技法执行 +- **PersonaShot** 人物状态重置、情感突变 +- **ProxyGenBench** 3D blockout 引导;代理更细 ≠ 补全更好 + +**端到端 Agent 榜**(直接对标): +- **StudioBench** 160 任务/33 工具,评成片 + 重建 workflow 图。**工具调用多 ≠ 质量高**,瓶颈是「检查—选择—修改」闭环 +- **Timeline-Bench** 56 任务,**四层阶梯**(格式→守卫→must-haves→质量门槛),2,582 次剪辑师盲判校准,留一法误差 3.0 点 +- **VAHBench** 48 配置;**质量分高 ≠ 交付完整**(缺集/重复/静态填充) +- **DramaChain** 63 叶子维度全链路,agentic judge PLCC 0.918 +- **DRAFT-Bench** 执行 / 需求合规 / 专业验收三分;结构满分≠验收通过 + +**编辑/时间线**:OmniEdit-Bench、CoVEBench、Goku、AVENUE、AVE-Compass、MEDit-Bench(**LLM judge 有严重位置偏差**)、Code2Video-Compass + +**Judge 校准**:**AGC-Bench** 的 Judge Response Theory 对裁判宽松/严苛做心理测量学校准——比只报 Spearman 严格一级 + +**过程可解释性**:**ATP-Bench** 的 MAM 评工具调用精度与**漏用机会**,无需 ground truth + +**成本**:**VidRouteBench** 16 arms/121× 成本跨度,per-prompt 专精可预测(oracle gap 0.642) + +--- + +## 4. 工业侧 + +| 榜 | 方法 | +| --- | --- | +| **Artificial Analysis** | 6 个 board(3 带音频+3 静音),独立 Elo pool,锚定 Kling 3.0 Pro = 1000 | +| **LMArena / arena.ai** | T2V 89 万票/50 模型;**Video Edit Arena** 5.6 万票/12 模型 | +| **videomodels.ai** | 46 模型 × 同一批 64 prompt,8 维 rubric | + +**分歧是结构性的**:AA 说 Wan 3.0 第一,Arena 说 Gemini Omni 1.2 Flash 第一,同模型两边差 5 名。自建榜必须公开锚点、样本量、CI。 + +--- + +## 5. 中文侧 + +**机构级(可引用)**: +- **晓天衡宇 SkyEval** 102.2 万局 Arena,8 内容 × 6 场景,**并列报成功率/首抽率/价格** +- **港大 AIEL** 12 模型,中文场景,唯一带安全维度;**发现加参考图反而变差**(Wan 2.6 −0.66) +- **火山引擎 MediaKit** 11 模块质检 API,输出秒级区间 + 证据帧,官方明说「可接入创作 Agent 形成闭环」 +- **SuperCLUE / FlagEval** 中文原生模型榜,必须按期次引用(三代不可比) + +**创作者级(不可作测量)**:B站/公众号/小红书横评——非盲、无 rubric、样本 5–6 条、带返利链接。唯一可靠产出是**失败模式清单**。 + +**要筛掉的错误**:VideoTemp-Bench 名称不存在(实为 VideoTemp-o3);LongVideoBench 是「最大 1 小时」不是「平均 70 分钟」;OmniCompass 漏了 AV 轨 240/720;「SkyReels V4 在 AA 全球第二」是厂商自述,AA 有 6 个 board。 + +--- + +## 6. 五条结论 + +1. **重心从「生成质量」移到「可执行交付验证」**——只有打分没有门槛的榜测不出差异 +2. **L3 质量闭环是唯一真瓶颈**,但**基础设施已就绪**(火山引擎已把它做成 API),缺的是 agent 会用并对反馈负责 +3. **饱和 → 必须转逐样本 checklist + 可执行测试**;judge 本身必须被校准 +4. **成本是一等指标**,且必须拆成 `模型 / harness / 工具 / 预算` 四项归因,否则「提升 X 分」无法解释 +5. **中文 L0 榜已成熟,缺的是 L2+ agent 层**与中文特有失败模式(小字乱码、粤语口型、字幕排版) + +--- + +## 7. 空白位(按纵×横矩阵) + +| 格 | 现状 | 机会 | +| --- | --- | --- | +| **L4 × 视频创作** | 只有 CineForge/VOL-Agent 的方法,无榜 | ★★ | +| **L3 × 双语/本地化** | 有单点(VisualTalk、CultureVidBench),无体系 | ★★ | +| **L3 × 时间线编辑** | Timeline-Bench 是 CLI harness,无可编辑产物验收 | ★ | +| **L3 × 人机协作** | τ²-bench 的 dual-control 从未用于创作域 | ★ | + +--- + +## 8. 若要自建 + +- **任务三层**:T1 单能力(回归)/ T2 多镜叙事 / T3 端到端 +- **验证四层**:交付 → 内容守卫 → brief must-haves → **专家校准质量门槛** +- **指标**:任务解决率、**首抽率**、**单位可用素材总成本**、建议修订单数 +- **负向指标**:静态填充率、素材重复率、幻觉引用率 +- **防作弊**:held-out、任务版本化、单次一跑、grader 不可观测、receipt + +详见 [评测集设计](video-agent-evaluation-set.md)。 + +--- + +## 9. 文献索引 + +**端到端 Agent**:2611.28902 StudioBench、2609.35143 Timeline-Bench、2611.20535 VAHBench、2609.00646 DramaChain、2611.08933 DRAFT-Bench +**多镜/技法**:2611.29417 MSBench、2607.24241 FilmBench、2609.08275 CutCraft、2608.16717 PersonaShot、2611.34457 ProxyGenBench +**方法学**:2609.06758 分层框架、2607.01152 AGC-Bench、2603.29902 ATP-Bench、2610.22466 Harness-Delta、2611.28099 VidRouteBench +**生成基础**:2503.21755 VBench-2.0、VBench++、T2V-CompBench、Video-Bench、AVGen-Bench、OmniVBench(2609.22069)、VComBench(2611.34680) +**编辑**:2608.05049 OmniEdit-Bench、2606.08415 CoVEBench、2609.04253 AVENUE、2607.24821 AVE-Compass、2607.25300 MEDit-Bench、2610.28416 Code2Video-Compass +**中文侧**:火山引擎 AI MediaKit、港大 AIEL、晓天衡宇 SkyEval、SuperCLUE/AIGVBench、FlagEval、imai.lol +**工业榜**:Artificial Analysis、arena.ai(含 Video Edit Arena)、videomodels.ai、peerBench、Labelbox diff --git a/docs/development/video-agent-evaluation-set.md b/docs/development/video-agent-evaluation-set.md new file mode 100644 index 000000000..79832ddaf --- /dev/null +++ b/docs/development/video-agent-evaluation-set.md @@ -0,0 +1,223 @@ +# 视频创作 Agent 评测集设计 + +状态:**设计规格,尚未实现**。调研依据见[版图](video-agent-benchmark-landscape.md)。 + +--- + +## 0. 先纠正定位:这不是视频理解评测 + +常见提纲把它写成 Video QA + 时间定位 + 空间定位,指标用 Accuracy / IoU / Recall@K。**那不是本项目的对象。** + +| | 视频理解 Agent | 视频创作 Agent(本项目) | +| --- | --- | --- | +| 产出 | 答案(文本/时间戳/框) | **成片文件 + 可继续编辑的项目状态** | +| 判定 | 与标注比对 | 可执行测试 + 专家校准门槛 | +| 失败形态 | 答错、定位偏 | 缺镜头、素材重复、格式对但内容空 | + +按 Accuracy 打分,会奖励「交出一个格式正确但空洞的成片」——而这正是当前主要的失败模式。 + +**外部基准核查**(引用前必看): + +| 名称 | 结论 | +| --- | --- | +| VideoTemp-Bench | ❌ 名称不存在,实为 **VideoTemp-o3**(某方法的配套榜),「0-3/3-10min 分段」无据 | +| LongVideoBench | ❌ 是「**最大** 1 小时」非「平均 70 分钟」;3,763 视频 / 6,678 题 | +| OmniCompass | ⚠️ VL 轨 820/2,460 对,但**漏了 AV 轨 240/720** | +| WildVideo | ✅ 准确(TPAMI 2025,9 类幻觉、最多 5 轮、中英双语) | + +四者均为理解侧,只可借方法,不可作基线。 + +--- + +## 1. 能力面决定能测什么 + +`domain/creation/commands.py` 实枚举:**53 条命令,agent 可调 45 条**。被排除的里有四个创作关键动词: + +``` +asset.import · canvas.applyEdit · canvas.publishMedia · timeline.publishRender +``` + +**agent 目前无法自己导入素材、应用编辑、导出成片。**「brief → 成片」这类任务今天跑不通——不是能力不足,是工具面缺动词。 + +- **路线 A**:先补齐四个动词,再做 T3(符合 AGENTS.md 的能力等价要求)。**本文按 A 设计。** +- **路线 B**:T3 拆成「到可交付为止」+ 用户点导出,报告中标注人工补位;代价是分数不可跨系统比较。 + +--- + +## 2. 配置空间:被测对象不是模型 + +``` +配置单元 = (模型 + 量化/LoRA/步数/输出阶梯/参考模式) × harness × skill 集 × 工具面版本 +``` + +实际可变面(清点自仓库):适配器 7 类 + gateway 多个 H3 LoRA 变体、**harness 7 个**(`native`/`pi`/`claude`/`codex`/`opencode`/`dsh`/`jiuwenswarm`)、**skills 5 个**、工具面 45 命令。组合是上千量级,**全测不可能**。 + +### 2.1 配置注册表(第一步就建) + +`configs.jsonl`,每行:`config_id, model_ref, quant, steps, resolution_tier, duration_tier, lora, reference_mode, harness, harness_version, skills[], tool_surface_version, fingerprint_hash` + +四条硬规则: + +1. 分数绑 `config_id`,不绑模型名 +2. `fingerprint_hash` 变则 `config_id` 必须变 +3. **禁止同名跳量化比较**(上一版 bf16 的分不能与这版 int8 并列)——这是「不依赖临时记忆」的具体含义 +4. 未登记配置跑出的数字不进报表 + +### 2.2 端侧改变成本结构,因此改变指标 + +| | 云端 | 端侧 | +| --- | --- | --- | +| 单次成本 | 主要成本 | 近零 | +| 正确策略 | 减少尝试 | **增加尝试、靠闭环收敛** | +| 首抽率 | 质量指标 | **吞吐指标** | + +推论:重心从「一次生成多好」移到「**几次尝试内收敛、代价多少算力**」;**不能引用外部 L0 榜**(其 prompt 为云端设计,端侧上限不同),T1 基线必须自测;端侧瓶颈常是内存与并发而非画质。 + +### 2.3 三层筛,不做全组合 + +| 层 | 做什么 | 判据 | 频率 | +| --- | --- | --- | --- | +| **1 门禁** | 与配置无关、代码可判、必须全过 | 二值,失败即阻断 | 每次改动 | +| **2 主效应** | 固定 reference config,单变量扫 | 主效应 + CI | 每周 | +| **3 交互** | 只对 top-k 测 2–3 变量的部分因子设计 | 交互项 | 里程碑 | + +**未测组合不给分。** 想要配置总排名是做不到的,假装做到就是编数据。 + +### 2.4 模型旋钮:必须冻结 + +| 旋钮 | 不冻结的后果 | +| --- | --- | +| 量化 bf16/fp8/int8/int4 | 直接影响交付契约(形状、时长精度、音频轨是否还在) | +| LoRA 变体 | 同 base 不同 LoRA = 不同模型,分数不可合并 | +| 采样步数 / 分辨率 / 时长阶梯 | 与成本强耦合,混报等于没测成本 | +| 参考模式 | 港大已证参考图会降质(Wan 2.6 −0.66),**T2V 与 I2V 必须拆开** | + +### 2.5 harness 测五个接口面,报 Δ 不报绝对分 + +| 接口面 | 指标 | +| --- | --- | +| 工具描述与选择 | 选错工具率、**漏用工具率** | +| 上下文管理 | 跨轮一致性、重读率 | +| 失败恢复 | 重试 / 换配置 / 放弃的比例 | +| skill 注入 | 前置注入 vs 按需检索的可达率与噪声 | +| 人工接管 | 停在哪、原因分布 | + +绝对分里混了模型能力,无法回答「harness 调得对不对」。用 Harness-Delta Attribution 的做法报 **Δ ± CI**。 + +### 2.6 skills 测三件事 + +增减单 skill 的 Δ、**误触发率**、**局部最优信号**(T1 升但 T2 降即警告)。2^5 子集不全测,只测「单 skill 增减」+「全开 vs 全关」;无显著差异则默认关闭。 + +--- + +## 3. 任务三层 + +| 层 | 数量 | 命令链 | 覆盖 | +| --- | --- | --- | --- | +| **T1** 单能力(回归,不排名) | 60 | `reference.add` → `generationSpec.create` → `generation.submit` → `job.get` → `result.select` | 组合绑定、参考保真、文字渲染、镜头方向、物理 | +| **T2** 多镜叙事(主榜 A) | 24 组 | 每镜生成 + `canvas.createGeneration` → `result.select` 采纳 → `editor.save` | 跨镜一致性、人物状态不重置、J/L-cut、节奏 | +| **T3** brief→成片(主榜 B,依赖 §1) | 12 | T2 全链 + `asset.import` + `publishMedia` + `publishRender`(**当前不可用**) | 素材筛选、废条识别、交付规格、可继续编辑 | + +### 样例 + +``` +[T2] 三镜头对话戏。A 说话时切到 B 的反应,声音不切(J-cut)。三人同场, + B 全程不换装。最后一句台词结束时画面停在 B 的脸上。 +must: [3 个镜头, 至少 1 处 J-cut, B 服装跨镜一致, 结束帧为 B 面部近景] +must_not: [B 面部跨镜变化, 出现第 4 个角色, 台词与口型明显不符] + +[T3] 用提供的 14 条素材剪 30 秒产品开场片,1080p/24fps/16:9。 + 其中 3 条是废条(穿模/静音/重复),必须剔除。 +must: [时长 28–32s, 剔除全部 3 条废条, 无 5s 以上空洞, 首帧为产品全貌] +must_not: [使用任一废条, 循环同一片段, 单边声道] +``` + +--- + +## 4. 验证器:四层阶梯 + +借 Timeline-Bench 的漏斗,因为它把「格式对但内容空」挡在第 2 层。 + +| 层 | 检查 | 方式 | 淘汰 | +| --- | --- | --- | --- | +| **L1 交付** | 文件存在;codec/raster/fps;时长窗口;音频轨 | ffprobe | 极少 | +| **L2 内容守卫** | 非静音/非冻结/无循环素材/无 >5s 空洞/无单边声道/人脸不被裁 | 代码+信号 | 少 | +| **L3 brief 明写要求** | 每任务 2–7 条 | 代码优先,否则 2-of-3 judge | 中 | +| **L4 质量门槛** | 对照专业参考剪辑,差距需超过 tie margin | 专家校准 judge | **多** | + +**L4 是唯一有区分度的层**(版图 §1:前三层几乎不筛人,第四层筛掉约 80%)。所以 tie margin 必须由人类盲判校准得出,judge 必须与被测模型族独立,并同时报「过 L3 未过 L4」的比例——那就是质量闭环缺口的直接度量。 + +--- + +## 5. 指标 + +### 5.1 端侧指标(一等) + +收敛曲线(**P50/P90,不报均值**)、达到阈值的尝试数、峰值显存、端侧秒/可用片段、长片吞吐(成片时长 ÷ 端到端墙钟)。 + +### 5.2 任务指标 + +任务解决率(过四层 / 总数)、**首次抽卡率**、**单位可用素材总成本**(生成+排队+返工+人工补位 ÷ 可用片段)、**建议修订单数**(agent 主动「检查→修改」的轮次,直接测 L3)。 + +### 5.3 分层归因(不可合并) + +必须分开报:**模型贡献**(固定 harness 换模型)、**harness 贡献**(固定模型换 harness)、**工具面贡献**(补一个命令的前后差)、**人工补位**(介入次数与介入点)。合并报分会让「提升 X 分」无法解释。 + +### 5.4 负向指标(必报) + +静态填充率、素材重复率、幻觉引用率。VAHBench 指出的真实失败模式,**不体现在任何质量分里**。 + +### 5.5 两本账 + +| | **账 A 门禁** | **账 B 能力** | +| --- | --- | --- | +| 内容 | L1–L3、可继续编辑性、三个负向指标 | L4、任务解决率、收敛曲线 | +| 判定 | 代码、二值 | 专家校准 tie margin | +| 失败 | **阻断发布** | 只影响选型 | +| 频率 | 每次改动 | 每周/里程碑 | + +**能力分报 capability-relative 达成率** = 达成率 ÷ 该配置自身能力上限。理由:NeurCo 实测同 agent 换模型差 21.7 点(46.8% vs 66.5%),不归一则「harness 调得对不对」与「模型强不强」永远纠缠。 + +**可继续编辑性是本项目独有门禁**:外部榜只看成片文件,我们能回读节点/时间线/版本/锁并验证仍可操作。 + +--- + +## 6. judge 校准(硬门槛) + +1. 人类校准集 ≥40 样本 × 3 名有剪辑经验者背靠背(2 否即否) +2. 不许自验:策划/生成该任务者不得参与判定 +3. 报留一法误差(≤3 点)与 Spearman(≥0.9) +4. 偏差建模参考 AGC-Bench 的 Judge Response Theory,而非只报相关系数 +5. A/B 换序重测,位置偏差显著即判 judge 不可用(MEDit-Bench 教训) + +--- + +## 7. 防作弊与版本化 + +held-out 加密测集 · 任务版本化(改一条 must 就 bump,跨版本不可比)· 单次一跑不许挑最好 · grader 不可被被测 agent 观测 · 保留 sealed 模型 · 留 receipt 可复算 · 人工介入留痕。 + +--- + +## 8. 来源台账 + +- **A 级(一手可核实,17 个)**:Timeline-Bench 2609.35143、StudioBench 2611.28902、VAHBench 2611.20535、DramaChain 2609.00646、DRAFT-Bench 2611.08933、ATP-Bench 2603.29902、AGC-Bench 2607.01152、MSBench 2611.29417、FilmBench 2607.24241、CutCraft 2609.08275、PersonaShot 2608.16717、NeurCo 2611.34680、VidRouteBench 2611.28099、Agentic Visual Generation 2609.06758、Harness-Delta 2610.22466、Epoch AI 基准审查、火山引擎 AI MediaKit、港大 AIEL、LongVideoBench/OmniCompass/WildVideo/VideoTemp-o3(理解侧参照) +- **B 级(官方但口径需注意)**:晓天衡宇 SkyEval、imai.lol 电商实测、SuperCLUE/AIGVBench、FlagEval +- **未采用**:B站/公众号/小红书创作者横评(非盲、无 rubric、样本 5–6 条、带返利),版本串台的 SEO 站 + +--- + +## 9. 实施顺序 + +前置链:**配置注册表 → 门禁 → 主效应 → 交互**。 + +1. 建配置注册表,先登记真实在用的 3–5 个配置(要求 fingerprint 诚实,不要求全) +2. 补齐四个命令(§1),否则 T3 不可测 +3. 建账 A 门禁:L1–L3 纯代码 + 可继续编辑性,用 12 个 T3 任务跑通 +4. T1 回归集 60 条跑通不求分(**自测,不引用外部 L0 榜**) +5. harness 主效应(1 个模型 × 7 harness)+ skills 主效应(单增减 / 全开全关) +6. judge 校准,得出 L4 的 tie margin;再做 T2 主榜 +7. 只对 top-3 配置测 2 变量交互;最后上 T3 + +两条硬约束:**第 3 步前不发布任何分数**(否则「格式对但内容空」算好成绩);**第 6 步前不发布任何能力排名**(否则测的只是「格式对不对」)。 + +端侧两条纪律:每个分数必须能回答「在哪个设备、哪个精度下」,不能回答的不进报表;收敛曲线优先于单点成绩,长尾失败比均值重要。 diff --git a/packages/core/src/opendirector/application/model_catalog.py b/packages/core/src/opendirector/application/model_catalog.py index f1cebf19b..272378255 100644 --- a/packages/core/src/opendirector/application/model_catalog.py +++ b/packages/core/src/opendirector/application/model_catalog.py @@ -63,6 +63,48 @@ def save_many(self, kind, url, model_ids, api_key, config_id=None, **options): def delete(self, config_id): self.configs.delete(config_id) + async def discover_many(self, kinds, url, api_key, *, connection_type='api', auth_mode=None, proxy_mode=None, + provider_id=None): + """Read model declarations for several modalities of one address. + + One modality failing does not abort the others; each result carries its + own error so the caller can retry only that part. + """ + existing = self._connection_key_source(provider_id) + if existing and existing.get('url') == (url or '').strip() and not api_key: + api_key = existing.get('apiKey', '') + outcomes = await asyncio.gather(*( + self._discover_one(kind['kind'], url, api_key, connection_type=connection_type, + protocol=kind.get('protocol'), auth_mode=auth_mode, proxy_mode=proxy_mode) + for kind in kinds)) + return [{'kind': kind['kind'], 'protocol': outcome['protocol'], 'models': outcome['models'], 'error': outcome['error']} + for kind, outcome in zip(kinds, outcomes)] + + def _connection_key_source(self, provider_id): + if not provider_id: + return None + return next((dict(row) for row, private in self.configs.catalog_snapshot() + if row.get('providerId') == str(provider_id)), None) + + async def _discover_one(self, kind, url, api_key, *, connection_type, protocol, auth_mode, proxy_mode): + try: + config = _draft(kind, url, 'discovery', api_key, connection_type, protocol, auth_mode, proxy_mode) + models = await read_service_models(config) + return {'protocol': config['protocol'], 'models': list(dict.fromkeys(item['id'] for item in models)), 'error': None} + except ProjectError as error: + resolved = None + try: + resolved = connection_fields(kind, connection_type, protocol, auth_mode, proxy_mode)['protocol'] + except ProjectError: + pass + return {'protocol': resolved, 'models': [], 'error': {'code': error.code, 'message': str(error)}} + + def save_connection(self, entries, url, api_key, *, connection_type='api', auth_mode=None, proxy_mode=None, + capability_auto_check=None, provider_id=None): + return self.configs.save_connection(url, api_key, entries, connection_type=connection_type, + auth_mode=auth_mode, proxy_mode=proxy_mode, + capability_auto_check=capability_auto_check, provider_id=provider_id) + def delete_service(self, config_id): self.configs.delete_service(config_id) diff --git a/packages/core/src/opendirector/infrastructure/model_configs.py b/packages/core/src/opendirector/infrastructure/model_configs.py index 9494704c4..f7a3a66e2 100644 --- a/packages/core/src/opendirector/infrastructure/model_configs.py +++ b/packages/core/src/opendirector/infrastructure/model_configs.py @@ -173,7 +173,7 @@ def _write(self, models: list[dict]) -> None: def save_many(self, kind: str, url: str, model_ids: list[str], api_key: str, config_id: str | None = None, *, connection_type='api', protocol=None, - auth_mode=None, proxy_mode=None, video_adapter=None, video_capabilities=None, input_modalities=None, model_options=None, capabilities_supplied=False, capability_auto_check=None) -> list[dict]: + auth_mode=None, proxy_mode=None, video_adapter=None, video_capabilities=None, input_modalities=None, model_options=None, capabilities_supplied=False, capability_auto_check=None, provider_id=None) -> list[dict]: if capability_auto_check is not None and type(capability_auto_check) is not bool: raise ProjectError('自动能力检查设置必须为布尔值。') if kind not in MODEL_KINDS or not 1 <= len(model_ids) <= 200: @@ -202,9 +202,11 @@ def save_many(self, kind: str, url: str, model_ids: list[str], api_key: str, if not existing or existing['url'] != fields[0]['url'] or not existing['apiKey']: raise ProjectError('请填写该服务的 API Key;新地址不能复用原地址的密钥。') key = existing['apiKey'] - provider_id = existing.get('providerId', existing['id']) if existing else str(uuid4()) + provider_id = provider_id or (existing.get('providerId', existing['id']) if existing else str(uuid4())) auto_check = capability_auto_check if capability_auto_check is not None else (existing or {}).get('capabilityAutoCheck') - previous = [item for item in models if item.get('providerId') == provider_id or item['id'] == config_id] + previous = [item for item in models + if (item.get('providerId') == provider_id and (item['kind'] == kind or (legacy_segmentation and item['id'] == config_id))) + or item['id'] == config_id] peers = {item['modelId']: item for item in previous} saved = [] for field in fields: @@ -234,6 +236,46 @@ def save_many(self, kind: str, url: str, model_ids: list[str], api_key: str, self._write(remaining + saved) return [self._public(item) for item in saved] + def save_connection(self, url: str, api_key: str, entries: list[dict], *, connection_type='api', auth_mode=None, + proxy_mode=None, capability_auto_check=None, provider_id=None) -> dict: + """Save several modalities of one address and credential as one connection. + + Entries commit independently: a rejected modality does not roll back the + ones that were saved, and the receipt reports both sets so callers can + retry only the failures. + """ + if not 1 <= len(entries) <= len(MODEL_KINDS): + raise ProjectError('请选择 1—5 个模态。') + if len({entry['kind'] for entry in entries}) != len(entries): + raise ProjectError('同一连接中每个模态只能出现一次。') + if capability_auto_check is not None and type(capability_auto_check) is not bool: + raise ProjectError('自动能力检查设置必须为布尔值。') + model_fields(url, 'connection', api_key) + kinds = [item['kind'] for item in entries] + if len(set(kinds)) != len(kinds): + raise ProjectError('同一连接中每个模态只能出现一次。') + with self.lock: + existing = self._read() + reused = next((item for item in existing if provider_id and item.get('providerId') == str(provider_id)), None) + if provider_id and reused is None: + raise ProjectError('连接已被删除,请重新加载。', 404) + shared = str(provider_id) if provider_id else str(uuid4()) + saved, rejected = [], [] + for entry in entries: + try: + saved.extend(self.save_many(entry['kind'], url, entry['modelIds'], api_key, provider_id=shared, + connection_type=connection_type, protocol=entry.get('protocol'), + auth_mode=auth_mode, proxy_mode=proxy_mode, + model_options=entry.get('modelOptions'), + capability_auto_check=capability_auto_check)) + except ProjectError as error: + rejected.append({'kind': entry['kind'], 'code': getattr(error, 'code', None) or 'connection_entry_invalid'}) + if not saved: + raise ProjectError('这个连接没有保存任何模型。', 400) + with self.lock: + peers = [item for item in self._read() if item.get('providerId') == shared] + return {'providerId': shared, 'saved': saved, 'rejected': rejected, 'kinds': sorted({item['kind'] for item in peers})} + def delete_service(self, config_id: str) -> None: with self.lock: models = self._read() diff --git a/scripts/run-browser-suite.mjs b/scripts/run-browser-suite.mjs index f0e75d69f..5163063d1 100644 --- a/scripts/run-browser-suite.mjs +++ b/scripts/run-browser-suite.mjs @@ -87,6 +87,7 @@ const workflows = [ env: { PYTHON: "python" }, }, { name: "first-run setup", script: "tests/browser/first_run.mjs" }, + { name: "multimodal connection", script: "tests/browser/model_connection.mjs" }, { name: "selection toolbar hover", script: "tests/browser/selection_toolbar_hover.mjs" }, { name: "model editor hosts", script: "tests/browser/model_editor_hosts.mjs" }, { name: "motion studio", script: "tests/browser/motion_studio.mjs" }, diff --git a/src/backend/models.ts b/src/backend/models.ts index d1f50f130..5533e8902 100644 --- a/src/backend/models.ts +++ b/src/backend/models.ts @@ -72,6 +72,53 @@ export function discoverModels(value: ModelConfigInput, configId?: string) { ); } +export type ConnectionKind = Exclude; + +export interface ConnectionDiscoveryRequest { + url: string; + apiKey: string; + connectionType: "api" | "self_hosted"; + authMode: "none" | "bearer"; + proxyMode: "system" | "direct"; + kinds: { kind: ConnectionKind; protocol: NonNullable }[]; +} + +export interface ConnectionDiscoveryResult { + kind: ConnectionKind; + protocol: NonNullable | null; + models: string[]; + error: { code: string; message: string } | null; +} + +export function discoverConnectionModels(value: ConnectionDiscoveryRequest) { + return request<{ results: ConnectionDiscoveryResult[] }>( + "/model-configs/discover-many", + json("POST", value), + ); +} + +export interface ConnectionSaveRequest { + url: string; + apiKey: string; + connectionType: "api" | "self_hosted"; + authMode: "none" | "bearer"; + proxyMode: "system" | "direct"; + capabilityAutoCheck?: boolean | null; + providerId?: string; + entries: { + kind: ConnectionKind; + protocol: NonNullable; + modelIds: string[]; + }[]; +} + +export interface ConnectionSaveReceipt { + providerId: string; + saved: ModelConfig[]; + rejected: { kind: ConnectionKind; code: string }[]; + kinds: ConnectionKind[]; +} + export function testAgentModel(value: ModelConfigInput, configId?: string) { return request<{ elapsedMs: number }>( "/model-configs/test-agent", @@ -292,6 +339,17 @@ export function useBackendModels() { await refresh(); void refreshAvailability([saved.id]); }; + const saveConnection = async (value: ConnectionSaveRequest) => { + epoch.current += 1; + const receipt = await request( + "/model-configs/connections", + json("POST", value), + ); + await refresh(); + void refreshAvailability(receipt.saved.map((model) => model.id)); + return receipt; + }; + const saveMany = async ( value: ModelConfigInput, modelIds: string[], @@ -341,6 +399,8 @@ export function useBackendModels() { refresh, save, saveMany, + saveConnection, + discoverConnectionModels, remove, removeService, updateSettings, diff --git a/src/canvas/ModelConnectionForm.tsx b/src/canvas/ModelConnectionForm.tsx new file mode 100644 index 000000000..63eef27df --- /dev/null +++ b/src/canvas/ModelConnectionForm.tsx @@ -0,0 +1,319 @@ +import { useId, useState, type FormEvent } from "react"; +import { errorMessage } from "../backend/api.ts"; +import { + MODEL_KINDS, + type BackendModels, + type ConnectionKind, + type ConnectionSaveReceipt, +} from "../backend/models.ts"; +import type { ModelConfig } from "../backend/rules.ts"; +import { useT } from "../i18n/I18nProvider"; +import type { MessageKey } from "../i18n/types"; +import { CanvasIcon } from "./CanvasIcon"; + +type Protocol = NonNullable; +type KindState = { + enabled: boolean; + protocol: Protocol; + models: string[]; + selected: string[]; + error: string; + fetched: boolean; +}; + +const KIND_PROTOCOLS: Record = { + agent: ["openai"], + image: ["openai", "volcengine"], + audio: ["openai", "volcengine"], + video: ["minimax_video_v2", "kling_video", "bigmodel_video", "higgsfield_open", "vllm_omni"], +}; +const REJECT_REASONS: Record = { + invalid_input: "models.connection.rejectReason.invalidInput", + connection_entry_invalid: "models.connection.rejectReason.invalidInput", + not_found: "models.connection.rejectReason.notFound", + model_list_http_error: "models.connection.rejectReason.serviceRejected", +}; +const PROTOCOL_LABELS: Record = { + openai: "models.protocolOption.openaiAgent", + volcengine: "models.protocolOption.volcengine", + minimax_video_v2: "models.protocolOption.minimaxVideo", + kling_video: "models.protocolOption.klingVideo", + bigmodel_video: "models.protocolOption.bigmodelVideo", + higgsfield_open: "models.protocolOption.higgsfieldOpen", + vllm_omni: "models.protocolOption.videos", +}; + +function initialKinds(): Record { + const state = {} as Record; + for (const { id } of MODEL_KINDS) { + state[id] = { + enabled: id === "agent", + protocol: KIND_PROTOCOLS[id][0], + models: [], + selected: [], + error: "", + fetched: false, + }; + } + return state; +} + +/** + * Adds one connection (address + credential) that carries several modalities. + * Discovery and saving stay per kind so a modality can fail without discarding + * the ones that succeeded. + */ +export function ModelConnectionForm({ + catalog, + onClose, + onSaved, +}: { + catalog: BackendModels; + onClose: () => void; + onSaved?: (receipt: ConnectionSaveReceipt) => void; +}) { + const t = useT(); + const fieldId = useId(); + const [url, setUrl] = useState(""); + const [apiKey, setApiKey] = useState(""); + const [showKey, setShowKey] = useState(false); + const [authMode, setAuthMode] = useState<"none" | "bearer">("bearer"); + const [proxyMode, setProxyMode] = useState<"system" | "direct">("direct"); + const [capabilityAutoCheck, setCapabilityAutoCheck] = useState(true); + const [kinds, setKinds] = useState(initialKinds); + const [discovering, setDiscovering] = useState(false); + const [discoveryError, setDiscoveryError] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(""); + const [receipt, setReceipt] = useState(null); + const enabled = (Object.keys(kinds) as ConnectionKind[]).filter((kind) => kinds[kind].enabled); + const selectedCount = enabled.reduce((total, kind) => total + kinds[kind].selected.length, 0); + const locked = busy || discovering; + const update = (kind: ConnectionKind, patch: Partial) => + setKinds((current) => ({ ...current, [kind]: { ...current[kind], ...patch } })); + + const discover = async () => { + if (locked || !enabled.length) return; + setDiscovering(true); + setDiscoveryError(""); + setError(""); + try { + const { results } = await catalog.discoverConnectionModels({ + url, + apiKey: authMode === "none" ? "" : apiKey, + connectionType: "api", + authMode, + proxyMode, + kinds: enabled.map((kind) => ({ kind, protocol: kinds[kind].protocol })), + }); + setKinds((current) => { + const next = { ...current }; + for (const result of results) { + const state = next[result.kind]; + if (!state) continue; + next[result.kind] = { + ...state, + models: result.models, + selected: result.error ? [] : result.models.filter((id) => state.selected.includes(id)), + error: result.error?.message ?? "", + fetched: !result.error, + }; + } + return next; + }); + if (results.every((result) => result.error)) setDiscoveryError(t("models.connection.discoveryFailed")); + } catch (failure) { + setDiscoveryError(errorMessage(failure)); + } finally { + setDiscovering(false); + } + }; + + const submit = async (event: FormEvent) => { + event.preventDefault(); + if (locked) return; + const entries = enabled + .filter((kind) => kinds[kind].selected.length) + .map((kind) => ({ kind, protocol: kinds[kind].protocol, modelIds: kinds[kind].selected })); + if (!entries.length) { + setError(t("models.connection.selectAtLeastOne")); + return; + } + setBusy(true); + setError(""); + try { + const saved = await catalog.saveConnection({ + url, + apiKey: authMode === "none" ? "" : apiKey, + connectionType: "api", + authMode, + proxyMode, + capabilityAutoCheck, + providerId: receipt?.providerId, + entries, + }); + setReceipt(saved); + if (!saved.rejected.length) onSaved?.(saved); + } catch (failure) { + setError(errorMessage(failure)); + } finally { + setBusy(false); + } + }; + + return ( +
void submit(event)} + > +
+ +
+

{t("models.connection.title")}

+

{t("models.connection.subtitle")}

+
+
+
+

{t("models.connection.hint")}

+
+
+ +
+
+ +
+
+ +
+
+
+
+ + +
+
+ setApiKey(event.target.value)} /> + +
+
+
+ {t("models.connection.kindsLabel")} + {MODEL_KINDS.map((spec) => { + const state = kinds[spec.id]; + const kindLabel = t(spec.labelKey); + return ( +
+
+ + {state.enabled && ( + + )} + {state.enabled && state.fetched && ( + + {t("models.connection.kindSelected", { count: state.selected.length })} + + )} +
+ {state.enabled && state.error &&

{state.error}

} + {state.enabled && state.models.length > 0 && ( +
+ {state.models.map((id) => ( + + ))} +
+ )} +
+ ); + })} +
+ {discoveryError &&

{discoveryError}

} + {receipt && ( +
+

{t("models.connection.savedKinds", { count: receipt.saved.length })}

+ {receipt.rejected.length > 0 && ( +
    + {receipt.rejected.map((item) => ( +
  • {t("models.connection.rejected", { + kind: t(MODEL_KINDS.find((spec) => spec.id === item.kind)?.labelKey ?? "models.category.agent"), + reason: REJECT_REASONS[item.code] ? t(REJECT_REASONS[item.code]) : item.code, + })}
  • + ))} +
+ )} +
+ )} +
+
+

+ {selectedCount + ? t("models.service.willEnable", { count: selectedCount }) + : t("models.connection.selectAtLeastOne")} +

+ + + + {error &&

{error}

} +
+
+ ); +} diff --git a/src/canvas/ModelSettings.tsx b/src/canvas/ModelSettings.tsx index 0dc2096ec..c56c7f966 100644 --- a/src/canvas/ModelSettings.tsx +++ b/src/canvas/ModelSettings.tsx @@ -8,6 +8,7 @@ import { MODEL_KINDS, type BackendModels } from "../backend/models.ts"; import type { ModelConfig } from "../backend/rules.ts"; import { useT } from "../i18n/I18nProvider"; import { ModelServiceForm, type SettingsModelKind } from "./ModelServiceForm"; +import { ModelConnectionForm } from "./ModelConnectionForm"; import { CanvasIcon } from "./CanvasIcon"; import "./model-settings.css"; @@ -26,6 +27,7 @@ export function ModelSettings({ kind: SettingsModelKind; model?: ModelConfig; } | null>(null); + const [addingConnection, setAddingConnection] = useState(false); const [deleting, setDeleting] = useState(null); const [busy, setBusy] = useState(false); const [error, setError] = useState(""); @@ -59,7 +61,11 @@ export function ModelSettings({ if (visibleIds && catalog.connected) void checkAvailability(visibleIds.split(",")); }, [visibleIds, catalog.connected, checkAvailability]); if (category === null) return
- + {addingConnection + ? setAddingConnection(false)} + onSaved={() => setAddingConnection(false)} /> + : setAddingConnection(true)} />}
; return (
@@ -75,7 +81,13 @@ export function ModelSettings({
)} {catalog.connected && - (editing ? ( + (addingConnection ? ( + setAddingConnection(false)} + onSaved={() => setAddingConnection(false)} + /> + ) : editing ? (

{t("models.services.hint")}

+ {services.length > 0 && ( + + )} {services.length > 0 && ( + )} {services.map((model) => { diff --git a/src/canvas/ModelSetup.tsx b/src/canvas/ModelSetup.tsx index c5b7bd1c1..69f3f2a9d 100644 --- a/src/canvas/ModelSetup.tsx +++ b/src/canvas/ModelSetup.tsx @@ -23,10 +23,11 @@ function modelSetupMissing(models: ModelConfig[]) { return kinds.filter(kind => !models.some(model => model.kind === kind && isGenerationModel(model))); } -export function ModelSetup({ catalog, onClose, onConfigure }: { +export function ModelSetup({ catalog, onClose, onConfigure, onAddConnection }: { catalog: BackendModels; onClose: () => void; onConfigure: (kind: SetupKind) => void; + onAddConnection?: () => void; }) { const { t, locale, setLocale } = useI18n(); const missing = modelSetupMissing(catalog.models); @@ -60,6 +61,11 @@ export function ModelSetup({ catalog, onClose, onConfigure }: {