vllm.renderers.cohere
¶
Cohere prompt renderer.
Templates the Cohere Command-family prompt formats (cmd3 / cmd4) using
the cohere_melody Rust bindings instead of Jinja. Enabled by
passing --tokenizer-mode cohere on the engine; tokenization itself
still flows through the cached HuggingFace tokenizer.
The renderer's client surface is chat_template_kwargs (vLLM's
generic passthrough for template-time inputs). It is fed by two
different code paths, which speak different vocabularies:
vllm.entrypoints.cohere.serving.CohereServingChatV2-- translates a native Cohere Chat v2 request intochat_template_kwargs.OpenAIServingChat-- forwards whatever the client puts inrequest.chat_template_kwargsdirectly, without translation.
Accordingly the renderer accepts keys from both vocabularies.
Cohere Chat v2 request fields (populated automatically by
CohereServingChatV2; a direct chat_template_kwargs caller may
also pass them):
documents: list of documents (v2documents)tools: list of tools (v2tools)safety_mode: v2safety_mode(CONTEXTUAL/STRICT/NONE) -- forwarded to melody's cmd3safety_modeslot; lowercased.citation_options: v2citation_options. Its.mode(ENABLED/DISABLED/FAST/ACCURATE/OFF) is normalized into melody's cmd3citation_quality(on/off) and cmd4grounding(enabled/disabled/unknown) slots. cmd4 has no fast/accurate distinction at the prompt-template layer -- both mean grounding-on.response_format: v2response_format(json_object/json_schema) -- mapped onto melody'sjson_mode/json_schemaconfig slots.thinking: v2thinking; its.type(enabled/disabled) becomes melody'sreasoning_type.
Melody template-config knobs (accepted for direct-passthrough callers; not part of the Cohere Chat v2 surface):
cohere_format: renderer selector,cmd3orcmd4(defaultcmd4).template_id: pick one of melody's built-in template variants.available_tools: melody's own name for tools; takes precedence overtoolswhen both are set.reasoning_type: directenabled/disabledtoggle; overrides derivation fromthinking.type.dev_instruction: developer-instruction override.json_mode/json_schema: direct structured-output toggles; override derivation fromresponse_format.- cmd3-only:
citation_quality(on/off),skip_preamble. - cmd4-only:
grounding(enabled/disabled/unknown; overrides derivation fromcitation_options.mode),platform_instruction.
Rejected inputs: This renderer accepts server-configured chat templates.
Online requests may select a built-in template or supply template variables.
They cannot supply template source through chat_template or the
template_jinja and template Cohere-specific kwargs.
Everything else in chat_template_kwargs is forwarded verbatim
to melody as additional_template_fields and becomes accessible as
Jinja variables inside the template. This matches vLLM's documented
contract for chat_template_kwargs ("kwargs accessible by the
template"), so e.g. chat_template_kwargs={"reasoning_effort":
"low"} resolves {{ reasoning_effort }} inside cmd3 / cmd4
templates.
Citations produced by Cohere models are surfaced through the
Cohere-scoped CohereChatMessage.citations /
CohereDeltaMessage.citations fields (see
vllm.entrypoints.cohere.cohere_chat_message), populated by the
cohere2 reasoning parser. The base OpenAI ChatMessage /
DeltaMessage keep their declared schemas unchanged; the response
envelope declares them as SerializeAsAny[...] so the subclass
fields survive JSON serialization.
Classes:
-
CohereRenderer–Renderer that templates Cohere prompts via the melody Rust bindings.
-
MelodyContentType–Wire-format discriminator for melody content blocks.
CohereRenderer
¶
Bases: BaseHfRenderer[HfTokenizer]
Renderer that templates Cohere prompts via the melody Rust bindings.
Tokenization is delegated to the standard HF tokenizer; only the
chat-template step is replaced with cohere_melody.render_cmd3 /
render_cmd4. Enabled via --tokenizer-mode cohere.
MelodyContentType
¶
Bases: StrEnum
Wire-format discriminator for melody content blocks.
These strings are what the cmd3 / cmd4 Jinja templates check against
in message.content[0].type (e.g. the thinking branch in
cmd4-v1.jinja). Keep new values in sync with melody's template
schema.
_build_render_config(conversation, chat_template_kwargs, chat_template=None)
¶
Build the render_cmd3 / render_cmd4 config dict.
chat_template is the server-configured template or an offline template.
When non-None it is forwarded to melody as template_jinja.
Returns (format, config_dict) where format is either "cmd3"
or "cmd4".
_content_blocks(content)
¶
Convert OpenAI ConversationMessage.content into melody content blocks.
The chat_utils content_format="openai" produces a list of
{type: text, text: ...} dicts already; we pass those through with
minimal coercion. Plain string content is wrapped in a single text block.
Image / multimodal placeholder dicts ({"type": "image"}) are
forwarded as-is so that templates can reference image placeholders that
the upstream tokenizer expands separately.
_conversation_to_melody_messages(conversation, messages_citations=None, tool_message_v2_content=None)
¶
Convert vLLM ConversationMessages into melody's message dict shape.
messages_citations is an optional index-keyed lookup of
per-message citations from the request, populated by
CohereServingChatV2 under the
MESSAGES_CITATIONS_KEY chat_template_kwargs entry. Values
must already be in melody's FilterCitation dict shape (see
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
TOOL_MESSAGE_V2_CONTENT_KEY entry. When set for a given
index, its blocks -- run through
_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.
_document_to_melody(doc)
¶
Coerce a Cohere v2 document into melody's Document (dict) shape.
_normalize_cmd4_grounding(value)
¶
Coerce a user-facing grounding/citation mode to melody's vocab.
Raises ValueError rather than letting an unrecognized value
slip through to render_cmd4 and surface as a generic
Invalid config: grounding from melody.
_normalize_tool_call(tc)
¶
Normalize an OpenAI tool call dict into melody's tool call shape.
melody expects {id, name, parameters: <json str>} whereas OpenAI
delivers {id, type, function: {name, arguments: <json|str>}}.
_role_to_melody(role)
¶
Map an OpenAI role to the role string melody expects.
The cmd3 / cmd4 jinja templates only recognize system, user,
assistant/chatbot, and tool: any other role is silently
dropped by the template's role-dispatch chain (no fallback branch),
which produces a malformed prompt without any error. We therefore
refuse unknown roles up front rather than letting them disappear.
Aliases:
assistant->chatbot(Cohere's historical assistant role name used by the templates).developer->system(OpenAI'sdeveloperrole is documented as high-priority instructions, which maps onto thesystemslot in Cohere's prompt format).
_tool_to_melody(tool)
¶
Coerce a chat completions tool definition into melody's Tool shape.
Accepts either the raw OpenAI tool wrapper {type:"function", function:
{name, description, parameters}} or a flat {name, description,
parameters} dict (which is what melody itself expects).
_v2_tool_content_to_melody_block(block)
¶
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. documentblocks unwrapdocument.data(a flat map) into the melody payload;document.idis intentionally dropped here because outbound citation binding tracks it separately viaPOSITION_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).