seedream_image_to_image
Edit images using text instructions to add or remove elements, change styles, replace materials, adjust colors, modify backgrounds, alter perspectives, or resize images.
Instructions
图文生图:
基于已有图片,结合文字指令进行图像编辑,包括图像元素增删、风格转化、材质替换、色调迁移、改变背景/视角/尺寸等。
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| params | Yes |
Implementation Reference
- seedream_mcp/server.py:98-108 (registration)Registers the MCP tool 'seedream_image_to_image' with metadata and wraps the runner function.@mcp.tool( name="seedream_image_to_image", annotations={"title": "Seedream 图生图", **GENERATION_TOOL_ANNOTATIONS}, ) async def seedream_image_to_image(params: ImageToImageInput) -> list[TextContent]: """ 图文生图: 基于已有图片,结合文字指令进行图像编辑,包括图像元素增删、风格转化、材质替换、色调迁移、改变背景/视角/尺寸等。 """ return await run_image_to_image(params)
- Core handler function executing the image-to-image tool logic: validates params, calls SeedreamClient API, handles streaming/auto-save, formats response or errors.async def handle_image_to_image(arguments: Dict[str, Any]) -> List[TextContent]: """ 处理图生图请求。 根据输入的图像和提示词生成新图像,支持多种配置选项包括尺寸、水印、 响应格式、流式输出、提示词优化及自动保存等功能。 Args: arguments: 请求参数字典,支持以下键值: - prompt (str, optional): 生成图像的提示词描述 - image (str): 输入图像的路径或URL - size (str, optional): 生成图像尺寸,默认使用配置中的默认值 - watermark (bool, optional): 是否添加水印,默认使用配置中的默认值 - response_format (str, optional): 响应格式,支持 "url" 或 "b64_json",默认为 "url" - stream (bool, optional): 是否启用流式输出,默认为 False - optimize_prompt_options (dict, optional): 提示词优化选项 - auto_save (bool, optional): 是否自动保存生成的图像,默认使用配置中的默认值 - save_path (str, optional): 自定义保存路径 - custom_name (str, optional): 自定义文件名 Returns: List[TextContent]: 包含生成结果或错误信息的文本内容列表, 成功时返回图像URL/Base64数据及元数据, 失败时返回格式化的错误信息和操作指引。 Raises: Exception: 捕获所有异常并转换为用户友好的错误消息,不向上层抛出。 """ try: # 获取全局配置 config = get_global_config() # 提取并验证请求参数 prompt = arguments.get("prompt", "") image = arguments.get("image") size = validate_size_for_model( arguments.get("size") or config.default_size, config.model_id ) watermark_value = arguments.get("watermark") watermark = ( validate_watermark(watermark_value) if watermark_value is not None else config.default_watermark ) response_format = validate_response_format(arguments.get("response_format", "url")) stream = bool(arguments.get("stream", False)) optimize_prompt_options = validate_optimize_prompt_options( arguments.get("optimize_prompt_options"), config.model_id ) auto_save = arguments.get("auto_save") save_path = arguments.get("save_path") custom_name = arguments.get("custom_name") # 确定是否启用自动保存功能 enable_auto_save = auto_save if auto_save is not None else config.auto_save_enabled # 记录请求信息 logger.info( "图生图开始: prompt='{}...', size={}, stream={}", (prompt or "")[:50], size, stream, ) # 调用客户端执行图生图请求 async with SeedreamClient(config) as client: result = await client.image_to_image( prompt=prompt, image=image, size=size, watermark=watermark, response_format=response_format, stream=stream, optimize_prompt_options=optimize_prompt_options, ) # 处理自动保存逻辑 auto_save_results: List[Any] = [] if enable_auto_save and result.get("success"): if response_format == "url": # URL格式:从远程URL下载并保存 auto_save_results = await auto_save_from_urls( result, prompt, config, save_path, custom_name, "image_to_image" ) else: # Base64格式:直接解码并保存 auto_save_results = await auto_save_from_base64( result, prompt, config, save_path, custom_name, "image_to_image" ) # 将保存结果合并到响应中 if auto_save_results: result = update_result_with_auto_save(result, auto_save_results) # 格式化响应文本 response_text = format_generation_response( "图生图任务完成", result, prompt, size, auto_save_results, enable_auto_save, ) return [TextContent(type="text", text=response_text)] except Exception as exc: # 记录异常详情 logger.error("图生图处理失败", exc_info=True) # 生成用户友好的错误信息和操作指引 guidance = "请检查图片路径/URL 与尺寸参数,确认 API Key 和网络可用后重试。" return [ TextContent( type="text", text=f"图生图生成失败:{format_error_for_user(exc)}\n{guidance}", ) ]
- Pydantic schema for ImageToImageInput defining input fields (prompt, image) and validators, inheriting common generation params.class ImageToImageInput(BaseGenerationInput): """ 图文生图:基于已有图片,结合文字指令进行图像编辑,包括图像元素增删、风格转化、材质替换、色调迁移、改变背景/视角/尺寸等。 """ prompt: str = Field( ..., min_length=1, description="图片修改或风格转换的指令,建议不超过300个汉字或600个英文单词。", ) image: str = Field( ..., description="待转换的图片,支持 URL、本地文件路径。", ) @field_validator("prompt") @classmethod def validate_prompt_field(cls, value: str) -> str: """ 校验并规范化提示词。 Args: value: 用户输入的提示词 Returns: 规范化后的提示词 Raises: ValueError: 当提示词格式或长度不符合要求时 """ try: return validate_prompt(value) except SeedreamValidationError as exc: raise ValueError(exc.message) from exc @field_validator("image") @classmethod def validate_image_field(cls, value: str) -> str: """ 校验图片来源。 Args: value: 图片 URL、文件路径 Returns: 规范化后的图片标识 Raises: ValueError: 当图片来源格式不合法时 """ try: return validate_image_url(value) except SeedreamValidationError as exc: raise ValueError(exc.message) from exc
- Intermediate runner that serializes validated schema to dict and calls the core handler.async def run_image_to_image(params: ImageToImageInput) -> List[TextContent]: """ 执行图像到图像转换工具。 Args: params: 图像到图像转换的已验证参数对象。 Returns: 包含转换结果的文本内容列表。 """ return await handle_image_to_image(params.model_dump(exclude_none=True))