Fix Cohere ChatV2 citation and tool handling issues (#52175)

Signed-off-by: Andrew Berneshawi <andrewberneshawi@cohere.com>
This commit is contained in:
andrewbcohere
2026-08-21 15:23:17 -07:00
committed by GitHub
parent f37d5868b9
commit f94dcde5c5
7 changed files with 1024 additions and 68 deletions
+130 -31
View File
@@ -89,7 +89,11 @@ from vllm.entrypoints.openai.models.serving import OpenAIServingModels
from vllm.entrypoints.serve.exception_handling.utils import sanitize_message
from vllm.entrypoints.serve.utils.request_logger import RequestLogger
from vllm.parser.abstract_parser import Parser
from vllm.renderers.cohere import MESSAGES_CITATIONS_KEY, POSITION_TO_SOURCE_KEY
from vllm.renderers.cohere import (
MESSAGES_CITATIONS_KEY,
POSITION_TO_SOURCE_KEY,
TOOL_MESSAGE_V2_CONTENT_KEY,
)
if TYPE_CHECKING:
from vllm.renderers.online_renderer import OnlineRenderer
@@ -97,6 +101,19 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__)
# Reserved ``chat_template_kwargs`` entries this handler populates for
# the API-server-side parser and renderer only. Stripped before the dict
# is forwarded to the engine core -- see
# :meth:`CohereServingChatV2._engine_chat_template_kwargs`.
_API_SERVER_ONLY_TEMPLATE_KWARGS = frozenset(
{
MESSAGES_CITATIONS_KEY,
POSITION_TO_SOURCE_KEY,
TOOL_MESSAGE_V2_CONTENT_KEY,
}
)
# ---------------------------------------------------------------------------
# SSE helpers
# ---------------------------------------------------------------------------
@@ -304,6 +321,28 @@ class CohereServingChatV2(OpenAIServingChat):
case _:
return self._chat_completion_stream_to_v2(generator, request)
def _engine_chat_template_kwargs(
self, chat_template_kwargs: dict[str, Any]
) -> dict[str, Any]:
"""Keep this handler's internal entries out of the engine hop.
Overrides :meth:`OpenAIServingChat._engine_chat_template_kwargs`.
The reserved keys in :data:`_API_SERVER_ONLY_TEMPLATE_KWARGS`
exist only to hand request-side state to the API-server-side
parser and renderer; the engine-core-side reasoning parser (used
for structured-output reasoning-end gating) never reads them. They
also can't survive the trip: ``POSITION_TO_SOURCE_KEY`` holds
:class:`CitationSource` models, and msgpack -- which encodes
``reasoning_parser_kwargs`` on the way to the engine core -- has
no native encoding for Pydantic models, so forwarding them fails
the request with a ``TypeError``.
"""
return {
k: v
for k, v in chat_template_kwargs.items()
if k not in _API_SERVER_ONLY_TEMPLATE_KWARGS
}
# ==================================================================
# Request conversion: Cohere V2 -> ChatCompletionRequest
# ==================================================================
@@ -438,46 +477,53 @@ class CohereServingChatV2(OpenAIServingChat):
"content": msg.content,
}
# When the tool result is text-only, flatten to a string for
# maximum compatibility with standard chat templates. When it
# includes documents, preserve them as structured content parts
# so the cohere renderer can surface them as grounding sources
# (the :class:`CohereRenderer` understands
# ``{type: document, document: {...}}`` blocks). Non-cohere
# renderers may not honor document blocks, but that matches
# the broader "documents are no-op for OSS models" contract
# documented on this endpoint.
# Map every content block to a plain ``{"type": "text", "text":
# ...}`` part, mirroring the shape :meth:`_convert_user_message`
# emits for multi-part user content. vLLM's
# ``_parse_chat_message_content`` collapses a text-only tool
# part list back into ``"\n".join(...)`` on the way to the
# renderer, so simple chat templates that expect string tool
# content still work; keeping the list here just preserves the
# per-block structure at the OpenAI-shape request level for
# symmetry with the user-message conversion.
#
# Tool message content uses ``ToolMessageV2Content``, which is a
# union of ``TextToolContent`` and ``DocumentToolContent`` -
# distinct from the user-message text/image union. We discriminate
# on the ``type`` literal so we don't have to import each variant.
has_documents = any(block.type == "document" for block in msg.content)
if not has_documents:
text = "\n".join(
block.text for block in msg.content if block.type == "text"
)
return {
"role": "tool",
"tool_call_id": msg.tool_call_id,
"content": text,
}
parts: list[dict[str, Any]] = []
# Tool message content uses ``ToolMessageV2Content``, a union of
# ``TextToolContent`` and ``DocumentToolContent``. The latter
# produces ``{"type": "document", "document": {...}}`` blocks,
# which vLLM's shared ``_parse_chat_message_content_parts`` in
# ``vllm/entrypoints/chat_utils.py`` rejects because the OpenAI
# ``ChatCompletionContentPartParam`` union only knows text /
# image / audio / etc. Emitting them anyway triggers a Pydantic
# ``ValidatorIterator`` failure at chat-parsing time, so we
# JSON-serialize each document into a text part instead.
#
# The cohere renderer doesn't consume this flattened content:
# :meth:`_collect_v2_tool_message_content` forwards the
# original v2 content blocks under
# :data:`TOOL_MESSAGE_V2_CONTENT_KEY`, and the renderer applies
# :func:`vllm.renderers.cohere._v2_tool_content_to_melody_block`
# to produce the melody-shape ``document`` blocks cmd3/cmd4
# tool-result rendering expects. Outbound citation binding is
# unaffected either way: sources resolve through the
# ``POSITION_TO_SOURCE_KEY`` map (built from the original v2
# messages, not the converted OpenAI messages).
content_parts: list[dict[str, Any]] = []
for block in msg.content:
if block.type == "text":
parts.append({"type": "text", "text": block.text})
content_parts.append({"type": "text", "text": block.text})
elif block.type == "document":
parts.append(
content_parts.append(
{
"type": "document",
"document": block.document.model_dump(exclude_none=True),
"type": "text",
"text": json.dumps(
block.document.model_dump(exclude_none=True)
),
}
)
return {
"role": "tool",
"tool_call_id": msg.tool_call_id,
"content": parts,
"content": content_parts,
}
@classmethod
@@ -660,6 +706,16 @@ class CohereServingChatV2(OpenAIServingChat):
if position_to_source:
kwargs.setdefault(POSITION_TO_SOURCE_KEY, position_to_source)
# Forward the original v2 tool-message content blocks so the
# renderer can apply its v2 → melody mapping over them (the
# renderer owns the melody-shape rules, this handler only
# ships the raw structural info that OpenAI validation would
# otherwise destroy -- see the flatten comment in
# :meth:`_convert_tool_message`).
v2_tool_content = cls._collect_v2_tool_message_content(request)
if v2_tool_content:
kwargs.setdefault(TOOL_MESSAGE_V2_CONTENT_KEY, v2_tool_content)
if kwargs:
chat_req.chat_template_kwargs = kwargs
@@ -1262,6 +1318,49 @@ class CohereServingChatV2(OpenAIServingChat):
)
return None
@classmethod
def _collect_v2_tool_message_content(
cls, request: CohereChatV2Request
) -> dict[int, list[dict[str, Any]]]:
"""Collect the original v2 tool-message content blocks so the
renderer can apply its v2 → melody mapping.
Builds the map that
:meth:`_apply_cohere_template_kwargs` stashes under
:data:`TOOL_MESSAGE_V2_CONTENT_KEY` for the renderer to
consume (see the constant definition in
:mod:`vllm.renderers.cohere` for why the map exists). Walks
``request.messages`` -- not the OpenAI-shape messages built by
:meth:`_convert_messages` -- because that flattening step
already threw away the structural distinction between text and
document blocks. Each surviving block is
:meth:`~pydantic.BaseModel.model_dump`'d to a plain dict so the
forwarded map carries no Pydantic instances (msgpack- /
general-serialization-safe on principle even though internal
underscore-prefixed keys are filtered before crossing the
engine-core boundary).
Only emits an entry for a tool message whose content is a
non-empty list of blocks; a bare-string tool message renders
fine through the default text-block path in
:func:`vllm.renderers.cohere._content_blocks`, so no forwarded
blocks are needed there. Returns an empty dict when there is
nothing to forward, so the caller can use truthiness to decide
whether to stash the key at all.
"""
blocks_by_index: dict[int, list[dict[str, Any]]] = {}
for i, msg in enumerate(request.messages):
if not isinstance(msg, ToolChatMessageV2):
continue
if isinstance(msg.content, str) or not msg.content:
continue
v2_blocks: list[dict[str, Any]] = []
for block in msg.content:
v2_blocks.append(block.model_dump(exclude_none=True))
if v2_blocks:
blocks_by_index[i] = v2_blocks
return blocks_by_index
@staticmethod
def _build_usage(response: ChatCompletionResponse) -> CohereUsage | None:
if response.usage is None:
@@ -196,6 +196,24 @@ class OpenAIServingChat(GenerateBaseServing):
.chat_template_kwargs
)
def _engine_chat_template_kwargs(
self, chat_template_kwargs: dict[str, Any]
) -> dict[str, Any]:
"""Subclass hook to narrow ``chat_template_kwargs`` for the engine.
The same dict is used twice: to build the API-server-side parser
instance, and to populate
``EngineCoreRequest.reasoning_parser_kwargs`` for the engine-core
side. The latter crosses ZMQ as msgpack, so a handler that stashes
request-scoped state only the API-server-side parser needs (values
msgpack can't encode, or payloads not worth shipping) can drop
those entries here without affecting the in-process parser.
Must not mutate the argument -- the caller still needs the full
dict. The default forwards it unchanged.
"""
return chat_template_kwargs
async def render_chat_request(
self,
request: ChatCompletionRequest,
@@ -360,7 +378,9 @@ class OpenAIServingChat(GenerateBaseServing):
session_id=session_id,
reasoning_ended=reasoning_ended,
reasoning_parser_kwargs={
"chat_template_kwargs": chat_template_kwargs,
"chat_template_kwargs": self._engine_chat_template_kwargs(
chat_template_kwargs
),
}
if parser is not None and parser.reasoning_parser is not None
else None,
@@ -681,27 +681,12 @@ class BaseCohereCommandReasoningParser(ReasoningParser):
return request
# melody's streaming filter only buffers a partial ``<co: ...>`` citation
# across ``write_decoded`` calls when ``stream_non_grounded_answer`` is
# set: otherwise, the moment an opening ``<co`` is seen without a
# closing ``</co: ...>`` in the same delta, the filter emits the partial
# marker bytes verbatim as plain content. In vLLM's streaming path the
# parser is fed one token (1-4 chars) per call, so an unbuffered filter
# will leak ``<co: 0>``-style markers into ``delta.content`` and never
# emit a ``FilterCitation`` for them. Enabling the flag flips the
# partial-match branch in melody's ``parse_citations`` (see
# ``src/parsing/citations_filter.rs``) to ``return (None, 0)`` -- i.e.
# keep buffering -- which lets a full citation eventually resolve.
# Non-streaming (unary) parsing receives the whole output in one call so
# the flag is a no-op there and we leave ``unary_opts`` alone.
class CohereCommand3ReasoningParser(BaseCohereCommandReasoningParser):
def __init__(self, tokenizer: TokenizerLike, *args, **kwargs):
super().__init__(
tokenizer,
*args,
streaming_opts=(
PyFilterOptions().cmd3().no_tools().stream_non_grounded_answer()
),
streaming_opts=PyFilterOptions().cmd3().no_tools(),
unary_opts=PyFilterOptions().cmd3().no_tools(),
**kwargs,
)
@@ -712,9 +697,7 @@ class CohereCommand4ReasoningParser(BaseCohereCommandReasoningParser):
super().__init__(
tokenizer,
*args,
streaming_opts=(
PyFilterOptions().cmd4().no_tools().stream_non_grounded_answer()
),
streaming_opts=PyFilterOptions().cmd4().no_tools(),
unary_opts=PyFilterOptions().cmd4().no_tools(),
**kwargs,
)
+131 -6
View File
@@ -157,6 +157,40 @@ MESSAGES_CITATIONS_KEY = "_messages_citations"
POSITION_TO_SOURCE_KEY = "_position_to_source"
# Reserved ``chat_template_kwargs`` key carrying the original Cohere v2
# tool-message content, keyed by request-message index. Populated by
# :meth:`CohereServingChatV2._apply_cohere_template_kwargs` and consumed
# by :func:`_conversation_to_melody_messages`, which runs each block
# through :func:`_v2_tool_content_to_melody_block` to produce the
# melody-shape content list the renderer emits.
#
# Motivation: OpenAI's ``ChatCompletionContentPartParam`` union (in
# ``vllm/entrypoints/chat_utils.py``) only allows ``text`` / ``image_url``
# / ``audio`` / ``video`` / ``file`` content parts on tool messages, so
# ``{"type": "document", "document": {...}}`` blocks -- valid in Cohere
# v2 -- get rejected by vLLM's shared chat validator before they can
# reach the renderer.
# ``CohereServingChatV2._convert_tool_message`` works around that by
# rewriting each content block into a plain ``text`` part (with document
# blocks JSON-serialized inline), but that flattening loses the
# structural distinction the cohere renderer needs to shape tool-result
# payloads for cmd3/cmd4. The serving layer therefore forwards the
# original v2 content blocks verbatim (as plain dicts) under this key,
# and the renderer owns the v2-shape → melody-shape mapping.
#
# Value type: ``dict[int, list[dict[str, Any]]]``. Each list entry is a
# ``model_dump``'d ``TextToolContent`` / ``DocumentToolContent`` block
# (e.g. ``{"type": "text", "text": ...}`` or ``{"type": "document",
# "document": {"id": ..., "data": {...}}}``). Index is the position of
# the tool message in the request's ``messages`` list, which -- since
# ``_convert_messages`` is 1-to-1 -- also matches its position in the
# ``ConversationMessage`` list handed to the renderer. Leading
# underscore signals "internal, not part of the public
# ``chat_template_kwargs`` surface" -- clients should not set this key
# directly.
TOOL_MESSAGE_V2_CONTENT_KEY = "_tool_message_v2_content"
# Keys this renderer interprets directly from ``chat_template_kwargs`` and
# maps onto typed melody render-config fields. Everything *not* in this
# set is forwarded verbatim to melody as ``additional_template_fields``
@@ -196,6 +230,7 @@ _RENDERER_CONSUMED_KEYS = frozenset(
"platform_instruction",
MESSAGES_CITATIONS_KEY,
POSITION_TO_SOURCE_KEY,
TOOL_MESSAGE_V2_CONTENT_KEY,
}
)
@@ -377,6 +412,69 @@ def _content_blocks(content: Any) -> list[dict[str, Any]]:
return blocks
def _v2_tool_content_to_melody_block(block: dict[str, Any]) -> dict[str, Any] | None:
"""Convert one Cohere v2 tool-message content block into a melody
``document`` content block.
Cohere's chat v2 admits two shapes for tool-message content parts:
* ``TextToolContent`` -- ``{"type": "text", "text": "..."}``.
* ``DocumentToolContent`` -- ``{"type": "document", "document":
{"id"?: str, "data": {...}}}``.
Both are emitted as melody ``document`` blocks, mirroring the cohere
api, which routes every tool content part through the same
"tool output as document" conversion. The rules:
* Text that parses to a JSON object becomes that object directly
(so structured tool output flows through as first-class fields).
* Text that doesn't parse as an object -- empty, non-JSON,
or JSON scalar/array -- gets wrapped as ``{"content": <text>}``
so templates have a stable field name to look up.
* ``document`` blocks unwrap ``document.data`` (a flat map) into
the melody payload; ``document.id`` is intentionally dropped
here because outbound citation binding tracks it separately via
``POSITION_TO_SOURCE_KEY``.
Only the JSON-object case actually changes what gets rendered. The
cmd3/cmd4 templates already wrap a bare ``text`` content block as
``{"content": <text>}`` themselves, so routing plain text through
here is a no-op on the prompt -- it is the JSON-object unwrap that
promotes structured tool output from an escaped string blob into
individually addressable (and citable) result fields.
Note the payload is the *flat* field map: melody's ``Content``
carries ``document`` as a plain map, so re-nesting it under a
``data`` key would render a spurious ``{"data": {...}}`` wrapper
into the tool-result block.
Returns ``None`` for unrecognised shapes; the caller should skip
those blocks (the citation-numbering walk in
``CohereServingChatV2._walk_citable_positions`` advances its own
cursor over unknown blocks, so slot alignment is preserved).
"""
block_type = block.get("type")
if block_type == "text":
text = block.get("text") or ""
try:
parsed = json.loads(text)
except (json.JSONDecodeError, TypeError):
parsed = None
if isinstance(parsed, dict):
payload: dict[str, Any] = dict(parsed)
else:
payload = {"content": text}
return {"type": MelodyContentType.DOCUMENT, "document": payload}
if block_type == "document":
doc = block.get("document")
if not isinstance(doc, dict):
return None
data = doc.get("data")
payload = dict(data) if isinstance(data, dict) else {}
return {"type": MelodyContentType.DOCUMENT, "document": payload}
return None
def _document_to_melody(doc: Any) -> dict[str, Any]:
"""Coerce a Cohere v2 document into melody's ``Document`` (dict) shape."""
match doc:
@@ -421,6 +519,7 @@ def _tool_to_melody(tool: Any) -> dict[str, Any]:
def _conversation_to_melody_messages(
conversation: list[ConversationMessage],
messages_citations: dict[int, list[dict[str, Any]]] | None = None,
tool_message_v2_content: dict[int, list[dict[str, Any]]] | None = None,
) -> list[dict[str, Any]]:
"""Convert vLLM ``ConversationMessage``s into melody's message dict shape.
@@ -429,17 +528,42 @@ def _conversation_to_melody_messages(
``CohereServingChatV2`` under the
:data:`MESSAGES_CITATIONS_KEY` chat_template_kwargs entry. Values
must already be in melody's ``FilterCitation`` dict shape (see
``CohereServingChatV2._sdk_citation_to_melody``). Index is the
position in the *input* ``conversation`` list, which currently maps
1-to-1 with ``CohereChatV2Request.messages`` for text-only Cohere
requests. This mapping breaks silently if ``parse_chat_messages``
ever expands a single input message into multiple entries (e.g.
``CohereServingChatV2._sdk_citation_to_melody``).
``tool_message_v2_content`` is an optional index-keyed lookup of
the original Cohere v2 tool-message content blocks (as plain
dicts), populated by ``CohereServingChatV2`` under the
:data:`TOOL_MESSAGE_V2_CONTENT_KEY` entry. When set for a given
index, its blocks -- run through
:func:`_v2_tool_content_to_melody_block` to apply the v2 → melody
mapping -- replace the block list this function would otherwise
derive from ``msg["content"]``. This lets the renderer own the
v2-shape → melody-shape conversion for the structured ``document``
blocks cohere v2 allows on tool messages (which don't survive
OpenAI's content-parts validator on the way in, so
``_convert_tool_message`` rewrites them into ``text`` parts).
Both index lookups key by position in the *input* ``conversation``
list, which currently maps 1-to-1 with
``CohereChatV2Request.messages`` for text-only Cohere requests.
This mapping breaks silently if ``parse_chat_messages`` ever
expands a single input message into multiple entries (e.g.
multi-modal splitting), which is not the case today.
"""
out: list[dict[str, Any]] = []
for i, msg in enumerate(conversation):
role = _role_to_melody(msg.get("role", "user"))
content_blocks = _content_blocks(msg.get("content"))
if (
tool_message_v2_content is not None
and (v2_blocks := tool_message_v2_content.get(i)) is not None
):
content_blocks = []
for v2_block in v2_blocks:
mapped = _v2_tool_content_to_melody_block(v2_block)
if mapped is not None:
content_blocks.append(mapped)
else:
content_blocks = _content_blocks(msg.get("content"))
# Treat reasoning content as a thinking block on assistant turns
# so multi-turn reasoning is preserved in the rendered prompt.
@@ -513,6 +637,7 @@ def _build_render_config(
"messages": _conversation_to_melody_messages(
conversation,
chat_template_kwargs.get(MESSAGES_CITATIONS_KEY),
chat_template_kwargs.get(TOOL_MESSAGE_V2_CONTENT_KEY),
),
}