From 6e737805e8d3235fa898d7a1b679a784326956c8 Mon Sep 17 00:00:00 2001 From: Kevin Hsiao Date: Fri, 27 Nov 2026 17:00:09 +0800 Subject: [PATCH] feat(byteplus-agentplan): integrate BytePlus Agent Plan across LLM, Seedream, and Seedance 2.5 skills (#8701) * feat(byteplus-agentplan): integrate BytePlus Agent Plan across LLM, Seedream, and Seedance 2.5 skills - Add `byteplus_agentplan` provider to `skills/public/video-generation` for Seedance 2.5 (`dreamina-seedance-2.5` / `dreamina-seedance-2.5-flash`) with multi-reference image support, native audio generation, same-origin redirect enforcement, BytePlus TOS download allowlist, and clear tier-upgrade guidance on HTTP 403 rejections. - Add `byteplus_agentplan` provider to `skills/public/image-generation` for Seedream (`dola-seedream-5.0-pro` / `5.5` / `5.0-flash`) with JSON reference images and safe decode-before-write handling, powering `ppt-generation` with the same API key. - Register `byteplus-agent-plan` in `managed_model_providers.py` and `byteplus_agentplan` in the interactive `make setup` wizard (auto-forwarding `BYTEPLUS_AGENTPLAN_API_KEY` into `sandbox.environment`). - Update `.env.example`, `provider_credentials.py`, `config.example.yaml`, READMEs, skills guide, and Ark model-provider docs. * fix(byteplus-agentplan): address review feedback on vision, Seedream prompt/format/aspect ratio, and test return flow * docs(byteplus-agentplan): append DeerFlow UTM parameters to BytePlus Agent Plan console and doc links * fix(byteplus-agentplan): require opt-in for sandbox key sharing and validate Seedream images before writing --- .env.example | 3 + README.md | 8 +- README_zh.md | 10 +- backend/docs/CONFIGURATION.md | 1 + .../community/provider_credentials.py | 1 + .../config/managed_model_providers.py | 14 ++ .../tests/test_managed_provider_presets.py | 14 +- backend/tests/test_setup_wizard.py | 75 +++++++ config.example.yaml | 53 +++++ docs/guide/skills-and-tools.md | 32 ++- .../en/reference/model-providers/ark.mdx | 61 ++++- .../zh/reference/model-providers/ark.mdx | 61 ++++- scripts/setup_wizard.py | 1 + scripts/wizard/providers.py | 37 +++ scripts/wizard/steps/llm.py | 14 ++ scripts/wizard/writer.py | 9 + skills/public/image-generation/SKILL.md | 15 +- .../image-generation/scripts/generate.py | 178 ++++++++++++++- skills/public/video-generation/AGENTS.md | 15 +- skills/public/video-generation/SKILL.md | 32 ++- .../video-generation/scripts/generate.py | 210 ++++++++++++++++-- tests/skills/test_image_generation.py | 187 ++++++++++++++++ .../skills/test_image_output_preservation.py | 11 +- tests/skills/test_video_generation.py | 201 +++++++++++++++++ tests/skills/test_video_generation_cli.py | 26 ++- .../test_video_generation_reference_mime.py | 37 ++- 26 files changed, 1228 insertions(+), 78 deletions(-) diff --git a/.env.example b/.env.example index 827c8f5e21..01939bb533 100644 --- a/.env.example +++ b/.env.example @@ -68,6 +68,9 @@ EXA_BASE_URL=https://api.exa.ai # Optional: # FIRECRAWL_API_KEY=your-firecrawl-api-key +# BytePlus Agent Plan (Personal & Enterprise): one key for LLM + Seedream images/slides + Seedance 2.5 video +# Subscribe at https://console.byteplus.com/ark/region:ap-southeast-1/subscription/agent-plan?utm_campaign=deer_flow&utm_content=deer_flow&utm_medium=devrel&utm_source=OWO&utm_term=deer_flow +# BYTEPLUS_AGENTPLAN_API_KEY=your-byteplus-agentplan-api-key # VOLCENGINE_API_KEY=your-volcengine-api-key # OPENAI_API_KEY=your-openai-api-key # OPENVIKING_API_KEY=your-openviking-user-api-key diff --git a/README.md b/README.md index 7b08db89c7..4ce50518bd 100644 --- a/README.md +++ b/README.md @@ -25,11 +25,11 @@ The landing-page case studies open as allowlisted, read-only showcases without r - [**LLM Space**](https://github.com/deer-flow/llm-space) - Meet our secret weapon behind DeerFlow — one desktop tool to prototype agent ideas, inspect each harness step, replay failures, and benchmark performance. -## Coding Plan from ByteDance Volcengine +## BytePlus Agent Plan -- We strongly recommend using Doubao-Seed-2.0-Code, DeepSeek v3.2 and Kimi 2.5 to run DeerFlow -- [Learn more](https://www.byteplus.com/en/activity/codingplan?utm_campaign=deer_flow&utm_content=deer_flow&utm_medium=devrel&utm_source=OWO&utm_term=deer_flow) -- [中国大陆地区的开发者请点击这里](https://www.volcengine.com/activity/codingplan?utm_campaign=deer_flow&utm_content=deer_flow&utm_medium=devrel&utm_source=OWO&utm_term=deer_flow) +- One key for LLMs, Seedream images/slides & Seedance 2.5 video +- [BytePlus Agent Plan](https://www.byteplus.com/en/activity/agentplan?utm_campaign=deer_flow&utm_content=deer_flow&utm_medium=devrel&utm_source=OWO&utm_term=deer_flow) +- [中国大陆地区请点击这里](https://www.volcengine.com/activity/codingplan?utm_campaign=deer_flow&utm_content=deer_flow&utm_medium=devrel&utm_source=OWO&utm_term=deer_flow) ## InfoQuest diff --git a/README_zh.md b/README_zh.md index 9ff9b3ed3c..3968476689 100644 --- a/README_zh.md +++ b/README_zh.md @@ -27,11 +27,11 @@ https://github.com/user-attachments/assets/a8bcadc4-e040-4cf2-8fda-dd768b999c18 - [**LLM Space**](https://github.com/deer-flow/llm-space) - 认识 DeerFlow 背后的秘密武器——一款桌面工具,用于原型化 agent 想法、检查 harness 的每个步骤、回放失败用例并基准测试性能。 -## 字节跳动火山引擎方舟 Coding Plan +## BytePlus Agent Plan 与火山引擎方舟 Coding Plan -- 我们推荐使用 Doubao-Seed-2.0-Code、DeepSeek v3.2 和 Kimi 2.5 运行 DeerFlow -- [现在就加入 Coding Plan](https://www.volcengine.com/activity/codingplan?utm_campaign=deer_flow&utm_content=deer_flow&utm_medium=devrel&utm_source=OWO&utm_term=deer_flow) -- [海外地区的开发者请点击这里](https://www.byteplus.com/en/activity/codingplan?utm_campaign=deer_flow&utm_content=deer_flow&utm_medium=devrel&utm_source=OWO&utm_term=deer_flow) +- **BytePlus Agent Plan(个人版 & 企业版)**:一把 API Key 打通 DeerFlow 全链路——旗舰对话模型(`dola-seed-2.1-turbo`、`deepseek-v4-pro`、`deepseek-v4.1-flash`)、**Seedream 5.0/5.5** 生图与 PPT 视觉生成(`image-generation` / `ppt-generation`),以及 **Seedance 2.5** 原生音画同步视频生成(`video-generation`,Large / Max / 企业共享包可用),统一以透明的 AFP(Agent Fuel Points)计量。 +- [了解 BytePlus Agent Plan](https://www.byteplus.com/en/activity/agentplan?utm_campaign=deer_flow&utm_content=deer_flow&utm_medium=devrel&utm_source=OWO&utm_term=deer_flow) · [控制台](https://console.byteplus.com/ark/region:ap-southeast-1/subscription/agent-plan?utm_campaign=deer_flow&utm_content=deer_flow&utm_medium=devrel&utm_source=OWO&utm_term=deer_flow) · [个人版文档](https://console.byteplus.com/ark/region:ap-southeast-1/docs/agent-plan-personal-plan-overview?utm_campaign=deer_flow&utm_content=deer_flow&utm_medium=devrel&utm_source=OWO&utm_term=deer_flow) · [企业版文档](https://console.byteplus.com/ark/region:ap-southeast-1/docs/agent-plan-enterprise-plan-overview?utm_campaign=deer_flow&utm_content=deer_flow&utm_medium=devrel&utm_source=OWO&utm_term=deer_flow) +- [中国大陆地区的开发者请点击这里(火山引擎 Coding Plan)](https://www.volcengine.com/activity/codingplan?utm_campaign=deer_flow&utm_content=deer_flow&utm_medium=devrel&utm_source=OWO&utm_term=deer_flow) ## InfoQuest @@ -50,7 +50,7 @@ DeerFlow 新近集成了 BytePlus 自研的智能搜索与抓取工具集——[ - [🦌 DeerFlow - 2.0](#-deerflow---20) - [官网](#官网) - [姐妹项目](#姐妹项目) - - [字节跳动火山引擎方舟 Coding Plan](#字节跳动火山引擎方舟-coding-plan) + - [BytePlus Agent Plan 与火山引擎方舟 Coding Plan](#byteplus-agent-plan-与火山引擎方舟-coding-plan) - [InfoQuest](#infoquest) - [目录](#目录) - [一句话交给 Coding Agent 安装](#一句话交给-coding-agent-安装) diff --git a/backend/docs/CONFIGURATION.md b/backend/docs/CONFIGURATION.md index 93b1f20cd5..103226fb14 100644 --- a/backend/docs/CONFIGURATION.md +++ b/backend/docs/CONFIGURATION.md @@ -354,6 +354,7 @@ are: | `qwen-cn` | Alibaba Cloud Bailian / Qwen, China | `https://dashscope.aliyuncs.com/compatible-mode/v1` | Chat Completions / Bearer | | `doubao` | Volcengine Beijing, ordinary API | `https://ark.cn-beijing.volces.com/api/v3` | Chat Completions / Bearer | | `doubao-coding` | Volcengine Coding Plan, separate key/plan | `https://ark.cn-beijing.volces.com/api/coding/v3` | Chat Completions / Bearer | +| `byteplus-agent-plan` | BytePlus Agent Plan (Personal & Enterprise), separate key/plan | `https://ark.ap-southeast.bytepluses.com/api/plan/v3` | Chat Completions / Bearer | | `moonshot-cn` | Moonshot / Kimi, China API | `https://api.moonshot.cn/v1` | Chat Completions / Bearer | | `zhipu-cn` | Zhipu, China ordinary API | `https://open.bigmodel.cn/api/paas/v4` | Chat Completions / Bearer | | `zai` | Z.AI, international ordinary API | `https://api.z.ai/api/paas/v4` | Chat Completions / Bearer | diff --git a/backend/packages/harness/deerflow/community/provider_credentials.py b/backend/packages/harness/deerflow/community/provider_credentials.py index 79c1210352..3f01e1cc3c 100644 --- a/backend/packages/harness/deerflow/community/provider_credentials.py +++ b/backend/packages/harness/deerflow/community/provider_credentials.py @@ -40,6 +40,7 @@ ENV_TEMPLATE_PLACEHOLDERS = frozenset( "your-anthropic-auth-token", "your-boxd-api-key", "your-byteplus-access-key-id", + "your-byteplus-agentplan-api-key", "your-byteplus-secret-access-key", "your-claude-code-oauth-token", "your-deepseek-api-key", diff --git a/backend/packages/harness/deerflow/config/managed_model_providers.py b/backend/packages/harness/deerflow/config/managed_model_providers.py index 27840c1453..cce2847cd3 100644 --- a/backend/packages/harness/deerflow/config/managed_model_providers.py +++ b/backend/packages/harness/deerflow/config/managed_model_providers.py @@ -41,6 +41,7 @@ PROVIDERS = ( ManagedModelProvider("qwen-cn", "Alibaba Cloud Bailian / Qwen (China)", "https://dashscope.aliyuncs.com/compatible-mode/v1", _DEEPSEEK, endpoint_parameter="api_base"), ManagedModelProvider("doubao", "Volcengine / Doubao (Beijing, API)", "https://ark.cn-beijing.volces.com/api/v3", _DEEPSEEK, endpoint_parameter="api_base"), ManagedModelProvider("doubao-coding", "Volcengine (Coding Plan)", "https://ark.cn-beijing.volces.com/api/coding/v3", _DEEPSEEK, endpoint_parameter="api_base"), + ManagedModelProvider("byteplus-agent-plan", "BytePlus (Agent Plan)", "https://ark.ap-southeast.bytepluses.com/api/plan/v3", _DEEPSEEK, endpoint_parameter="api_base"), ManagedModelProvider("moonshot-cn", "Moonshot / Kimi (China)", "https://api.moonshot.cn/v1", _DEEPSEEK, endpoint_parameter="api_base"), ManagedModelProvider("zhipu-cn", "Zhipu (China, API)", "https://open.bigmodel.cn/api/paas/v4", _DEEPSEEK, endpoint_parameter="api_base"), ManagedModelProvider("zai", "Z.AI (International, API)", "https://api.z.ai/api/paas/v4", _DEEPSEEK, endpoint_parameter="api_base"), @@ -131,6 +132,19 @@ def _capabilities(provider: str, model: str) -> dict[str, Any]: when_thinking_enabled={"extra_body": {"thinking": {"type": "enabled"}}}, when_thinking_disabled={"extra_body": {"thinking": {"type": "disabled"}}}, ) + elif provider == "byteplus-agent-plan" and model in {"dola-seed-2.1-turbo", "deepseek-v4.1-flash", "seed-2.0-lite", "seed-2.0-mini"}: + result.update( + supports_vision=True, + reasoning={"thinking": "optional", "dialect": "openai_extra_body", "history": "preserve"}, + when_thinking_enabled={"extra_body": {"thinking": {"type": "enabled"}}}, + when_thinking_disabled={"extra_body": {"thinking": {"type": "disabled"}}}, + ) + elif provider == "byteplus-agent-plan" and model in {"deepseek-v4-pro", "deepseek-v4.1-flash-economy"}: + result.update( + reasoning={"thinking": "optional", "dialect": "openai_extra_body", "history": "preserve"}, + when_thinking_enabled={"extra_body": {"thinking": {"type": "enabled"}}}, + when_thinking_disabled={"extra_body": {"thinking": {"type": "disabled"}}}, + ) elif provider == "moonshot-cn" and model == "kimi-k2.5": result.update( supports_vision=True, diff --git a/backend/tests/test_managed_provider_presets.py b/backend/tests/test_managed_provider_presets.py index 03b46441c2..389959d925 100644 --- a/backend/tests/test_managed_provider_presets.py +++ b/backend/tests/test_managed_provider_presets.py @@ -32,6 +32,7 @@ def store(tmp_path, monkeypatch): ("deepseek", "https://api.deepseek.com", "deerflow.models.patched_deepseek:PatchedChatDeepSeek"), ("qwen-cn", "https://dashscope.aliyuncs.com/compatible-mode/v1", "deerflow.models.patched_deepseek:PatchedChatDeepSeek"), ("doubao", "https://ark.cn-beijing.volces.com/api/v3", "deerflow.models.patched_deepseek:PatchedChatDeepSeek"), + ("byteplus-agent-plan", "https://ark.ap-southeast.bytepluses.com/api/plan/v3", "deerflow.models.patched_deepseek:PatchedChatDeepSeek"), ("moonshot-cn", "https://api.moonshot.cn/v1", "deerflow.models.patched_deepseek:PatchedChatDeepSeek"), ("zai", "https://api.z.ai/api/paas/v4", "deerflow.models.patched_deepseek:PatchedChatDeepSeek"), ("minimax", "https://api.minimax.io/v1", "deerflow.models.patched_minimax:PatchedChatMiniMax"), @@ -261,7 +262,7 @@ async def test_probe_and_chat_share_real_sdk_protocol_and_auth(store, wire, prov @pytest.mark.asyncio -@pytest.mark.parametrize("provider,model", [("deepseek", "deepseek-v4-flash"), ("anthropic", "claude-sonnet-4-5-20250929"), ("minimax", "MiniMax-M3"), ("moonshot-cn", "kimi-k2.5")]) +@pytest.mark.parametrize("provider,model", [("deepseek", "deepseek-v4-flash"), ("anthropic", "claude-sonnet-4-5-20250929"), ("minimax", "MiniMax-M3"), ("moonshot-cn", "kimi-k2.5"), ("byteplus-agent-plan", "dola-seed-2.1-turbo")]) async def test_known_optional_thinking_disabled_only_for_probe(store, wire, provider, model): profile = ManagedModel(provider=provider, model=model, api_key="secret-test-key") config = profile.runtime_config() @@ -402,6 +403,17 @@ def test_reasoning_cannot_override_preset_routing_or_credentials(path): ManagedModel(provider="openai", model="x", api_key="secret-test-key", reasoning={"thinking": "required", "effort": {"values": ["high"], "default": "high", "path": path}}) +def test_byteplus_agent_plan_vision_capabilities_match_documented_models(): + for model_id in ("dola-seed-2.1-turbo", "deepseek-v4.1-flash", "seed-2.0-lite", "seed-2.0-mini"): + runtime = ManagedModel(provider="byteplus-agent-plan", model=model_id, api_key="test-key").runtime_config() + assert runtime.supports_vision is True + assert runtime.supports_thinking is True + for model_id in ("deepseek-v4-pro", "deepseek-v4.1-flash-economy"): + runtime = ManagedModel(provider="byteplus-agent-plan", model=model_id, api_key="test-key").runtime_config() + assert runtime.supports_vision is False + assert runtime.supports_thinking is True + + def test_reasoning_contract_override_is_preserved_and_validated(store): profile = ManagedModel(provider="deepseek", model="deepseek-v4-pro", api_key="test", reasoning={"thinking": "unsupported", "dialect": "none"}, supports_vision=False) saved = store.save(profile, expected_revision=None) diff --git a/backend/tests/test_setup_wizard.py b/backend/tests/test_setup_wizard.py index 727a278425..ced4382945 100644 --- a/backend/tests/test_setup_wizard.py +++ b/backend/tests/test_setup_wizard.py @@ -29,6 +29,7 @@ class TestProviders: providers = {provider.name: provider for provider in LLM_PROVIDERS} expected = { + "byteplus_agentplan", "volcengine", "zai", "openai", @@ -57,6 +58,31 @@ class TestProviders: assert providers["mimo"].use == "deerflow.models.patched_mimo:PatchedChatMiMo" assert providers["deepseek"].use == "deerflow.models.patched_deepseek:PatchedChatDeepSeek" assert providers["volcengine"].extra_config["api_base"] == "https://ark.cn-beijing.volces.com/api/v3" + assert providers["byteplus_agentplan"].extra_config["api_base"] == "https://ark.ap-southeast.bytepluses.com/api/plan/v3" + assert providers["byteplus_agentplan"].sandbox_env_vars == ("BYTEPLUS_AGENTPLAN_API_KEY",) + + def test_byteplus_agentplan_vision_and_sandbox_env_wiring(self): + provider = next(p for p in LLM_PROVIDERS if p.name == "byteplus_agentplan") + assert provider.default_model == "dola-seed-2.1-turbo" + assert provider.extra_config_for("dola-seed-2.1-turbo")["supports_vision"] is True + assert provider.extra_config_for("deepseek-v4.1-flash")["supports_vision"] is True + assert provider.extra_config_for("deepseek-v4-pro")["supports_vision"] is False + assert provider.extra_config_for("deepseek-v4.1-flash-economy")["supports_vision"] is False + + content = build_minimal_config( + provider_use=provider.use, + model_name=provider.default_model, + display_name=f"{provider.display_name} / {provider.default_model}", + api_key_field=provider.api_key_field, + env_var=provider.env_var, + extra_model_config=provider.extra_config_for(provider.default_model), + sandbox_env_vars=provider.sandbox_env_vars, + ) + data = yaml.safe_load(content) + model = data["models"][0] + assert model["api_base"] == "https://ark.ap-southeast.bytepluses.com/api/plan/v3" + assert model["api_key"] == "$BYTEPLUS_AGENTPLAN_API_KEY" + assert data["sandbox"]["environment"]["BYTEPLUS_AGENTPLAN_API_KEY"] == "$BYTEPLUS_AGENTPLAN_API_KEY" def test_zai_glm_flash_declares_the_reasoning_contract(self): """GLM-5.3-Flash cannot disable thinking and only accepts low/high/max (issue #5073). @@ -648,6 +674,55 @@ class TestLLMStep: assert result.provider.extra_config["supports_thinking"] is False assert "when_thinking_enabled" not in result.provider.extra_config + def test_byteplus_agentplan_sandbox_sharing_is_opt_in(self, monkeypatch): + provider = next(p for p in LLM_PROVIDERS if p.name == "byteplus_agentplan") + asked: list[tuple[str, bool]] = [] + + monkeypatch.setattr(llm_step, "LLM_PROVIDERS", [provider]) + monkeypatch.setattr(llm_step, "ask_choice", lambda *_args, **_kwargs: 0) + monkeypatch.setattr(llm_step, "ask_secret", lambda _prompt: "bp-secret") + monkeypatch.setattr(llm_step, "print_header", lambda *_args, **_kwargs: None) + monkeypatch.setattr(llm_step, "print_info", lambda *_args, **_kwargs: None) + monkeypatch.setattr(llm_step, "print_success", lambda *_args, **_kwargs: None) + + def decline(prompt, default=True): + asked.append((prompt, default)) + return False + + monkeypatch.setattr(llm_step, "ask_yes_no", decline) + declined = llm_step.run_llm_step() + + assert asked == [("Share BYTEPLUS_AGENTPLAN_API_KEY with sandboxes?", False)] + assert declined.sandbox_env_vars == () + declined_cfg = yaml.safe_load( + build_minimal_config( + provider_use=declined.provider.use, + model_name=declined.model_name, + display_name=declined.provider.display_name, + api_key_field=declined.provider.api_key_field, + env_var=declined.provider.env_var, + extra_model_config=declined.provider.extra_config_for(declined.model_name), + sandbox_env_vars=declined.sandbox_env_vars or None, + ) + ) + assert "environment" not in declined_cfg["sandbox"] + + monkeypatch.setattr(llm_step, "ask_yes_no", lambda *_args, **_kwargs: True) + accepted = llm_step.run_llm_step() + assert accepted.sandbox_env_vars == ("BYTEPLUS_AGENTPLAN_API_KEY",) + accepted_cfg = yaml.safe_load( + build_minimal_config( + provider_use=accepted.provider.use, + model_name=accepted.model_name, + display_name=accepted.provider.display_name, + api_key_field=accepted.provider.api_key_field, + env_var=accepted.provider.env_var, + extra_model_config=accepted.provider.extra_config_for(accepted.model_name), + sandbox_env_vars=accepted.sandbox_env_vars or None, + ) + ) + assert accepted_cfg["sandbox"]["environment"]["BYTEPLUS_AGENTPLAN_API_KEY"] == "$BYTEPLUS_AGENTPLAN_API_KEY" + class TestChannelsStep: def test_returns_selected_channel_keys(self, monkeypatch): diff --git a/config.example.yaml b/config.example.yaml index 1427bab5ff..db746b40af 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -179,6 +179,53 @@ models: # thinking: # type: disabled + # Example: BytePlus Agent Plan (Personal & Enterprise — one key for LLM + Seedream images/slides + Seedance 2.5 video) + # Endpoint: https://ark.ap-southeast.bytepluses.com/api/plan/v3 + # Subscribe or manage seats/shared packages at: + # https://console.byteplus.com/ark/region:ap-southeast-1/subscription/agent-plan?utm_campaign=deer_flow&utm_content=deer_flow&utm_medium=devrel&utm_source=OWO&utm_term=deer_flow + # Also forward BYTEPLUS_AGENTPLAN_API_KEY in sandbox.environment below so + # image-generation (Seedream), ppt-generation, and video-generation (Seedance 2.5, Large/Max/Shared) work with the same key. + # + # - name: dola-seed-2.1-turbo-ap + # display_name: Dola-Seed-2.1-Turbo (BytePlus Agent Plan) + # use: deerflow.models.patched_deepseek:PatchedChatDeepSeek + # model: dola-seed-2.1-turbo + # api_base: https://ark.ap-southeast.bytepluses.com/api/plan/v3 + # api_key: $BYTEPLUS_AGENTPLAN_API_KEY + # timeout: 600.0 + # max_retries: 2 + # supports_thinking: true + # supports_vision: true + # supports_reasoning_effort: true + # when_thinking_enabled: + # extra_body: + # thinking: + # type: enabled + # when_thinking_disabled: + # extra_body: + # thinking: + # type: disabled + # + # - name: deepseek-v4-pro-ap + # display_name: DeepSeek-V4-Pro (BytePlus Agent Plan) + # use: deerflow.models.patched_deepseek:PatchedChatDeepSeek + # model: deepseek-v4-pro + # api_base: https://ark.ap-southeast.bytepluses.com/api/plan/v3 + # api_key: $BYTEPLUS_AGENTPLAN_API_KEY + # timeout: 600.0 + # max_retries: 2 + # supports_thinking: true + # supports_vision: false + # supports_reasoning_effort: true + # when_thinking_enabled: + # extra_body: + # thinking: + # type: enabled + # when_thinking_disabled: + # extra_body: + # thinking: + # type: disabled + # Example: Volcengine Coding Plan (one key, multi-vendor gateway) # The Coding Plan endpoint (/api/coding/v3) lets you access models from # Doubao, GLM, DeepSeek, Kimi, and MiniMax with a single API key. @@ -1914,6 +1961,12 @@ sandbox: # # IMAGE_GENERATION_BASE_URL: $IMAGE_GENERATION_BASE_URL # # IMAGE_GENERATION_MODEL: $IMAGE_GENERATION_MODEL # # IMAGE_GENERATION_SIZE: $IMAGE_GENERATION_SIZE # Optional fixed-size override +# # # BytePlus Agent Plan multimodal skills (Seedream images/slides + Seedance 2.5 video): +# # BYTEPLUS_AGENTPLAN_API_KEY: $BYTEPLUS_AGENTPLAN_API_KEY +# # # BYTEPLUS_AGENTPLAN_IMAGE_MODEL: dola-seedream-5.0-pro +# # # BYTEPLUS_AGENTPLAN_VIDEO_MODEL: dreamina-seedance-2.5 +# # # BYTEPLUS_AGENTPLAN_VIDEO_RESOLUTION: 720p +# # # BYTEPLUS_AGENTPLAN_VIDEO_DURATION: "6" # # # Optional: Cross-instance container ownership (issue #4206). # # diff --git a/docs/guide/skills-and-tools.md b/docs/guide/skills-and-tools.md index 548723c08e..33f27b9d6e 100644 --- a/docs/guide/skills-and-tools.md +++ b/docs/guide/skills-and-tools.md @@ -163,6 +163,20 @@ Skills are what make DeerFlow do *almost anything*. A standard Agent Skill is a structured capability module — a Markdown file that defines a workflow, best practices, and references to supporting resources. DeerFlow ships with built-in skills for research, report generation, slide creation, web pages, image and video generation, and more. But the real power is extensibility: add your own skills, replace the built-in ones, or combine them into compound workflows. +For BytePlus Agent Plan, the [video-generation skill](../../skills/public/video-generation/SKILL.md) +accepts `BYTEPLUS_AGENTPLAN_API_KEY` (auto-selected when neither Gemini nor +MiniMax keys are set, or forced with `VIDEO_GENERATION_PROVIDER=byteplus_agentplan`) +and submits Seedance 2.5 tasks to `https://ark.ap-southeast.bytepluses.com/api/plan/v3/contents/generations/tasks` +(default model `dreamina-seedance-2.5`; override with `BYTEPLUS_AGENTPLAN_VIDEO_MODEL`, +`BYTEPLUS_AGENTPLAN_VIDEO_RESOLUTION`, `BYTEPLUS_AGENTPLAN_VIDEO_DURATION` in +`4..30` or `-1`, and `BYTEPLUS_AGENTPLAN_GENERATE_AUDIO`). All `--reference-images` +are forwarded as `role: "reference_image"` data URLs. Video downloads trust +BytePlus Ark TOS storage endpoints by default (`tos-ap-southeast-1.volces.com`, +`tos-ap-southeast-1.bytepluses.com`, `tos-cn-beijing.volces.com`) and honor +exact extra hostnames listed in `BYTEPLUS_AGENTPLAN_VIDEO_DOWNLOAD_HOSTS`. +Seedance 2.5 video generation requires BytePlus Agent Plan Large, Max, or +Enterprise Shared Package; HTTP 403 tier rejections surface an upgrade hint. + For MiniMax, the [video-generation skill](../../skills/public/video-generation/SKILL.md) accepts `MINIMAX_VIDEO_RESOLUTION` and `MINIMAX_VIDEO_DURATION` (integer seconds). Unset overrides use the provider defaults. Invalid duration strings fail before @@ -306,16 +320,20 @@ Skill projection manifest saves preserve the original error or interruption even └── lark-cli/lark-doc/SKILL.md ← managed, read-only ``` -The built-in `image-generation` skill supports Gemini, MiniMax, and -OpenAI-compatible Images APIs. Select the latter with -`IMAGE_GENERATION_PROVIDER=openai`, then configure +The built-in `image-generation` skill supports Gemini, MiniMax, +OpenAI-compatible Images APIs, and BytePlus Agent Plan (Seedream). Select +OpenAI-compatible with `IMAGE_GENERATION_PROVIDER=openai`, then configure `IMAGE_GENERATION_API_KEY`, `IMAGE_GENERATION_BASE_URL`, and -`IMAGE_GENERATION_MODEL`. If the explicitly selected provider's API key is missing, +`IMAGE_GENERATION_MODEL`. For BytePlus Agent Plan, set +`BYTEPLUS_AGENTPLAN_API_KEY` (and optionally `IMAGE_GENERATION_PROVIDER=byteplus_agentplan`, +`BYTEPLUS_AGENTPLAN_IMAGE_MODEL` defaulting to `dola-seedream-5.0-pro`, and +`BYTEPLUS_AGENTPLAN_IMAGE_SIZE`) — the same key also powers `ppt-generation` +slide rendering. If the explicitly selected provider's API key is missing, the CLI reports the missing key on stderr and exits with status 1. Run the skill's script in an isolated sandbox such as -Docker/AIO, the Kubernetes provisioner, or E2B, and pass the variables through -`sandbox.environment`. Sandbox commands do not inherit API keys from the Gateway -process. +Docker/AIO, the Kubernetes provisioner, E2B, or veFaaS, and pass the variables +through `sandbox.environment`. Sandbox commands do not inherit API keys from +the Gateway process. The local provider applies the skill view through its workspace file tools. Script-based skills require an isolated sandbox provider on Windows as well. diff --git a/frontend/src/content/en/reference/model-providers/ark.mdx b/frontend/src/content/en/reference/model-providers/ark.mdx index 5956d691b3..f882703e98 100644 --- a/frontend/src/content/en/reference/model-providers/ark.mdx +++ b/frontend/src/content/en/reference/model-providers/ark.mdx @@ -1,8 +1,61 @@ --- -title: Volcano Ark -description: Integration guide for the Volcano Ark model provider. +title: BytePlus ModelArk & Volcano Ark +description: Integration guide for BytePlus Agent Plan (Personal & Enterprise) and Volcano Ark Coding Plan. --- -# Volcano Ark +# BytePlus ModelArk & Volcano Ark -## Coding Plan +## BytePlus Agent Plan (Personal & Enterprise) + +[BytePlus Agent Plan](https://www.byteplus.com/en/activity/agentplan?utm_campaign=deer_flow&utm_content=deer_flow&utm_medium=devrel&utm_source=OWO&utm_term=deer_flow) provides a unified Agent Fuel Points (AFP) subscription across flagship LLMs, **Seedream** image generation, and **Seedance 2.5** video generation with native synchronized audio — using a single dedicated API key and OpenAI-compatible base URL: + +- **Base URL**: `https://ark.ap-southeast.bytepluses.com/api/plan/v3` +- **Subscription Console**: [ModelArk Agent Plan](https://console.byteplus.com/ark/region:ap-southeast-1/subscription/agent-plan?utm_campaign=deer_flow&utm_content=deer_flow&utm_medium=devrel&utm_source=OWO&utm_term=deer_flow) +- **Official Docs**: [Personal Edition](https://console.byteplus.com/ark/region:ap-southeast-1/docs/agent-plan-personal-plan-overview?utm_campaign=deer_flow&utm_content=deer_flow&utm_medium=devrel&utm_source=OWO&utm_term=deer_flow) · [Enterprise / Team Edition](https://console.byteplus.com/ark/region:ap-southeast-1/docs/agent-plan-enterprise-plan-overview?utm_campaign=deer_flow&utm_content=deer_flow&utm_medium=devrel&utm_source=OWO&utm_term=deer_flow) + +> **Plan Tiers Note**: Language models (`dola-seed-2.1-turbo`, `deepseek-v4-pro`, `deepseek-v4.1-flash`, `seed-2.0-lite`, `seed-2.0-mini`) and Seedream image models (`dola-seedream-5.0-pro`, `dola-seedream-5.5`, `dola-seedream-5.0-flash`) are included across all tiers (Small, Medium, Large, Max, and Enterprise Shared Package). **Seedance 2.5** video generation (`dreamina-seedance-2.5` and `dreamina-seedance-2.5-flash`) requires **Large**, **Max**, or **Enterprise Shared Package**. + +### Quick Setup (`make setup`) + +Run `make setup` and choose **BytePlus Agent Plan**. The wizard writes your LLM model profile and asks whether to also share `BYTEPLUS_AGENTPLAN_API_KEY` with `sandbox.environment` (default: No) so `image-generation` (Seedream), `ppt-generation`, and `video-generation` (Seedance 2.5) can reuse the same key inside sandboxes. + +### Manual `config.yaml` Configuration + +```yaml +models: + - name: dola-seed-2.1-turbo-ap + display_name: Dola-Seed-2.1-Turbo (BytePlus Agent Plan) + use: deerflow.models.patched_deepseek:PatchedChatDeepSeek + model: dola-seed-2.1-turbo + api_base: https://ark.ap-southeast.bytepluses.com/api/plan/v3 + api_key: $BYTEPLUS_AGENTPLAN_API_KEY + timeout: 600.0 + max_retries: 2 + supports_thinking: true + supports_vision: true + supports_reasoning_effort: true + when_thinking_enabled: + extra_body: + thinking: + type: enabled + when_thinking_disabled: + extra_body: + thinking: + type: disabled + +sandbox: + use: deerflow.community.aio_sandbox:AioSandboxProvider + environment: + BYTEPLUS_AGENTPLAN_API_KEY: $BYTEPLUS_AGENTPLAN_API_KEY + # Optional overrides: + # BYTEPLUS_AGENTPLAN_IMAGE_MODEL: dola-seedream-5.0-pro + # BYTEPLUS_AGENTPLAN_VIDEO_MODEL: dreamina-seedance-2.5 + # BYTEPLUS_AGENTPLAN_VIDEO_RESOLUTION: 720p + # BYTEPLUS_AGENTPLAN_VIDEO_DURATION: "6" +``` + +For multi-user team deployments running batch multimodal or video workloads, see the [Enterprise / Team Edition documentation](https://console.byteplus.com/ark/region:ap-southeast-1/docs/agent-plan-enterprise-plan-overview?utm_campaign=deer_flow&utm_content=deer_flow&utm_medium=devrel&utm_source=OWO&utm_term=deer_flow) for team seat and shared-package options, and pair with the **BytePlus veFaaS Cloud Sandbox** provider. + +## Volcano Ark Coding Plan (China Mainland) + +For developers in Mainland China using Volcengine Coding Plan, select **Volcengine Coding Plan** in `make setup` or configure `api_base: https://ark.cn-beijing.volces.com/api/coding/v3` with `$VOLCENGINE_API_KEY` (see `config.example.yaml`). diff --git a/frontend/src/content/zh/reference/model-providers/ark.mdx b/frontend/src/content/zh/reference/model-providers/ark.mdx index 6f6e4ed123..ec4a65ac8c 100644 --- a/frontend/src/content/zh/reference/model-providers/ark.mdx +++ b/frontend/src/content/zh/reference/model-providers/ark.mdx @@ -1,8 +1,61 @@ --- -title: 火山方舟 -description: 火山方舟模型接入指南。 +title: BytePlus ModelArk 与火山方舟 +description: BytePlus Agent Plan(个人版 / 企业版)与火山方舟 Coding Plan 模型接入指南。 --- -# 火山方舟 +# BytePlus ModelArk 与火山方舟 -## Coding Plan +## BytePlus Agent Plan(个人版 & 企业版) + +[BytePlus Agent Plan](https://www.byteplus.com/en/activity/agentplan?utm_campaign=deer_flow&utm_content=deer_flow&utm_medium=devrel&utm_source=OWO&utm_term=deer_flow) 通过统一的 **AFP(Agent Fuel Points)** 额度体系,用**一把专属 API Key** 同时驱动 DeerFlow 的对话/推理大模型、**Seedream** 生图/PPT 视觉生成与 **Seedance 2.5** 原生音画同步视频生成: + +- **Base URL**:`https://ark.ap-southeast.bytepluses.com/api/plan/v3` +- **订阅控制台**:[ModelArk Agent Plan](https://console.byteplus.com/ark/region:ap-southeast-1/subscription/agent-plan?utm_campaign=deer_flow&utm_content=deer_flow&utm_medium=devrel&utm_source=OWO&utm_term=deer_flow) +- **官方文档**:[个人版文档](https://console.byteplus.com/ark/region:ap-southeast-1/docs/agent-plan-personal-plan-overview?utm_campaign=deer_flow&utm_content=deer_flow&utm_medium=devrel&utm_source=OWO&utm_term=deer_flow) · [企业版文档](https://console.byteplus.com/ark/region:ap-southeast-1/docs/agent-plan-enterprise-plan-overview?utm_campaign=deer_flow&utm_content=deer_flow&utm_medium=devrel&utm_source=OWO&utm_term=deer_flow) + +> **套餐档位说明**:语言模型(`dola-seed-2.1-turbo`、`deepseek-v4-pro`、`deepseek-v4.1-flash`、`seed-2.0-lite`、`seed-2.0-mini`)与 Seedream 生图模型(`dola-seedream-5.0-pro`、`dola-seedream-5.5`、`dola-seedream-5.0-flash`)支持全档位套餐;**Seedance 2.5** 生视频模型(`dreamina-seedance-2.5`、`dreamina-seedance-2.5-flash`)需订阅 **Large**、**Max** 或 **企业版共享包(Shared Package)**。 + +### 快速配置(`make setup`) + +执行 `make setup` 并选择 **BytePlus Agent Plan**,向导会配置主模型,并明确询问是否将 `BYTEPLUS_AGENTPLAN_API_KEY` 共享到 `sandbox.environment`(默认否);勾选共享后即可复用同一把 Key 打通生图(`image-generation`)、PPT 视觉生成(`ppt-generation`)与视频生成(`video-generation`)。 + +### 手动配置 `config.yaml` + +```yaml +models: + - name: dola-seed-2.1-turbo-ap + display_name: Dola-Seed-2.1-Turbo (BytePlus Agent Plan) + use: deerflow.models.patched_deepseek:PatchedChatDeepSeek + model: dola-seed-2.1-turbo + api_base: https://ark.ap-southeast.bytepluses.com/api/plan/v3 + api_key: $BYTEPLUS_AGENTPLAN_API_KEY + timeout: 600.0 + max_retries: 2 + supports_thinking: true + supports_vision: true + supports_reasoning_effort: true + when_thinking_enabled: + extra_body: + thinking: + type: enabled + when_thinking_disabled: + extra_body: + thinking: + type: disabled + +sandbox: + use: deerflow.community.aio_sandbox:AioSandboxProvider + environment: + BYTEPLUS_AGENTPLAN_API_KEY: $BYTEPLUS_AGENTPLAN_API_KEY + # 可选覆盖参数: + # BYTEPLUS_AGENTPLAN_IMAGE_MODEL: dola-seedream-5.0-pro + # BYTEPLUS_AGENTPLAN_VIDEO_MODEL: dreamina-seedance-2.5 + # BYTEPLUS_AGENTPLAN_VIDEO_RESOLUTION: 720p + # BYTEPLUS_AGENTPLAN_VIDEO_DURATION: "6" +``` + +若为企业团队部署批量多模态或短视频工作流,可参考[企业版文档](https://console.byteplus.com/ark/region:ap-southeast-1/docs/agent-plan-enterprise-plan-overview?utm_campaign=deer_flow&utm_content=deer_flow&utm_medium=devrel&utm_source=OWO&utm_term=deer_flow)选择团队席位或共享包方案,并搭配 **BytePlus veFaaS Cloud Sandbox** 使用。 + +## 火山方舟 Coding Plan(中国大陆) + +中国大陆开发者使用火山引擎 Coding Plan 时,可在 `make setup` 中选择 **Volcengine Coding Plan**,或参考 `config.example.yaml` 配置 `api_base: https://ark.cn-beijing.volces.com/api/coding/v3` 与 `$VOLCENGINE_API_KEY`。 diff --git a/scripts/setup_wizard.py b/scripts/setup_wizard.py index 1997b9fa32..157002279e 100644 --- a/scripts/setup_wizard.py +++ b/scripts/setup_wizard.py @@ -100,6 +100,7 @@ def main() -> int: web_fetch_tool_name=fetch_provider.tool_name if fetch_provider else "web_fetch", web_fetch_extra_config=fetch_provider.extra_config if fetch_provider else None, sandbox_use=execution.sandbox_use, + sandbox_env_vars=llm.sandbox_env_vars or None, include_bash_tool=execution.include_bash_tool, include_write_tools=execution.include_write_tools, channel_connection_providers=channels.enabled_providers, diff --git a/scripts/wizard/providers.py b/scripts/wizard/providers.py index 54d3c82edd..f20454e04f 100644 --- a/scripts/wizard/providers.py +++ b/scripts/wizard/providers.py @@ -32,6 +32,9 @@ class LLMProvider: # For generic OpenAI-compatible gateways the wizard cannot infer whether the # user-supplied model supports thinking/reasoning, so prompt for it explicitly. ask_thinking_support: bool = False + # Optional host environment variables forwarded into sandbox.environment so + # multimodal skills (e.g. Seedream image & Seedance video) work with one key. + sandbox_env_vars: tuple[str, ...] = () def extra_config_for(self, model_name: str) -> dict: """Return extra_config for a selected model, applying per-model overrides. @@ -119,6 +122,40 @@ def with_thinking_support(provider: LLMProvider, supports_thinking: bool) -> LLM LLM_PROVIDERS: list[LLMProvider] = [ + LLMProvider( + name="byteplus_agentplan", + display_name="BytePlus Agent Plan", + description="One key for LLM, Seedream images/slides & Seedance 2.5 video (Personal & Team)", + use="deerflow.models.patched_deepseek:PatchedChatDeepSeek", + models=[ + "dola-seed-2.1-turbo", + "deepseek-v4-pro", + "deepseek-v4.1-flash", + "deepseek-v4.1-flash-economy", + "seed-2.0-lite", + "seed-2.0-mini", + ], + default_model="dola-seed-2.1-turbo", + env_var="BYTEPLUS_AGENTPLAN_API_KEY", + package="langchain-deepseek", + extra_config={ + "api_base": "https://ark.ap-southeast.bytepluses.com/api/plan/v3", + "timeout": 600.0, + "max_retries": 2, + "supports_vision": True, + "supports_reasoning_effort": True, + **OPENAI_COMPAT_THINKING_CONFIG, + }, + model_vision_overrides={ + "dola-seed-2.1-turbo": True, + "deepseek-v4.1-flash": True, + "seed-2.0-lite": True, + "seed-2.0-mini": True, + "deepseek-v4-pro": False, + "deepseek-v4.1-flash-economy": False, + }, + sandbox_env_vars=("BYTEPLUS_AGENTPLAN_API_KEY",), + ), LLMProvider( name="volcengine", display_name="Volcengine Doubao", diff --git a/scripts/wizard/steps/llm.py b/scripts/wizard/steps/llm.py index 6e0d3a9e7b..c728477916 100644 --- a/scripts/wizard/steps/llm.py +++ b/scripts/wizard/steps/llm.py @@ -22,6 +22,7 @@ class LLMStepResult: model_name: str api_key: str | None base_url: str | None = None + sandbox_env_vars: tuple[str, ...] = () def run_llm_step(step_label: str = "Step 1/3") -> LLMStepResult: @@ -81,9 +82,22 @@ def run_llm_step(step_label: str = "Step 1/3") -> LLMStepResult: if api_key: print_success(f"Key will be saved to .env as {provider.env_var}") + sandbox_env_vars: tuple[str, ...] = () + if provider.sandbox_env_vars: + var_list = ", ".join(provider.sandbox_env_vars) + print() + print_info( + f"Sharing {var_list} with sandbox.environment enables image, PPT, and video skills, " + "but exposes this key to every command-enabled sandbox run." + ) + if ask_yes_no(f"Share {var_list} with sandboxes?", default=False): + sandbox_env_vars = provider.sandbox_env_vars + print_success(f"{var_list} will be forwarded to sandbox.environment") + return LLMStepResult( provider=provider, model_name=model_name, api_key=api_key, base_url=base_url, + sandbox_env_vars=sandbox_env_vars, ) diff --git a/scripts/wizard/writer.py b/scripts/wizard/writer.py index cf289967ec..9eb8b077c3 100644 --- a/scripts/wizard/writer.py +++ b/scripts/wizard/writer.py @@ -189,6 +189,7 @@ def build_minimal_config( web_fetch_tool_name: str = "web_fetch", web_fetch_extra_config: dict | None = None, sandbox_use: str = "deerflow.sandbox.local:LocalSandboxProvider", + sandbox_env_vars: list[str] | tuple[str, ...] | None = None, include_bash_tool: bool = False, include_write_tools: bool = True, channel_connection_providers: list[str] | None = None, @@ -237,6 +238,12 @@ def build_minimal_config( sandbox_config = deepcopy(data.get("sandbox") if isinstance(data.get("sandbox"), dict) else {}) sandbox_config["use"] = sandbox_use sandbox_config.pop("allow_host_bash", None) + if sandbox_env_vars: + existing_env = sandbox_config.get("environment") + sandbox_env = dict(existing_env) if isinstance(existing_env, dict) else {} + for var_name in sandbox_env_vars: + sandbox_env[var_name] = f"${var_name}" + sandbox_config["environment"] = sandbox_env data["sandbox"] = sandbox_config if channel_connection_providers is not None: data["channel_connections"] = _build_channel_connections_config(channel_connection_providers) @@ -268,6 +275,7 @@ def write_config_yaml( web_fetch_tool_name: str = "web_fetch", web_fetch_extra_config: dict | None = None, sandbox_use: str = "deerflow.sandbox.local:LocalSandboxProvider", + sandbox_env_vars: list[str] | tuple[str, ...] | None = None, include_bash_tool: bool = False, include_write_tools: bool = True, channel_connection_providers: list[str] | None = None, @@ -302,6 +310,7 @@ def write_config_yaml( web_fetch_tool_name=web_fetch_tool_name, web_fetch_extra_config=web_fetch_extra_config, sandbox_use=sandbox_use, + sandbox_env_vars=sandbox_env_vars, include_bash_tool=include_bash_tool, include_write_tools=include_write_tools, channel_connection_providers=channel_connection_providers, diff --git a/skills/public/image-generation/SKILL.md b/skills/public/image-generation/SKILL.md index ceabf5eae5..b5608b6eed 100644 --- a/skills/public/image-generation/SKILL.md +++ b/skills/public/image-generation/SKILL.md @@ -193,17 +193,26 @@ For scenarios where visual accuracy is critical, **use the `image_search` tool f This approach significantly improves generation quality by providing the model with concrete visual guidance rather than relying solely on text descriptions. -## Providers (Gemini / MiniMax / OpenAI-compatible) +## Providers (Gemini / MiniMax / OpenAI-compatible / BytePlus Agent Plan) This skill auto-selects the provider by environment variables (no CLI change): - `GEMINI_API_KEY` set → use Gemini (default, unchanged). - Otherwise, `MINIMAX_API_KEY` set → use MiniMax (`/v1/image_generation`, model `image-01`). - Otherwise, `IMAGE_GENERATION_API_KEY` set → use an OpenAI-compatible Images API. -- Force one explicitly with `IMAGE_GENERATION_PROVIDER=gemini|minimax|openai`. - `openai-compatible` is also accepted as an alias for `openai`. +- Otherwise, `BYTEPLUS_AGENTPLAN_API_KEY` set → use BytePlus Agent Plan Seedream (`/api/plan/v3/images/generations`, default model `dola-seedream-5.0-pro`; also powers `ppt-generation` slide decks with the same key). +- Force one explicitly with `IMAGE_GENERATION_PROVIDER=gemini|minimax|openai|byteplus_agentplan`. + `openai-compatible` is accepted as an alias for `openai`; `byteplus`, `byteplus-agentplan`, and `seedream` are accepted as aliases for `byteplus_agentplan`. If the selected provider's key is missing, the CLI names it on stderr and exits with status 1. +BytePlus Agent Plan settings: + +- `BYTEPLUS_AGENTPLAN_API_KEY` (required; available on all Personal and Enterprise Agent Plan tiers) +- `BYTEPLUS_AGENTPLAN_BASE_URL` (default `https://ark.ap-southeast.bytepluses.com/api/plan/v3`) +- `BYTEPLUS_AGENTPLAN_IMAGE_MODEL` (default `dola-seedream-5.0-pro`; also supports `dola-seedream-5.5` and `dola-seedream-5.0-flash`) +- `BYTEPLUS_AGENTPLAN_IMAGE_SIZE` (optional fixed-size override such as `2K` or `2048x2048`; by default maps `--aspect-ratio` across `1:1`, `16:9`, `9:16`, `4:3`, `3:4`, `3:2`, `2:3`, and `21:9` to Seedream 2K dimensions and rejects unmapped ratios explicitly) +- The full structured JSON prompt is forwarded intact (preserving `style`, `composition`, `negative_prompt`, and slide instructions), and `output_format` matches the destination suffix (`.jpg`/`.jpeg` requests `jpeg`; other extensions request `png`). Every response is decoded and validated (container + pixel load) in memory — converting mismatched codecs when needed — before opening the destination file, preserving any existing output on invalid, truncated, or failed responses. Reference images passed via `--reference-images` are sent as data URLs in the JSON `image` field of `POST {base_url}/images/generations` (single string for one image, list for multiple images). + OpenAI-compatible settings: - `IMAGE_GENERATION_API_KEY` (required) diff --git a/skills/public/image-generation/scripts/generate.py b/skills/public/image-generation/scripts/generate.py index 8d841bea1e..3684394620 100644 --- a/skills/public/image-generation/scripts/generate.py +++ b/skills/public/image-generation/scripts/generate.py @@ -13,6 +13,18 @@ import requests MINIMAX_DEFAULT_HOST = "https://api.minimaxi.com" OPENAI_DEFAULT_BASE_URL = "https://api.openai.com/v1" OPENAI_DEFAULT_MODEL = "gpt-image-2.5-flare" +BYTEPLUS_AGENTPLAN_DEFAULT_BASE_URL = "https://ark.ap-southeast.bytepluses.com/api/plan/v3" +BYTEPLUS_AGENTPLAN_DEFAULT_IMAGE_MODEL = "dola-seedream-5.0-pro" +BYTEPLUS_AGENTPLAN_ASPECT_SIZES = { + "1:1": "2048x2048", + "16:9": "2560x1440", + "9:16": "1440x2560", + "4:3": "2304x1728", + "3:4": "1728x2304", + "3:2": "2496x1664", + "2:3": "1664x2496", + "21:9": "3136x1344", +} MAX_REDIRECTS = 5 # MiniMax image-01 caps the prompt at 1500 characters and rejects longer requests # with a generic "invalid params" error, so validate before calling the API. @@ -41,7 +53,7 @@ def _resolve_provider( 1. Explicit _PROVIDER override wins. 2. Otherwise prefer the existing provider when its credentials are present. - 3. Otherwise fall back to MiniMax, then the OpenAI-compatible provider. + 3. Otherwise fall back to MiniMax, OpenAI-compatible, then BytePlus Agent Plan. """ override = os.getenv(override_env) if override: @@ -52,9 +64,12 @@ def _resolve_provider( return "minimax" if os.getenv("IMAGE_GENERATION_API_KEY"): return "openai" + if os.getenv("BYTEPLUS_AGENTPLAN_API_KEY"): + return "byteplus_agentplan" raise ValueError( f"No credentials found. Set GEMINI_API_KEY for {existing_provider}, " - "MINIMAX_API_KEY for minimax, or IMAGE_GENERATION_API_KEY for openai " + "MINIMAX_API_KEY for minimax, IMAGE_GENERATION_API_KEY for openai, " + "or BYTEPLUS_AGENTPLAN_API_KEY for byteplus_agentplan " f"(optionally force with {override_env})." ) @@ -67,6 +82,36 @@ def _openai_base_url() -> str: return os.getenv("IMAGE_GENERATION_BASE_URL", OPENAI_DEFAULT_BASE_URL).rstrip("/") +def _byteplus_agentplan_base_url() -> str: + return ( + os.getenv("BYTEPLUS_AGENTPLAN_BASE_URL", BYTEPLUS_AGENTPLAN_DEFAULT_BASE_URL) + .strip() + .rstrip("/") + ) + + +def _byteplus_agentplan_size(aspect_ratio: str) -> str: + override = os.getenv("BYTEPLUS_AGENTPLAN_IMAGE_SIZE", "").strip() + if override: + return override + normalized = aspect_ratio.strip() + size = BYTEPLUS_AGENTPLAN_ASPECT_SIZES.get(normalized) + if size is None: + supported = ", ".join(BYTEPLUS_AGENTPLAN_ASPECT_SIZES) + raise ValueError( + f"Unsupported aspect ratio {aspect_ratio!r} for BytePlus Agent Plan Seedream " + f"(supported: {supported}; or set BYTEPLUS_AGENTPLAN_IMAGE_SIZE)" + ) + return size + + +def _byteplus_agentplan_output_format(output_file: str) -> str: + extension = os.path.splitext(output_file)[1].lower() + if extension in {".jpg", ".jpeg"}: + return "jpeg" + return "png" + + def _openai_size(aspect_ratio: str, model: str) -> str: override = os.getenv("IMAGE_GENERATION_SIZE") if override: @@ -124,10 +169,84 @@ def _guess_mime(image_path: str) -> str: }.get(ext, "image/jpeg") +def _detect_image_format(image_bytes: bytes) -> str | None: + if image_bytes.startswith(b"\x89PNG\r\n\x1a\n"): + return "PNG" + if image_bytes.startswith(b"\xff\xd8\xff"): + return "JPEG" + if ( + len(image_bytes) >= 12 + and image_bytes[:4] == b"RIFF" + and image_bytes[8:12] == b"WEBP" + ): + return "WEBP" + if image_bytes.startswith((b"GIF87a", b"GIF89a")): + return "GIF" + return None + + +def _validate_and_prepare_image(image_bytes: bytes, output_file: str) -> bytes: + """Validate decoded image bytes and convert format to match ``output_file``. + + Runs both container verification (``verify``) and full pixel decoding + (``load``) before ``output_file`` is opened so non-image payloads and + truncated/corrupted responses never overwrite an existing file. + """ + from io import BytesIO + from PIL import Image, ImageFile # lazy import: keeps module importable without Pillow + + previous_truncated = ImageFile.LOAD_TRUNCATED_IMAGES + ImageFile.LOAD_TRUNCATED_IMAGES = False + try: + with Image.open(BytesIO(image_bytes)) as img: + actual = (img.format or "").upper() + img.verify() + with Image.open(BytesIO(image_bytes)) as img: + img.load() + target_formats = { + ".jpg": "JPEG", + ".jpeg": "JPEG", + ".png": "PNG", + ".webp": "WEBP", + } + target = target_formats.get(os.path.splitext(output_file)[1].lower()) + if not target or actual == target: + return image_bytes + if target == "JPEG": + if img.mode in {"RGBA", "LA"} or ( + img.mode == "P" and "transparency" in img.info + ): + rgba = img.convert("RGBA") + background = Image.new("RGB", rgba.size, (255, 255, 255)) + background.paste(rgba, mask=rgba.getchannel("A")) + converted = background + else: + converted = img.convert("RGB") + else: + converted = img + buffer = BytesIO() + converted.save(buffer, format=target) + return buffer.getvalue() + except Exception as exc: + raise ValueError( + f"Provider returned invalid or corrupted image data: {exc}" + ) from exc + finally: + ImageFile.LOAD_TRUNCATED_IMAGES = previous_truncated + + def _to_data_url(image_path: str) -> str: with open(image_path, "rb") as f: - b64 = base64.b64encode(f.read()).decode("utf-8") - return f"data:{_guess_mime(image_path)};base64,{b64}" + data = f.read() + fmt = _detect_image_format(data) + mime = { + "PNG": "image/png", + "JPEG": "image/jpeg", + "WEBP": "image/webp", + "GIF": "image/gif", + }.get(fmt or "", _guess_mime(image_path)) + b64 = base64.b64encode(data).decode("utf-8") + return f"data:{mime};base64,{b64}" def _ensure_output_dir(output_file: str) -> None: @@ -353,7 +472,9 @@ def _generate_image_gemini( raise Exception("Failed to generate image") -def _write_openai_image(payload: dict, output_file: str) -> str: +def _write_openai_image( + payload: dict, output_file: str, *, convert_to_extension: bool = False +) -> str: images = payload.get("data") or [] if not images or not isinstance(images[0], dict): raise Exception("OpenAI-compatible provider returned no image data") @@ -379,6 +500,9 @@ def _write_openai_image(payload: dict, output_file: str) -> str: if not image_bytes: raise ValueError("Provider returned an empty image") + if convert_to_extension: + image_bytes = _validate_and_prepare_image(image_bytes, output_file) + _ensure_output_dir(output_file) with open(output_file, "wb") as f: f.write(image_bytes) @@ -440,6 +564,42 @@ def _generate_image_openai( return _write_openai_image(response.json(), output_file) +def _generate_image_byteplus_agentplan( + prompt: str, reference_images: list[str], output_file: str, aspect_ratio: str +) -> str: + bearer_value = os.getenv("BYTEPLUS_AGENTPLAN_API_KEY", "").strip() + if not bearer_value: + raise ValueError("BYTEPLUS_AGENTPLAN_API_KEY is not set") + + url = f"{_byteplus_agentplan_base_url()}/images/generations" + model = ( + os.getenv("BYTEPLUS_AGENTPLAN_IMAGE_MODEL", "").strip() + or BYTEPLUS_AGENTPLAN_DEFAULT_IMAGE_MODEL + ) + body: dict[str, object] = { + "model": model, + "prompt": prompt, + "size": _byteplus_agentplan_size(aspect_ratio), + "response_format": "b64_json", + "output_format": _byteplus_agentplan_output_format(output_file), + "watermark": False, + } + if reference_images: + encoded_refs = [_to_data_url(path) for path in reference_images] + body["image"] = encoded_refs[0] if len(encoded_refs) == 1 else encoded_refs + + response = _post_image( + url, + headers={ + "Authorization": f"Bearer {bearer_value}", + "Content-Type": "application/json", + }, + json=body, + timeout=180, + ) + return _write_openai_image(response.json(), output_file, convert_to_extension=True) + + def generate_image( prompt_file: str, reference_images: list[str], @@ -451,6 +611,10 @@ def generate_image( provider = _resolve_provider( "IMAGE_GENERATION_PROVIDER", "gemini", bool(os.getenv("GEMINI_API_KEY")) ) + if provider in ("byteplus", "byteplus_agentplan", "byteplus-agentplan", "seedream"): + return _generate_image_byteplus_agentplan( + prompt, reference_images, output_file, aspect_ratio + ) if provider in ("openai", "openai-compatible"): return _generate_image_openai( prompt, reference_images, output_file, aspect_ratio @@ -465,7 +629,7 @@ def generate_image( ) raise ValueError( f"Unknown image provider: {provider!r} " - "(use 'gemini', 'minimax', 'openai', or 'openai-compatible')" + "(use 'gemini', 'minimax', 'openai', 'openai-compatible', or 'byteplus_agentplan')" ) @@ -473,7 +637,7 @@ if __name__ == "__main__": import argparse parser = argparse.ArgumentParser( - description="Generate images using Gemini, MiniMax, or an OpenAI-compatible API" + description="Generate images using Gemini, MiniMax, OpenAI-compatible, or BytePlus Agent Plan (Seedream) API" ) parser.add_argument( "--prompt-file", required=True, help="Absolute path to JSON prompt file" diff --git a/skills/public/video-generation/AGENTS.md b/skills/public/video-generation/AGENTS.md index 39979deda0..9553b79be3 100644 --- a/skills/public/video-generation/AGENTS.md +++ b/skills/public/video-generation/AGENTS.md @@ -1,11 +1,12 @@ # Video generation skill (`skills/public/video-generation/`) -- **One extension-based MIME lookup serves Gemini references and MiniMax - first-frame data URLs.** An unmapped suffix raises an error that names the file - and the supported extensions. Images are not decoded or transcoded. +- **One extension-based MIME lookup serves Gemini references, MiniMax + first-frame data URLs, and BytePlus Agent Plan reference images.** An unmapped + suffix raises an error that names the file and the supported extensions. + Images are not decoded or transcoded. - **MIME recognition is separate from the formats a provider accepts.** -- **Blank MiniMax resolution and duration overrides are omitted from the - request.** An invalid duration string is reported before submission. The - provider checks the model-specific combinations. +- **Blank MiniMax and BytePlus Agent Plan resolution and duration overrides are + omitted from the request.** An invalid duration string is reported before + submission. The provider checks the model-specific combinations. - **Tests mock HTTP and check request metadata and the exact input bytes** for - both providers. Offline fixtures clear both override variables. + all providers. Offline fixtures clear all override variables. diff --git a/skills/public/video-generation/SKILL.md b/skills/public/video-generation/SKILL.md index 5ffd8bcdff..648f607f55 100644 --- a/skills/public/video-generation/SKILL.md +++ b/skills/public/video-generation/SKILL.md @@ -53,7 +53,7 @@ Parameters: - `--prompt-file`: Absolute path to JSON prompt file (required) - `--reference-images`: Absolute paths to reference images (optional). Images used by the provider must have a recognized filename extension: `.png`, `.jpg`, `.jpeg`, `.webp`, or `.gif` (case-insensitive). Missing or other extensions are rejected before submission. Filenames must match their contents: the script neither validates image contents nor converts bytes. Recognizing an extension does not guarantee that the selected provider accepts that format. - `--output-file`: Absolute path to output image file (required) -- `--aspect-ratio` sets the video aspect ratio for Gemini (optional, defaults to 16:9). +- `--aspect-ratio`: Aspect ratio of the generated video for Gemini and BytePlus Agent Plan (optional, defaults to `16:9`; BytePlus Agent Plan supports `16:9`, `9:16`, `1:1`, `4:3`, `3:4`, `21:9`, `adaptive`). [!NOTE] Do NOT read the python file, instead just call it with the parameters. @@ -134,6 +134,17 @@ VIDEO_GENERATION_PROVIDER=minimax MINIMAX_VIDEO_RESOLUTION=1080P MINIMAX_VIDEO_D --output-file /mnt/user-data/outputs/narnia-farewell-scene-01.mp4 ``` +With BytePlus Agent Plan (Seedance 2.5), one API key powers LLM planning, Seedream reference images, and video generation with native synchronized audio: + +```bash +VIDEO_GENERATION_PROVIDER=byteplus_agentplan BYTEPLUS_AGENTPLAN_VIDEO_RESOLUTION=720p BYTEPLUS_AGENTPLAN_VIDEO_DURATION=6 \ + python /mnt/skills/public/video-generation/scripts/generate.py \ + --prompt-file /mnt/user-data/workspace/narnia-farewell-scene.json \ + --reference-images /mnt/user-data/outputs/narnia-farewell-scene-01.jpg \ + --output-file /mnt/user-data/outputs/narnia-farewell-scene-01.mp4 \ + --aspect-ratio 16:9 +``` + > Do NOT read the python file, just call it with the parameters. ## Output Handling @@ -156,7 +167,7 @@ After generation: - Reference image enhance generation quality significantly - Iterative refinement is normal for optimal results -## Providers (Gemini / MiniMax) +## Providers (Gemini / MiniMax / BytePlus Agent Plan) Provider credentials are read from the runtime environment, not embedded in the script. Do not put their values in prompt files or command-line arguments. @@ -164,8 +175,21 @@ script. Do not put their values in prompt files or command-line arguments. Auto-selected by environment variables (CLI unchanged): - `GEMINI_API_KEY` set → Gemini Veo (default, unchanged). -- Only `MINIMAX_API_KEY` set → MiniMax video (`/v1/video_generation`, async 3-step poll/download). -- Force with `VIDEO_GENERATION_PROVIDER=gemini|minimax`. +- Otherwise, `MINIMAX_API_KEY` set → MiniMax video (`/v1/video_generation`, async 3-step poll/download). +- Otherwise, `BYTEPLUS_AGENTPLAN_API_KEY` set → BytePlus Agent Plan Seedance 2.5 (`/api/plan/v3/contents/generations/tasks`, async poll/download). +- Force with `VIDEO_GENERATION_PROVIDER=gemini|minimax|byteplus_agentplan` (aliases `byteplus`, `byteplus-agentplan`, and `seedance` are also accepted). + +BytePlus Agent Plan settings: + +- `BYTEPLUS_AGENTPLAN_API_KEY` (required; subscribe or upgrade at https://console.byteplus.com/ark/region:ap-southeast-1/subscription/agent-plan?utm_campaign=deer_flow&utm_content=deer_flow&utm_medium=devrel&utm_source=OWO&utm_term=deer_flow — Seedance 2.5 video generation is included in **Large**, **Max**, and **Enterprise Shared Package** tiers). +- `BYTEPLUS_AGENTPLAN_BASE_URL` (default `https://ark.ap-southeast.bytepluses.com/api/plan/v3`). +- `BYTEPLUS_AGENTPLAN_VIDEO_MODEL` (default `dreamina-seedance-2.5`; set `dreamina-seedance-2.5-flash` for faster/lower-AFP drafts). +- `BYTEPLUS_AGENTPLAN_VIDEO_RESOLUTION` (optional, e.g. `480p`, `720p`, `1080p`). +- `BYTEPLUS_AGENTPLAN_VIDEO_DURATION` (optional integer seconds `4`–`30`, or `-1` for auto). +- `BYTEPLUS_AGENTPLAN_GENERATE_AUDIO` (optional boolean, default `true` for native synchronized audio). +- `BYTEPLUS_AGENTPLAN_VIDEO_DOWNLOAD_HOSTS` (optional comma-separated list of additional exact HTTPS download hostnames approved by the operator; BytePlus Ark TOS storage endpoints under `tos-ap-southeast-1.volces.com`, `tos-ap-southeast-1.bytepluses.com`, and `tos-cn-beijing.volces.com` are trusted by default). +- Reference images passed via `--reference-images` are all sent as `role: "reference_image"` data URLs to preserve subject/product consistency. +- For a fast draft-to-final workflow, render a `480p` preview with `dreamina-seedance-2.5-flash` first, verify framing and motion, then render the final `720p` or `1080p` clip with `dreamina-seedance-2.5`. MiniMax uses `MINIMAX_API_HOST` (default `https://api.minimaxi.com`) and `MINIMAX_VIDEO_MODEL` (default `MiniMax-Hailuo-2.3`). It uses the first reference diff --git a/skills/public/video-generation/scripts/generate.py b/skills/public/video-generation/scripts/generate.py index 0dea4dd4a2..f64a2373e5 100644 --- a/skills/public/video-generation/scripts/generate.py +++ b/skills/public/video-generation/scripts/generate.py @@ -3,12 +3,25 @@ import os import re import sys import time -from urllib.parse import urljoin, urlsplit +from urllib.parse import quote, urljoin, urlsplit import requests MINIMAX_DEFAULT_HOST = "https://api.minimaxi.com" GEMINI_API_HOST = "generativelanguage.googleapis.com" +BYTEPLUS_AGENTPLAN_DEFAULT_BASE_URL = "https://ark.ap-southeast.bytepluses.com/api/plan/v3" +BYTEPLUS_AGENTPLAN_DEFAULT_VIDEO_MODEL = "dreamina-seedance-2.5" +BYTEPLUS_AGENTPLAN_CONSOLE_URL = ( + "https://console.byteplus.com/ark/region:ap-southeast-1/subscription/agent-plan" + "?utm_campaign=deer_flow&utm_content=deer_flow&utm_medium=devrel&utm_source=OWO&utm_term=deer_flow" +) +BYTEPLUS_AGENTPLAN_SUPPORTED_RATIOS = frozenset({"9:16", "16:9", "1:1", "4:3", "3:4", "21:9", "adaptive"}) +BYTEPLUS_AGENTPLAN_TOS_ENDPOINTS = { + "tos-ap-southeast-1.volces.com", + "tos-ap-southeast-1.bytepluses.com", + "tos-cn-beijing.volces.com", +} +BYTEPLUS_AGENTPLAN_TERMINAL_FAILURE_STATUSES = frozenset({"failed", "cancelled", "canceled", "expired"}) MINIMAX_VIDEO_HOSTS = { "api.minimaxi.com", "api.minimax.io", @@ -23,7 +36,7 @@ MAX_MINIMAX_API_REDIRECTS = 5 def _resolve_provider(override_env: str, existing_provider: str, has_existing_creds: bool) -> str: - """Pick the provider: _PROVIDER override > existing creds > MiniMax fallback.""" + """Pick the provider: _PROVIDER override > existing creds > MiniMax > BytePlus Agent Plan.""" override = os.getenv(override_env) if override: return override.strip().lower() @@ -31,13 +44,25 @@ def _resolve_provider(override_env: str, existing_provider: str, has_existing_cr return existing_provider if os.getenv("MINIMAX_API_KEY"): return "minimax" - raise ValueError(f"No credentials found. Set GEMINI_API_KEY for {existing_provider}, or MINIMAX_API_KEY for minimax (optionally force with {override_env}).") + if os.getenv("BYTEPLUS_AGENTPLAN_API_KEY"): + return "byteplus_agentplan" + raise ValueError( + f"No credentials found. Set GEMINI_API_KEY for {existing_provider}, " + "MINIMAX_API_KEY for minimax, or BYTEPLUS_AGENTPLAN_API_KEY for byteplus_agentplan " + f"(Seedance 2.5 via {BYTEPLUS_AGENTPLAN_CONSOLE_URL}; optionally force with {override_env})." + ) def _minimax_host() -> str: return os.getenv("MINIMAX_API_HOST", MINIMAX_DEFAULT_HOST).rstrip("/") +def _byteplus_agentplan_base_url() -> str: + base_url = os.getenv("BYTEPLUS_AGENTPLAN_BASE_URL", BYTEPLUS_AGENTPLAN_DEFAULT_BASE_URL).strip().rstrip("/") + _api_origin(base_url, provider_name="BytePlus Agent Plan") + return base_url + + def _ensure_output_dir(output_file: str) -> None: """Create the output file's parent directory so nested paths don't fail.""" output_dir = os.path.dirname(output_file) @@ -57,45 +82,49 @@ def _require_success(response: requests.Response) -> None: raise ValueError(f"Unexpected HTTP status {response.status_code} from video provider") -def _api_origin(url: str) -> tuple[str, str, int]: +def _api_origin(url: str, *, provider_name: str = "MiniMax") -> tuple[str, str, int]: parsed = urlsplit(url) host = parsed.hostname if parsed.scheme not in {"http", "https"} or not host: - raise ValueError("Invalid MiniMax API redirect origin") + raise ValueError(f"Invalid {provider_name} API redirect origin") port = parsed.port # Check the entire authority, including brackets for an IPv6 literal. # hostname/port alone would discard user information or stray delimiters. host_field = parsed.netloc if port is None else parsed.netloc.rsplit(":", 1)[0] expected = f"[{host}]" if ":" in host else host if host_field.lower() != expected.lower(): - raise ValueError("Invalid MiniMax API redirect authority") + raise ValueError(f"Invalid {provider_name} API redirect authority") default_port = 443 if parsed.scheme == "https" else 80 return parsed.scheme, host, default_port if port is None else port -def _minimax_api_request(send, url: str, *, timeout: int, **kwargs) -> requests.Response: +def _api_request(send, url: str, *, provider_name: str, timeout: int, check_response=_require_success, **kwargs) -> requests.Response: response = send(url, timeout=timeout, allow_redirects=False, **kwargs) if response.status_code in (307, 308): - origin = _api_origin(response.request.url) + origin = _api_origin(response.request.url, provider_name=provider_name) with requests.Session() as session: for _ in range(MAX_MINIMAX_API_REDIRECTS): # Requests prepares the redirect with the original method and body, # and resolves Location against the full URL (including GET params). target = response.next if target is None: - raise ValueError("MiniMax API redirect has no destination") - if _api_origin(target.url) != origin: - raise ValueError("MiniMax API redirect changes origin") + raise ValueError(f"{provider_name} API redirect has no destination") + if _api_origin(target.url, provider_name=provider_name) != origin: + raise ValueError(f"{provider_name} API redirect changes origin") settings = session.merge_environment_settings(target.url, {}, None, None, None) response = session.send(target, timeout=timeout, allow_redirects=False, **settings) if response.status_code not in (307, 308): break else: - raise ValueError("Too many MiniMax API redirects") - _require_success(response) + raise ValueError(f"Too many {provider_name} API redirects") + check_response(response) return response +def _minimax_api_request(send, url: str, *, timeout: int, **kwargs) -> requests.Response: + return _api_request(send, url, provider_name="MiniMax", timeout=timeout, **kwargs) + + def _guess_mime(image_path: str) -> str: ext = os.path.splitext(image_path)[1].lower() mime_types = { @@ -190,7 +219,7 @@ def _retrieve_file_url(host: str, auth: str, file_id: str) -> str: return payload["file"]["download_url"] -def _download_host(url: str, *, gemini: bool) -> str: +def _download_host(url: str, *, gemini: bool = False, provider: str | None = None) -> str: if not isinstance(url, str) or re.search(r"[\x00-\x20\x7f\\]", url): raise ValueError("Invalid video download URL") parsed = urlsplit(url) @@ -200,12 +229,17 @@ def _download_host(url: str, *, gemini: bool) -> str: if not re.fullmatch(r"(?:[a-z0-9-]+\.)+[a-z][a-z0-9-]*", host): raise ValueError("Invalid video download hostname") + resolved_provider = provider or ("gemini" if gemini else "minimax") # Only the storage provider controls DNS for bucket endpoints under these # exact suffixes. A bucket name is one DNS label. endpoint = host.partition(".")[2] - if gemini: + if resolved_provider == "gemini": trusted = host in {GEMINI_API_HOST, "storage.googleapis.com"} storage_endpoints = {"storage.googleapis.com"} + elif resolved_provider == "byteplus_agentplan": + extra_hosts = os.getenv("BYTEPLUS_AGENTPLAN_VIDEO_DOWNLOAD_HOSTS", "").split(",") + trusted = host in {name.strip().lower() for name in extra_hosts if name.strip()} + storage_endpoints = BYTEPLUS_AGENTPLAN_TOS_ENDPOINTS else: extra_hosts = os.getenv("MINIMAX_VIDEO_DOWNLOAD_HOSTS", "").split(",") trusted = host in MINIMAX_VIDEO_HOSTS or host in {name.strip().lower() for name in extra_hosts} @@ -215,10 +249,11 @@ def _download_host(url: str, *, gemini: bool) -> str: raise ValueError(f"Video download host {host!r} is outside the provider allowlist") -def _download(url: str, output_file: str, *, gemini_api_key: str = "") -> None: - headers = {"x-goog-api-key": gemini_api_key} if gemini_api_key else {} +def _download(url: str, output_file: str, *, gemini_api_key: str = "", provider: str | None = None) -> None: + resolved_provider = provider or ("gemini" if gemini_api_key else "minimax") + headers = {"x-goog-api-key": gemini_api_key} if resolved_provider == "gemini" and gemini_api_key else {} for _ in range(MAX_DOWNLOAD_REDIRECTS + 1): - host = _download_host(url, gemini=bool(gemini_api_key)) + host = _download_host(url, provider=resolved_provider) if host != GEMINI_API_HOST: headers = {} response = requests.get(url, headers=headers, timeout=300, allow_redirects=False) @@ -239,6 +274,137 @@ def _download(url: str, output_file: str, *, gemini_api_key: str = "") -> None: raise ValueError("Too many video download redirects") +def _check_byteplus_agentplan_response(response: requests.Response) -> None: + if response.status_code == 403: + detail = "" + try: + err = (response.json() or {}).get("error") or {} + detail = err.get("message") or "" + except Exception: + detail = "" + suffix = f" ({detail})" if detail else "" + raise RuntimeError( + f"BytePlus Agent Plan rejected the video generation request with HTTP 403{suffix}. " + "Seedance 2.5 video generation requires BytePlus Agent Plan Large, Max, or Enterprise Shared Package " + f"(Small and Medium tiers do not include video generation). Upgrade at {BYTEPLUS_AGENTPLAN_CONSOLE_URL}" + ) + _require_success(response) + + +def _parse_bool_env(name: str, default: bool) -> bool: + raw = os.getenv(name, "").strip().lower() + if not raw: + return default + if raw in {"1", "true", "yes", "on"}: + return True + if raw in {"0", "false", "no", "off"}: + return False + raise ValueError(f"{name} must be a boolean ('true' or 'false'), got {raw!r}") + + +def _extract_byteplus_video_url(payload: dict) -> str | None: + content = payload.get("content") + if isinstance(content, dict) and isinstance(content.get("video_url"), str): + return content["video_url"] + if isinstance(content, list): + for item in content: + if isinstance(item, dict) and isinstance(item.get("video_url"), str): + return item["video_url"] + if isinstance(payload.get("video_url"), str): + return payload["video_url"] + output = payload.get("output") + if isinstance(output, dict) and isinstance(output.get("video_url"), str): + return output["video_url"] + return None + + +def _poll_byteplus_agentplan_task(base_url: str, auth: str, task_id: str, max_attempts: int = 240, interval: int = 3) -> str: + poll_url = f"{base_url}/contents/generations/tasks/{quote(task_id, safe='')}" + for _ in range(max_attempts): + response = _api_request( + requests.get, + poll_url, + provider_name="BytePlus Agent Plan", + headers={"Authorization": auth}, + timeout=30, + check_response=_check_byteplus_agentplan_response, + ) + payload = response.json() + status = str(payload.get("status", "")).strip().lower() + if status == "succeeded": + video_url = _extract_byteplus_video_url(payload) + if not video_url: + raise Exception(f"BytePlus Agent Plan video task {task_id} succeeded without a video_url") + return video_url + if status in BYTEPLUS_AGENTPLAN_TERMINAL_FAILURE_STATUSES: + err = payload.get("error") or {} + detail = err.get("message") if isinstance(err, dict) else str(err) + raise Exception(f"BytePlus Agent Plan video task {task_id} failed ({status}): {detail or 'unknown error'}") + time.sleep(interval) + raise Exception(f"BytePlus Agent Plan video task {task_id} timed out after {max_attempts} polls") + + +def _generate_video_byteplus_agentplan(prompt: str, reference_images: list[str], output_file: str, aspect_ratio: str = "16:9") -> str: + api_key = os.getenv("BYTEPLUS_AGENTPLAN_API_KEY", "").strip() + if not api_key: + raise ValueError("BYTEPLUS_AGENTPLAN_API_KEY is not set") + base_url = _byteplus_agentplan_base_url() + auth = f"Bearer {api_key}" + model = os.getenv("BYTEPLUS_AGENTPLAN_VIDEO_MODEL", "").strip() or BYTEPLUS_AGENTPLAN_DEFAULT_VIDEO_MODEL + + ratio = (aspect_ratio or "16:9").strip() + if ratio not in BYTEPLUS_AGENTPLAN_SUPPORTED_RATIOS: + supported = ", ".join(sorted(BYTEPLUS_AGENTPLAN_SUPPORTED_RATIOS)) + raise ValueError(f"Unsupported aspect ratio {ratio!r} for BytePlus Agent Plan. Supported values: {supported}") + + content: list[dict] = [{"type": "text", "text": prompt}] + for reference_image in reference_images: + content.append( + { + "type": "image_url", + "image_url": {"url": _to_data_url(reference_image)}, + "role": "reference_image", + } + ) + + body: dict = { + "model": model, + "content": content, + "ratio": ratio, + "generate_audio": _parse_bool_env("BYTEPLUS_AGENTPLAN_GENERATE_AUDIO", True), + "watermark": False, + } + resolution = os.getenv("BYTEPLUS_AGENTPLAN_VIDEO_RESOLUTION", "").strip() + if resolution: + body["resolution"] = resolution + duration_raw = os.getenv("BYTEPLUS_AGENTPLAN_VIDEO_DURATION", "").strip() + if duration_raw: + error = f"BYTEPLUS_AGENTPLAN_VIDEO_DURATION must be an integer between 4 and 30 (or -1 for auto), got {duration_raw!r}" + if not re.fullmatch(r"-?[0-9]+", duration_raw): + raise ValueError(error) + duration = int(duration_raw) + if duration != -1 and not (4 <= duration <= 30): + raise ValueError(error) + body["duration"] = duration + + response = _api_request( + requests.post, + f"{base_url}/contents/generations/tasks", + provider_name="BytePlus Agent Plan", + headers={"Authorization": auth, "Content-Type": "application/json"}, + json=body, + timeout=60, + check_response=_check_byteplus_agentplan_response, + ) + payload = response.json() + task_id = payload.get("id") + if not isinstance(task_id, str) or not task_id: + raise Exception("BytePlus Agent Plan video submission response did not include a task id") + download_url = _poll_byteplus_agentplan_task(base_url, auth, task_id) + _download(download_url, output_file, provider="byteplus_agentplan") + return f"The video has been generated successfully to {output_file}" + + def _generate_video_minimax(prompt: str, reference_images: list[str], output_file: str) -> str: minimax_api_key = os.getenv("MINIMAX_API_KEY") if not minimax_api_key: @@ -326,22 +492,24 @@ def generate_video( with open(prompt_file, encoding="utf-8") as f: prompt = f.read() provider = _resolve_provider("VIDEO_GENERATION_PROVIDER", "gemini", bool(os.getenv("GEMINI_API_KEY"))) + if provider in ("byteplus", "byteplus_agentplan", "byteplus-agentplan", "seedance"): + return _generate_video_byteplus_agentplan(prompt, reference_images, output_file, aspect_ratio) if provider == "minimax": # MiniMax video uses resolution/duration, not aspect_ratio; aspect_ratio ignored. return _generate_video_minimax(prompt, reference_images, output_file) if provider in ("gemini", "google"): return _generate_video_gemini(prompt, reference_images, output_file, aspect_ratio) - raise ValueError(f"Unknown video provider: {provider!r} (use 'gemini' or 'minimax')") + raise ValueError(f"Unknown video provider: {provider!r} (use 'gemini', 'minimax', or 'byteplus_agentplan')") if __name__ == "__main__": import argparse - parser = argparse.ArgumentParser(description="Generate videos using Gemini or MiniMax API") + parser = argparse.ArgumentParser(description="Generate videos using Gemini, MiniMax, or BytePlus Agent Plan (Seedance 2.5) API") parser.add_argument("--prompt-file", required=True, help="Absolute path to JSON prompt file") parser.add_argument("--reference-images", nargs="*", default=[], help="Absolute paths to reference images (space-separated)") parser.add_argument("--output-file", required=True, help="Output path for generated video") - parser.add_argument("--aspect-ratio", required=False, default="16:9", help="Aspect ratio of the generated video (Gemini only)") + parser.add_argument("--aspect-ratio", required=False, default="16:9", help="Aspect ratio of the generated video (Gemini and BytePlus Agent Plan)") args = parser.parse_args() try: diff --git a/tests/skills/test_image_generation.py b/tests/skills/test_image_generation.py index 4e405147b6..30ea54bd6e 100644 --- a/tests/skills/test_image_generation.py +++ b/tests/skills/test_image_generation.py @@ -16,6 +16,7 @@ def clean_env(monkeypatch): for k in [ "GEMINI_API_KEY", "MINIMAX_API_KEY", + "BYTEPLUS_AGENTPLAN_API_KEY", "IMAGE_GENERATION_PROVIDER", "MINIMAX_API_HOST", "MINIMAX_IMAGE_MODEL", @@ -23,6 +24,9 @@ def clean_env(monkeypatch): "IMAGE_GENERATION_BASE_URL", "IMAGE_GENERATION_MODEL", "IMAGE_GENERATION_SIZE", + "BYTEPLUS_AGENTPLAN_BASE_URL", + "BYTEPLUS_AGENTPLAN_IMAGE_MODEL", + "BYTEPLUS_AGENTPLAN_IMAGE_SIZE", ]: monkeypatch.delenv(k, raising=False) @@ -862,3 +866,186 @@ def test_guess_mime_by_extension(): assert img._guess_mime("/a/b.webp") == "image/webp" assert img._guess_mime("/a/b.jpg") == "image/jpeg" assert img._guess_mime("/a/b.unknown") == "image/jpeg" + + +def test_resolve_falls_back_to_byteplus_agentplan(monkeypatch): + monkeypatch.setenv("BYTEPLUS_AGENTPLAN_API_KEY", "bp-key") + assert ( + img._resolve_provider("IMAGE_GENERATION_PROVIDER", "gemini", False) + == "byteplus_agentplan" + ) + + +def _make_test_image(fmt: str = "PNG", size: tuple[int, int] = (8, 6)) -> bytes: + from io import BytesIO + from PIL import Image + + buf = BytesIO() + mode = "RGBA" if fmt == "PNG" else "RGB" + color = (20, 120, 220, 255) if mode == "RGBA" else (20, 120, 220) + Image.new(mode, size, color).save(buf, format=fmt) + return buf.getvalue() + + +@pytest.mark.parametrize( + "alias", ["byteplus", "byteplus_agentplan", "byteplus-agentplan", "seedream"] +) +def test_byteplus_agentplan_generation_writes_base64(monkeypatch, tmp_path, alias): + monkeypatch.setenv("IMAGE_GENERATION_PROVIDER", alias) + monkeypatch.setenv("BYTEPLUS_AGENTPLAN_API_KEY", "bp-key") + jpeg_bytes = _make_test_image("JPEG") + captured = {} + + def fake_post(url, headers=None, json=None, **kwargs): + captured.update(url=url, headers=headers, json=json, kwargs=kwargs) + return FakeResp({"data": [{"b64_json": base64.b64encode(jpeg_bytes).decode()}]}) + + monkeypatch.setattr(img.requests, "post", fake_post) + structured_prompt = ( + '{"prompt": "glassmorphism slide", "style": "keynote", ' + '"composition": "wide hero", "negative_prompt": "cluttered"}' + ) + prompt_file = tmp_path / "prompt.json" + prompt_file.write_text(structured_prompt, encoding="utf-8") + output_file = tmp_path / "nested" / "slide.jpg" + + result = img.generate_image(str(prompt_file), [], str(output_file), "16:9") + + assert captured["url"] == "https://ark.ap-southeast.bytepluses.com/api/plan/v3/images/generations" + assert captured["headers"]["Authorization"] == "Bearer bp-key" + assert captured["json"] == { + "model": "dola-seedream-5.0-pro", + "prompt": structured_prompt, + "size": "2560x1440", + "response_format": "b64_json", + "output_format": "jpeg", + "watermark": False, + } + assert output_file.read_bytes() == jpeg_bytes + assert "Successfully generated image" in result + + +def test_byteplus_agentplan_aspect_ratio_21_9_and_unmapped_rejected(monkeypatch, tmp_path): + monkeypatch.setenv("BYTEPLUS_AGENTPLAN_API_KEY", "bp-key") + png_bytes = _make_test_image("PNG") + captured = [] + + def fake_post(url, headers=None, json=None, **kwargs): + captured.append(json) + return FakeResp({"data": [{"b64_json": base64.b64encode(png_bytes).decode()}]}) + + monkeypatch.setattr(img.requests, "post", fake_post) + prompt_file = tmp_path / "prompt.txt" + prompt_file.write_text("cinematic panorama", encoding="utf-8") + + img.generate_image(str(prompt_file), [], str(tmp_path / "wide.png"), "21:9") + assert captured[0]["size"] == "3136x1344" + assert captured[0]["output_format"] == "png" + + with pytest.raises(ValueError, match="Unsupported aspect ratio '5:4'"): + img.generate_image(str(prompt_file), [], str(tmp_path / "bad.png"), "5:4") + assert len(captured) == 1 + + +def test_byteplus_agentplan_converts_mismatched_png_for_jpg_slide_chain(monkeypatch, tmp_path): + monkeypatch.setenv("BYTEPLUS_AGENTPLAN_API_KEY", "bp-key") + png_bytes = _make_test_image("PNG") + assert png_bytes.startswith(b"\x89PNG\r\n\x1a\n") + + posts = [] + + def fake_post(url, headers=None, json=None, **kwargs): + posts.append(json) + return FakeResp({"data": [{"b64_json": base64.b64encode(png_bytes).decode()}]}) + + monkeypatch.setattr(img.requests, "post", fake_post) + prompt_file = tmp_path / "prompt.json" + prompt_file.write_text('{"prompt": "title slide", "style": "clean"}', encoding="utf-8") + + slide1 = tmp_path / "slide-01.jpg" + slide2 = tmp_path / "slide-02.jpg" + img.generate_image(str(prompt_file), [], str(slide1), "16:9") + img.generate_image(str(prompt_file), [str(slide1)], str(slide2), "16:9") + + assert posts[0]["output_format"] == "jpeg" + assert slide1.read_bytes().startswith(b"\xff\xd8\xff") + assert slide2.read_bytes().startswith(b"\xff\xd8\xff") + ref_data_url = posts[1]["image"] + assert isinstance(ref_data_url, str) + assert ref_data_url.startswith("data:image/jpeg;base64,") + assert base64.b64decode(ref_data_url.split(",", 1)[1]).startswith(b"\xff\xd8\xff") + + +@pytest.mark.parametrize( + "bad_bytes", + [ + b"not an image", + _make_test_image("JPEG", size=(64, 64))[:120], + ], + ids=["non-image-payload", "truncated-jpeg"], +) +def test_byteplus_agentplan_rejects_corrupt_or_truncated_image_and_preserves_slide( + monkeypatch, tmp_path, bad_bytes +): + monkeypatch.setenv("BYTEPLUS_AGENTPLAN_API_KEY", "bp-key") + monkeypatch.setattr( + img.requests, + "post", + lambda *args, **kwargs: FakeResp( + {"data": [{"b64_json": base64.b64encode(bad_bytes).decode()}]} + ), + ) + prompt_file = tmp_path / "prompt.txt" + prompt_file.write_text("slide update", encoding="utf-8") + existing_slide = _make_test_image("JPEG") + slide_path = tmp_path / "slide-01.jpg" + slide_path.write_bytes(existing_slide) + + with pytest.raises(ValueError, match="invalid or corrupted image data"): + img.generate_image(str(prompt_file), [], str(slide_path), "16:9") + + assert slide_path.read_bytes() == existing_slide + + +def test_byteplus_agentplan_single_and_multi_reference_images_and_overrides(monkeypatch, tmp_path): + monkeypatch.setenv("BYTEPLUS_AGENTPLAN_API_KEY", "bp-key") + monkeypatch.setenv("BYTEPLUS_AGENTPLAN_BASE_URL", "https://plan.example/api/plan/v3/") + monkeypatch.setenv("BYTEPLUS_AGENTPLAN_IMAGE_MODEL", "dola-seedream-5.5") + monkeypatch.setenv("BYTEPLUS_AGENTPLAN_IMAGE_SIZE", "2K") + png_bytes = _make_test_image("PNG") + posts = [] + + def fake_post(url, headers=None, json=None, **kwargs): + posts.append((url, json)) + return FakeResp({"data": [{"b64_json": base64.b64encode(png_bytes).decode()}]}) + + monkeypatch.setattr(img.requests, "post", fake_post) + prompt_file = tmp_path / "prompt.txt" + prompt_file.write_text("matching next slide", encoding="utf-8") + ref1 = tmp_path / "slide1.png" + ref1.write_bytes(b"\x89PNGone") + ref2 = tmp_path / "slide2.jpg" + ref2.write_bytes(b"\xff\xd8two") + + img.generate_image(str(prompt_file), [str(ref1)], str(tmp_path / "out1.png"), "16:9") + img.generate_image(str(prompt_file), [str(ref1), str(ref2)], str(tmp_path / "out2.png"), "9:16") + + assert posts[0][0] == "https://plan.example/api/plan/v3/images/generations" + assert posts[0][1]["model"] == "dola-seedream-5.5" + assert posts[0][1]["size"] == "2K" + assert posts[0][1]["output_format"] == "png" + assert isinstance(posts[0][1]["image"], str) + assert posts[0][1]["image"].startswith("data:image/png;base64,") + + assert isinstance(posts[1][1]["image"], list) + assert len(posts[1][1]["image"]) == 2 + assert posts[1][1]["image"][0].startswith("data:image/png;base64,") + assert posts[1][1]["image"][1].startswith("data:image/jpeg;base64,") + + +def test_byteplus_agentplan_missing_key_raises(monkeypatch, tmp_path): + monkeypatch.setenv("IMAGE_GENERATION_PROVIDER", "byteplus_agentplan") + prompt_file = tmp_path / "prompt.txt" + prompt_file.write_text("a deer", encoding="utf-8") + with pytest.raises(ValueError, match="BYTEPLUS_AGENTPLAN_API_KEY is not set"): + img.generate_image(str(prompt_file), [], str(tmp_path / "o.png"), "1:1") diff --git a/tests/skills/test_image_output_preservation.py b/tests/skills/test_image_output_preservation.py index 986eebde5f..a026326bd0 100644 --- a/tests/skills/test_image_output_preservation.py +++ b/tests/skills/test_image_output_preservation.py @@ -34,7 +34,12 @@ def _response(provider, encoded): def _generate(monkeypatch, tmp_path, provider, encoded, output): monkeypatch.setenv("IMAGE_GENERATION_PROVIDER", provider) - for key in ("MINIMAX_API_KEY", "GEMINI_API_KEY", "IMAGE_GENERATION_API_KEY"): + for key in ( + "MINIMAX_API_KEY", + "GEMINI_API_KEY", + "IMAGE_GENERATION_API_KEY", + "BYTEPLUS_AGENTPLAN_API_KEY", + ): monkeypatch.setenv(key, "offline-fixture") monkeypatch.setenv("IMAGE_GENERATION_MODEL", "gpt-image-1") monkeypatch.setattr( @@ -47,7 +52,7 @@ def _generate(monkeypatch, tmp_path, provider, encoded, output): return image.generate_image(str(prompt), [], str(output)) -@pytest.mark.parametrize("provider", ["gemini", "openai"]) +@pytest.mark.parametrize("provider", ["gemini", "openai", "byteplus_agentplan"]) @pytest.mark.parametrize( "existing", [False, True], ids=["new-output", "existing-output"] ) @@ -74,7 +79,7 @@ def test_decode_failure_preserves_output( assert not output.parent.exists() -@pytest.mark.parametrize("provider", ["gemini", "openai"]) +@pytest.mark.parametrize("provider", ["gemini", "openai", "byteplus_agentplan"]) @pytest.mark.parametrize( "existing", [False, True], ids=["new-output", "existing-output"] ) diff --git a/tests/skills/test_video_generation.py b/tests/skills/test_video_generation.py index f08eed04b8..20d7975eb0 100644 --- a/tests/skills/test_video_generation.py +++ b/tests/skills/test_video_generation.py @@ -11,6 +11,7 @@ from skill_loader import FakeResp, load # noqa: E402 vid = load("video-generation") GEMINI_VIDEO = "https://generativelanguage.googleapis.com/download/v1beta/files/video" MINIMAX_VIDEO = "https://filecdn.minimax.chat/v.mp4" +BYTEPLUS_VIDEO = "https://bucket.tos-ap-southeast-1.volces.com/generated/v.mp4" @pytest.fixture(autouse=True) @@ -18,12 +19,19 @@ def clean_env(monkeypatch): for key in ( "GEMINI_API_KEY", "MINIMAX_API_KEY", + "BYTEPLUS_AGENTPLAN_API_KEY", "VIDEO_GENERATION_PROVIDER", "MINIMAX_API_HOST", "MINIMAX_VIDEO_DOWNLOAD_HOSTS", "MINIMAX_VIDEO_MODEL", "MINIMAX_VIDEO_RESOLUTION", "MINIMAX_VIDEO_DURATION", + "BYTEPLUS_AGENTPLAN_BASE_URL", + "BYTEPLUS_AGENTPLAN_VIDEO_MODEL", + "BYTEPLUS_AGENTPLAN_VIDEO_RESOLUTION", + "BYTEPLUS_AGENTPLAN_VIDEO_DURATION", + "BYTEPLUS_AGENTPLAN_GENERATE_AUDIO", + "BYTEPLUS_AGENTPLAN_VIDEO_DOWNLOAD_HOSTS", ): monkeypatch.delenv(key, raising=False) monkeypatch.setattr(vid.time, "sleep", lambda *_: None) @@ -664,3 +672,196 @@ def test_gemini_forwards_aspect_ratio_to_predict_request(monkeypatch, tmp_path): assert "predictLongRunning" in captured["url"] assert captured["json"]["parameters"]["aspectRatio"] == "9:16" + + +def test_resolve_falls_back_to_byteplus_agentplan(monkeypatch): + monkeypatch.setenv("BYTEPLUS_AGENTPLAN_API_KEY", "bp-key") + assert vid._resolve_provider("VIDEO_GENERATION_PROVIDER", "gemini", False) == "byteplus_agentplan" + + +def test_resolve_prefers_minimax_before_byteplus_agentplan(monkeypatch): + monkeypatch.setenv("MINIMAX_API_KEY", "m") + monkeypatch.setenv("BYTEPLUS_AGENTPLAN_API_KEY", "bp-key") + assert vid._resolve_provider("VIDEO_GENERATION_PROVIDER", "gemini", False) == "minimax" + + +@pytest.mark.parametrize("alias", ["byteplus", "byteplus_agentplan", "byteplus-agentplan", "seedance"]) +def test_byteplus_agentplan_full_flow_and_aliases(monkeypatch, tmp_path, alias): + monkeypatch.setenv("VIDEO_GENERATION_PROVIDER", alias) + monkeypatch.setenv("BYTEPLUS_AGENTPLAN_API_KEY", "bp-key") + captured = {} + + def fake_post(url, headers=None, json=None, **kw): + captured["post_url"] = url + captured["post_headers"] = headers + captured["post_json"] = json + assert kw["allow_redirects"] is False + return FakeResp({"id": "cgt-123"}) + + def fake_get(url, headers=None, **kw): + assert kw["allow_redirects"] is False + if url.endswith("/contents/generations/tasks/cgt-123"): + assert headers["Authorization"] == "Bearer bp-key" + return FakeResp({"id": "cgt-123", "status": "succeeded", "content": {"video_url": BYTEPLUS_VIDEO}}) + assert url == BYTEPLUS_VIDEO + assert not headers + return FakeResp(content=b"SEEDANCE_MP4") + + monkeypatch.setattr(vid.requests, "post", fake_post) + monkeypatch.setattr(vid.requests, "get", fake_get) + + out = tmp_path / "seedance.mp4" + pf = tmp_path / "prompt.json" + pf.write_text("cinematic sunset over mountains", encoding="utf-8") + msg = vid.generate_video(str(pf), [], str(out), "9:16") + + assert out.read_bytes() == b"SEEDANCE_MP4" + assert captured["post_url"] == "https://ark.ap-southeast.bytepluses.com/api/plan/v3/contents/generations/tasks" + assert captured["post_headers"]["Authorization"] == "Bearer bp-key" + assert captured["post_json"] == { + "model": "dreamina-seedance-2.5", + "content": [{"type": "text", "text": "cinematic sunset over mountains"}], + "ratio": "9:16", + "generate_audio": True, + "watermark": False, + } + assert "successfully" in msg.lower() + + +def test_byteplus_agentplan_env_overrides_and_multiple_references(monkeypatch, tmp_path): + monkeypatch.setenv("BYTEPLUS_AGENTPLAN_API_KEY", "bp-key") + monkeypatch.setenv("BYTEPLUS_AGENTPLAN_BASE_URL", "https://plan.example/api/plan/v3/") + monkeypatch.setenv("BYTEPLUS_AGENTPLAN_VIDEO_MODEL", "dreamina-seedance-2.5-flash") + monkeypatch.setenv("BYTEPLUS_AGENTPLAN_VIDEO_RESOLUTION", "480p") + monkeypatch.setenv("BYTEPLUS_AGENTPLAN_VIDEO_DURATION", "15") + monkeypatch.setenv("BYTEPLUS_AGENTPLAN_GENERATE_AUDIO", "false") + captured = {} + + def fake_post(url, headers=None, json=None, **kw): + captured["url"] = url + captured["json"] = json + return FakeResp({"id": "cgt-456"}) + + def fake_get(url, headers=None, **kw): + if url.endswith("/contents/generations/tasks/cgt-456"): + return FakeResp({"status": "succeeded", "content": {"video_url": BYTEPLUS_VIDEO}}) + return FakeResp(content=b"FLASH_MP4") + + monkeypatch.setattr(vid.requests, "post", fake_post) + monkeypatch.setattr(vid.requests, "get", fake_get) + + ref1 = tmp_path / "a.jpg" + ref1.write_bytes(b"\xff\xd8first") + ref2 = tmp_path / "b.png" + ref2.write_bytes(b"\x89PNGsecond") + pf = tmp_path / "prompt.json" + pf.write_text("product showcase", encoding="utf-8") + out = tmp_path / "out.mp4" + + vid.generate_video(str(pf), [str(ref1), str(ref2)], str(out), "16:9") + + assert captured["url"] == "https://plan.example/api/plan/v3/contents/generations/tasks" + payload = captured["json"] + assert payload["model"] == "dreamina-seedance-2.5-flash" + assert payload["resolution"] == "480p" + assert payload["duration"] == 15 + assert payload["generate_audio"] is False + assert payload["ratio"] == "16:9" + assert len(payload["content"]) == 3 + assert payload["content"][1]["role"] == "reference_image" + assert payload["content"][1]["image_url"]["url"].startswith("data:image/jpeg;base64,") + assert payload["content"][2]["role"] == "reference_image" + assert payload["content"][2]["image_url"]["url"].startswith("data:image/png;base64,") + + +@pytest.mark.parametrize("duration", ["abc", "0", "3", "31", "-2", "6.5"]) +def test_byteplus_agentplan_rejects_invalid_duration_before_submission(monkeypatch, tmp_path, duration): + monkeypatch.setenv("BYTEPLUS_AGENTPLAN_API_KEY", "bp-key") + monkeypatch.setenv("BYTEPLUS_AGENTPLAN_VIDEO_DURATION", duration) + monkeypatch.setattr(vid.requests, "post", lambda *a, **kw: pytest.fail("must not submit invalid duration")) + pf = tmp_path / "prompt.json" + pf.write_text("a cat", encoding="utf-8") + with pytest.raises(ValueError, match="BYTEPLUS_AGENTPLAN_VIDEO_DURATION"): + vid.generate_video(str(pf), [], str(tmp_path / "v.mp4"), "16:9") + + +def test_byteplus_agentplan_rejects_unsupported_aspect_ratio_before_submission(monkeypatch, tmp_path): + monkeypatch.setenv("BYTEPLUS_AGENTPLAN_API_KEY", "bp-key") + monkeypatch.setattr(vid.requests, "post", lambda *a, **kw: pytest.fail("must not submit invalid ratio")) + pf = tmp_path / "prompt.json" + pf.write_text("a cat", encoding="utf-8") + with pytest.raises(ValueError, match="Unsupported aspect ratio"): + vid.generate_video(str(pf), [], str(tmp_path / "v.mp4"), "5:4") + + +def test_byteplus_agentplan_403_reports_plan_tier_upgrade_hint(monkeypatch, tmp_path): + monkeypatch.setenv("BYTEPLUS_AGENTPLAN_API_KEY", "bp-small-key") + monkeypatch.setattr( + vid.requests, + "post", + lambda *a, **kw: FakeResp({"error": {"message": "model not available in plan"}}, status_code=403), + ) + pf = tmp_path / "prompt.json" + pf.write_text("a cat", encoding="utf-8") + with pytest.raises(RuntimeError, match="Large, Max, or Enterprise Shared Package"): + vid.generate_video(str(pf), [], str(tmp_path / "v.mp4"), "16:9") + + +def test_byteplus_agentplan_task_failure_and_timeout(monkeypatch, tmp_path): + monkeypatch.setenv("BYTEPLUS_AGENTPLAN_API_KEY", "bp-key") + monkeypatch.setattr(vid.requests, "post", lambda *a, **kw: FakeResp({"id": "cgt-fail"})) + monkeypatch.setattr( + vid.requests, + "get", + lambda *a, **kw: FakeResp({"id": "cgt-fail", "status": "failed", "error": {"message": "safety filtered"}}), + ) + pf = tmp_path / "prompt.json" + pf.write_text("x", encoding="utf-8") + with pytest.raises(Exception, match="safety filtered"): + vid.generate_video(str(pf), [], str(tmp_path / "v.mp4"), "16:9") + + monkeypatch.setattr(vid.requests, "get", lambda *a, **kw: FakeResp({"id": "cgt-slow", "status": "running"})) + with pytest.raises(Exception, match="timed out"): + vid._poll_byteplus_agentplan_task("https://ark.ap-southeast.bytepluses.com/api/plan/v3", "Bearer bp-key", "cgt-slow", max_attempts=2, interval=0) + + +def test_byteplus_agentplan_download_allowlist_and_custom_hosts(monkeypatch, tmp_path): + monkeypatch.setenv("BYTEPLUS_AGENTPLAN_API_KEY", "bp-key") + untrusted = "https://evil.example/video.mp4" + monkeypatch.setattr(vid.requests, "post", lambda *a, **kw: FakeResp({"id": "cgt-1"})) + + def fake_get(url, **kw): + if url.endswith("/contents/generations/tasks/cgt-1"): + return FakeResp({"status": "succeeded", "content": {"video_url": untrusted}}) + raise AssertionError("untrusted download URL must not be fetched") + + monkeypatch.setattr(vid.requests, "get", fake_get) + pf = tmp_path / "prompt.json" + pf.write_text("x", encoding="utf-8") + out = tmp_path / "v.mp4" + out.write_bytes(b"existing") + with pytest.raises(ValueError, match="outside the provider allowlist"): + vid.generate_video(str(pf), [], str(out), "16:9") + assert out.read_bytes() == b"existing" + + # Explicit operator approval allows custom HTTPS host. + monkeypatch.setenv("BYTEPLUS_AGENTPLAN_VIDEO_DOWNLOAD_HOSTS", "cdn.partner.test") + custom_url = "https://cdn.partner.test/v.mp4" + monkeypatch.setattr( + vid.requests, + "get", + lambda url, **kw: FakeResp({"status": "succeeded", "content": {"video_url": custom_url}}) + if url.endswith("/contents/generations/tasks/cgt-1") + else FakeResp(content=b"approved-bytes"), + ) + vid.generate_video(str(pf), [], str(out), "16:9") + assert out.read_bytes() == b"approved-bytes" + + +def test_byteplus_agentplan_rejects_cross_origin_api_redirect(monkeypatch, tmp_path): + host = "https://ark.ap-southeast.bytepluses.com/api/plan/v3" + monkeypatch.setenv("BYTEPLUS_AGENTPLAN_API_KEY", "bp-key") + sent = mock_http_transport(monkeypatch, [(307, "https://other.example/tasks")]) + with pytest.raises(ValueError, match="changes origin"): + vid._generate_video_byteplus_agentplan("a cat", [], str(tmp_path / "v.mp4"), "16:9") + assert [request.url for request in sent] == [f"{host}/contents/generations/tasks"] diff --git a/tests/skills/test_video_generation_cli.py b/tests/skills/test_video_generation_cli.py index d0aa175aea..6b439dc471 100644 --- a/tests/skills/test_video_generation_cli.py +++ b/tests/skills/test_video_generation_cli.py @@ -17,10 +17,17 @@ def clean_env(monkeypatch): for key in ( "GEMINI_API_KEY", "MINIMAX_API_KEY", + "BYTEPLUS_AGENTPLAN_API_KEY", "VIDEO_GENERATION_PROVIDER", "MINIMAX_API_HOST", "MINIMAX_VIDEO_RESOLUTION", "MINIMAX_VIDEO_DURATION", + "BYTEPLUS_AGENTPLAN_BASE_URL", + "BYTEPLUS_AGENTPLAN_VIDEO_MODEL", + "BYTEPLUS_AGENTPLAN_VIDEO_RESOLUTION", + "BYTEPLUS_AGENTPLAN_VIDEO_DURATION", + "BYTEPLUS_AGENTPLAN_GENERATE_AUDIO", + "BYTEPLUS_AGENTPLAN_VIDEO_DOWNLOAD_HOSTS", ): monkeypatch.delenv(key, raising=False) @@ -33,6 +40,7 @@ def clean_env(monkeypatch): ("gemini", "GEMINI_API_KEY is not set"), ("google", "GEMINI_API_KEY is not set"), ("minimax", "MINIMAX_API_KEY is not set"), + ("byteplus_agentplan", "BYTEPLUS_AGENTPLAN_API_KEY is not set"), ("unknown", "Unknown video provider"), ], ) @@ -58,13 +66,19 @@ def test_cli_generation_failure_is_nonzero(monkeypatch, tmp_path, case, error): assert not output.exists() -@pytest.mark.parametrize("provider", ["gemini", "minimax"]) +@pytest.mark.parametrize("provider", ["gemini", "minimax", "byteplus_agentplan"]) @pytest.mark.parametrize("http_error", [False, True], ids=["success", "http-error"]) def test_cli_provider_result(monkeypatch, tmp_path, capsys, provider, http_error): monkeypatch.setenv("VIDEO_GENERATION_PROVIDER", provider) monkeypatch.setenv("GEMINI_API_KEY", "test-key") monkeypatch.setenv("MINIMAX_API_KEY", "test-key") - download_url = "https://filecdn.minimax.chat/video.mp4" if provider == "minimax" else "https://generativelanguage.googleapis.com/video.mp4" + monkeypatch.setenv("BYTEPLUS_AGENTPLAN_API_KEY", "test-key") + download_urls = { + "minimax": "https://filecdn.minimax.chat/video.mp4", + "gemini": "https://generativelanguage.googleapis.com/video.mp4", + "byteplus_agentplan": "https://bucket.tos-ap-southeast-1.volces.com/video.mp4", + } + download_url = download_urls[provider] prompt = tmp_path / "prompt.json" prompt.write_text('{"prompt": "A cat runs"}', encoding="utf-8") output = tmp_path / "video.mp4" @@ -81,13 +95,19 @@ def test_cli_provider_result(monkeypatch, tmp_path, capsys, provider, http_error def post(*args, **kwargs): if http_error: return response(status=500) - return response({"task_id": "task-1"} if provider == "minimax" else {"name": "operations/test"}) + if provider == "minimax": + return response({"task_id": "task-1"}) + if provider == "byteplus_agentplan": + return response({"id": "cgt-task-1"}) + return response({"name": "operations/test"}) def get(url, **kwargs): if url.endswith("/query/video_generation"): return response({"status": "Success", "file_id": "file-1"}) if url.endswith("/files/retrieve"): return response({"file": {"download_url": download_url}}) + if url.endswith("/contents/generations/tasks/cgt-task-1"): + return response({"id": "cgt-task-1", "status": "succeeded", "content": {"video_url": download_url}}) if url.endswith("/operations/test"): return response({"done": True, "response": {"generateVideoResponse": {"generatedSamples": [{"video": {"uri": download_url}}]}}}) assert url == download_url diff --git a/tests/skills/test_video_generation_reference_mime.py b/tests/skills/test_video_generation_reference_mime.py index 83637df99a..c30fb10494 100644 --- a/tests/skills/test_video_generation_reference_mime.py +++ b/tests/skills/test_video_generation_reference_mime.py @@ -16,16 +16,33 @@ def _mock_provider(monkeypatch, provider): monkeypatch.setenv("VIDEO_GENERATION_PROVIDER", provider) monkeypatch.setenv("GEMINI_API_KEY", "offline-test-key") monkeypatch.setenv("MINIMAX_API_KEY", "offline-test-key") + monkeypatch.setenv("BYTEPLUS_AGENTPLAN_API_KEY", "offline-test-key") monkeypatch.setenv("MINIMAX_API_HOST", "https://api.example.test") - download_url = "https://filecdn.minimax.chat/video.mp4" if provider == "minimax" else "https://generativelanguage.googleapis.com/video.mp4" - monkeypatch.delenv("MINIMAX_VIDEO_RESOLUTION", raising=False) - monkeypatch.delenv("MINIMAX_VIDEO_DURATION", raising=False) + download_urls = { + "minimax": "https://filecdn.minimax.chat/video.mp4", + "gemini": "https://generativelanguage.googleapis.com/video.mp4", + "byteplus_agentplan": "https://bucket.tos-ap-southeast-1.volces.com/video.mp4", + } + download_url = download_urls[provider] + for env_name in ( + "MINIMAX_VIDEO_RESOLUTION", + "MINIMAX_VIDEO_DURATION", + "BYTEPLUS_AGENTPLAN_BASE_URL", + "BYTEPLUS_AGENTPLAN_VIDEO_MODEL", + "BYTEPLUS_AGENTPLAN_VIDEO_RESOLUTION", + "BYTEPLUS_AGENTPLAN_VIDEO_DURATION", + "BYTEPLUS_AGENTPLAN_GENERATE_AUDIO", + "BYTEPLUS_AGENTPLAN_VIDEO_DOWNLOAD_HOSTS", + ): + monkeypatch.delenv(env_name, raising=False) captured = {"posts": [], "gets": []} def fake_post(url, *, json, **kwargs): captured["posts"].append(json) if provider == "gemini": return FakeResp({"name": "operations/offline-test"}) + if provider == "byteplus_agentplan": + return FakeResp({"id": "cgt-offline-task"}) return FakeResp({"task_id": "offline-task", "base_resp": {"status_code": 0}}) def fake_get(url, **kwargs): @@ -36,6 +53,8 @@ def _mock_provider(monkeypatch, provider): return FakeResp({"status": "Success", "file_id": "offline-file", "base_resp": {"status_code": 0}}) if url.endswith("/v1/files/retrieve"): return FakeResp({"file": {"download_url": download_url}, "base_resp": {"status_code": 0}}) + if url.endswith("/contents/generations/tasks/cgt-offline-task"): + return FakeResp({"id": "cgt-offline-task", "status": "succeeded", "content": {"video_url": download_url}}) assert url == download_url return FakeResp(content=b"offline-video-bytes") @@ -44,7 +63,7 @@ def _mock_provider(monkeypatch, provider): return captured -@pytest.mark.parametrize("provider", ["gemini", "minimax"]) +@pytest.mark.parametrize("provider", ["gemini", "minimax", "byteplus_agentplan"]) @pytest.mark.parametrize( "images", [ @@ -88,6 +107,14 @@ def test_provider_preserves_reference_image_mime(monkeypatch, tmp_path, provider assert reference["referenceType"] == "asset" assert reference["image"]["mimeType"] == expected_mime assert base64.b64decode(reference["image"]["bytesBase64Encoded"]) == image_bytes + elif provider == "byteplus_agentplan": + references = [item for item in request["content"] if item.get("type") == "image_url"] + assert len(references) == len(images) + for reference, (_, image_bytes, expected_mime) in zip(references, images, strict=True): + assert reference["role"] == "reference_image" + prefix, encoded = reference["image_url"]["url"].split(",", 1) + assert prefix == f"data:{expected_mime};base64" + assert base64.b64decode(encoded) == image_bytes else: # MiniMax uses only the first reference, as documented by the skill. prefix, encoded = request["first_frame_image"].split(",", 1) @@ -97,7 +124,7 @@ def test_provider_preserves_reference_image_mime(monkeypatch, tmp_path, provider assert "successfully" in result -@pytest.mark.parametrize("provider", ["gemini", "minimax"]) +@pytest.mark.parametrize("provider", ["gemini", "minimax", "byteplus_agentplan"]) @pytest.mark.parametrize("filename", ["reference", "reference.bmp", "reference.BMP", "reference.avif"]) def test_unsupported_reference_extension_rejected_before_submission(monkeypatch, tmp_path, provider, filename): captured = _mock_provider(monkeypatch, provider)