Prhub

#45873 [Misc] Validate Cohere Embed Mixed Content Payloads

原始 PR 作者 taneem-ibrahim 合并时间 2026-06-17 14:57 文件变更 2 提交数 1 评论 0 代码增减 +53 / -0

执行摘要

Cohere Embed 混合内容 payload 校验

PR body 指出:当前 payload 如 {"type": "text"} 或 {"type": "image_url", "image_url": {}} 会通过请求解析,然后 _mixed_input_to_messages() 仅追加有效项,导致无效部分被静默跳过,在某些情况下变为空 user message,增加调试难度。因此需要在协议边界提前拒绝。

值得精读,尤其是 pydantic model_validator 的使用方式。该 PR 体现了“fail fast”的设计原则,适合作为类似校验场景的参考。

讨论亮点

该 PR 无 review 评论,仅由 noooop 直接批准。无讨论要点。

实现拆解

  1. 在 CohereEmbedContent 模型中添加校验器vllm/entrypoints/pooling/embed/protocol.py):
    • 使用 @model_validator(mode="after") 装饰器新增 validate_content_payload 方法。
    • type == "text"textNone 时,抛出 ValueError
    • type == "image_url"image_urlNoneimage_url.get("url") 为空时,抛出 ValueError
    • 校验器在 pydantic 反序列化时自动执行,确保非法 payload 在实例化时即失败。
  2. 添加测试用例tests/entrypoints/pooling/embed/test_io_processor.py):
    • 新增 test_rejects_invalid_mixed_content_payloads 参数化测试,覆盖 4 种非法 payload(纯 type、缺 url、空 url 等)。
    • 同时扩展 test_accepts_exactly_one_non_empty_input_field 以包含合法的 image_url 示例,避免回归。
文件 模块 状态 重要度
vllm/entrypoints/pooling/embed/protocol.py 请求协议 modified 6.5
tests/entrypoints/pooling/embed/test_io_processor.py 测试套件 modified 5.9

关键符号

validate_content_payload

关键源码片段

vllm/entrypoints/pooling/embed/protocol.py core-logic

核心变更文件,新增 validate_content_payload 校验器,在协议模型层面拦截非法 payload。

class CohereEmbedContent(BaseModel):
    type: Literal["text", "image_url"]
    text: str | None = None
    image_url: dict[str, str] | None = None
​
    @model_validator(mode="after")
    def validate_content_payload(self):
        # 校验 type="text" 时必须提供 text 字段
        if self.type == "text":
            if self.text is None:
                raise ValueError(
                    "CohereEmbedContent with type='text' requires text"
                )
        # 校验 type="image_url" 时必须提供 image_url.url 且非空
        elif not self.image_url or not self.image_url.get("url"):
            raise ValueError(
                "CohereEmbedContent with type='image_url' requires image_url.url"
            )
        return self

评论区精华

没有提炼出高价值讨论线程

当前评论区没有形成足够清晰的争议点或结论,后续有更多讨论时会体现在这里。

风险与影响

风险极低:

  • 仅在 CohereEmbedContent 模型反序列化时增加校验,不改变下游处理逻辑。
  • 测试覆盖了所有非法 payload 及合法 image_url 场景。
  • 变更集中,影响范围仅限于 Cohere /v2/embed 接口的混合内容路径。
  • 用户:非法 payload 将立即收到清晰的 ValidationError,而不是空响应或错误推理,提升调试体验。
  • 系统:无性能影响,校验仅发生在请求解析阶段。
  • 团队:代码可维护性提升,协议边界更明确。

关联 Issue

未识别关联 Issue

当前没有检测到明确关联的 Issue 链接,后续同步到相关引用后会出现在这里。

完整报告

参与讨论