Skip to content

Add rerank support to Cohere provider - #72501

Merged
potiuk merged 3 commits into
apache:mainfrom
jeff3071:add-rerank-cohere
Sep 9, 2026
Merged

potiuk merged 3 commits into
apache:mainfrom
jeff3071:add-rerank-cohere

Conversation

@jeff3071

@jeff3071 jeff3071 commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

Why

Cohere provider only supports embedding and does not provide an operator for the Rerank API.

What

  • Add CohereHook.rerank to rank documents by relevance to a query.
  • Add CohereRerankOperator with top_n and max_tokens_per_doc support.
  • Return an XCom-serializable dictionary containing ranked indexes and relevance scores.
  • Add unit tests, documentation, and an example Dag.

Test

Use the testing Dag below with a Cohere connection (Azure).

from __future__ import annotations

import logging
from datetime import datetime, timezone
from typing import Any

from airflow.providers.cohere.operators.rerank import CohereRerankOperator
from airflow.sdk import dag, task

log = logging.getLogger(__name__)


@dag(
    dag_id="test_azure_cohere_rerank",
    schedule=None,
    start_date=datetime(2025, 1, 1, tzinfo=timezone.utc),
    catchup=False,
    tags=["cohere", "azure", "rerank", "test"],
)
def test_azure_cohere_rerank():
    reranked = CohereRerankOperator(
        task_id="rerank_documents",
        conn_id="cohere_azure",
        query="What is the capital of the United States?",
        documents=[
            "Carson City is the capital city of Nevada.",
            "Washington, D.C. is the capital of the United States.",
            "The capital city of France is Paris.",
        ],
        top_n=2,
    )

    @task
    def verify_results(response: dict[str, Any]) -> None:
        results = response.get("results")
        if not results:
            raise ValueError("Cohere returned no reranking results")
        first_result = results[0]
        if "index" not in first_result or "relevance_score" not in first_result:
            raise ValueError("Cohere reranking result is missing its index or relevance score")
        log.info("Highest-ranked document: %s", first_result)

    verify_results(reranked.output)


test_azure_cohere_rerank()

log

::group::Log message source details
/root/airflow/logs/dag_id=test_azure_cohere_rerank/run_id=manual__2026-09-04T06:59:03.159000+00:00/task_id=rerank_documents/attempt=1.log
::endgroup::
[2026-09-04T06:59:04.172411Z] INFO - ::group::Pre Execute
Task Identity ti_id=01a06b36-b784-737c-a285-3fa0673a58dc dag_id=test_azure_cohere_rerank task_id=rerank_documents run_id=manual__2026-09-04T06:59:03.159000+00:00 try_number=1 map_index=-1
[2026-09-04T06:59:04.208824Z] INFO - DAG bundles loaded: dags-folder
[2026-09-04T06:59:04.209832Z] INFO - Filling up the DagBag from /files/dags/test_azure_cohere_rerank.py
[2026-09-04T06:59:04.284956Z] INFO - Worker startup parse complete bundle_name=dags-folder  bundle_version=null  dag_file=test_azure_cohere_rerank.py  bundle_prepare_ms=2  dag_file_parse_ms=75 
[2026-09-04T06:59:04.312538Z] INFO - ::endgroup::
[2026-09-04T06:59:08.422692Z] INFO - ::group::Post Execute
[2026-09-04T06:59:08.423119Z] INFO - Pushing xcom ti=RuntimeTaskInstance(id=UUID('01a06b36-b784-737c-a285-3fa0673a58dc'), task_id='rerank_documents', dag_id='test_azure_cohere_rerank', run_id='manual__2026-09-04T06:59:03.159000+00:00', try_number=1, dag_version_id=UUID('01a06b31-96de-780b-9344-11512671e374'), map_index=-1, hostname='bed06d3cd41b', context_carrier={'traceparent': '00-398c0a86f4882365defcedb4de9cea71-e1df67c087d2aa62-00'}, queue='default', task=<Task(CohereRerankOperator): rerank_documents>, bundle_instance=LocalDagBundle(name=dags-folder), max_tries=0, start_date=datetime.datetime(2026, 9, 4, 6, 59, 4, 178740, tzinfo=datetime.timezone.utc), end_date=None, state=<TaskInstanceState.RUNNING: 'running'>, is_mapped=False, rendered_map_index=None, sentry_integration='') 
[2026-09-04T06:59:08.479633Z] INFO - ::endgroup::


::group::Log message source details
/root/airflow/logs/dag_id=test_azure_cohere_rerank/run_id=manual__2026-09-04T06:59:03.159000+00:00/task_id=verify_results/attempt=1.log
::endgroup::
[2026-09-04T06:59:09.077249Z] INFO - ::group::Pre Execute
Task Identity ti_id=01a06b36-b785-7dde-b2c0-3e3fa1256d3c dag_id=test_azure_cohere_rerank task_id=verify_results run_id=manual__2026-09-04T06:59:03.159000+00:00 try_number=1 map_index=-1
[2026-09-04T06:59:09.088840Z] INFO - DAG bundles loaded: dags-folder
[2026-09-04T06:59:09.089513Z] INFO - Filling up the DagBag from /files/dags/test_azure_cohere_rerank.py
[2026-09-04T06:59:09.165990Z] INFO - Worker startup parse complete bundle_name=dags-folder  bundle_version=null  dag_file=test_azure_cohere_rerank.py  bundle_prepare_ms=1  dag_file_parse_ms=76 
[2026-09-04T06:59:09.190519Z] INFO - ::endgroup::
[2026-09-04T06:59:09.191773Z] INFO - Highest-ranked document: {'index': 1, 'relevance_score': 0.9446076}
[2026-09-04T06:59:09.191919Z] INFO - Done. Returned value was: None
[2026-09-04T06:59:09.192023Z] INFO - ::group::Post Execute
[2026-09-04T06:59:09.200257Z] INFO - ::endgroup::


Was generative AI tooling used to co-author this PR?
  • Yes (GPT 5.6 sol)

Generated-by: [GPT 5.6 sol] following the guidelines


  • Read the Pull Request Guidelines for more information. Note: commit author/co-author name and email in commits become permanently public when merged.
  • For fundamental code changes, an Airflow Improvement Proposal (AIP) is needed.
  • When adding dependency, check compliance with the ASF 3rd Party License Policy.
  • For significant user-facing changes create newsfragment: {pr_number}.significant.rst, in airflow-core/newsfragments. You can add this file in a follow-up commit after the PR is created so you know the PR number.

@potiuk potiuk left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this — the shape of the change is right. It mirrors CohereEmbeddingOperator closely (same cached_property hook, same common.compat.sdk imports, same example-DAG and docs layout), provider.yaml and the generated get_provider_info.py agree, and the test file lands where the provider-structure check expects it. Two things need fixing first.

1. The default rerank model is an Azure deployment name, and nothing can override it

In hooks/cohere.py:

model: str = "Cohere-rerank-v4.0-pro",

That capitalised Cohere- prefix is the Azure AI Foundry catalog naming convention (Cohere-rerank-v3.5, Cohere-embed-v3-english), not a model ID on api.cohere.com, where they are lowercase (rerank-v3.5, rerank-multilingual-v3.0). The description confirms the end-to-end testing was against an Azure connection (conn_id="cohere_azure"), which is how this slipped through. Two corroborating signals: the PR's own unit test uses model="rerank-v3.5", the canonical form, and the sibling create_embeddings defaults to embed-multilingual-v3.0, a real Cohere ID. As it stands, a user on a plain cohere_default connection gets a bad model name on the primary path.

Compounding it: the operator has no model parameter at all. CohereRerankOperator.__init__ doesn't accept one and execute() doesn't forward one, so every task is pinned to that default with no escape hatch. The new doc page says:

The model is configured by the hook.

but CohereHook.__init__ has no model parameter either — it exists only as a per-call kwarg the operator never passes. So the documented configuration path doesn't exist in any form.

Suggested fix: default the hook to a canonical Cohere model ID, add model: str | None = None to the operator and forward it when set, and correct that sentence in rerank.rst.

(CohereEmbeddingOperator has the same hook-only-model limitation, so there is precedent — but the docs here actively promise otherwise, which makes it worth closing rather than repeating.)

2. top_n / max_tokens_per_doc as template fields will send strings to the API

template_fields: Sequence[str] = ("query", "documents", "top_n", "max_tokens_per_doc")

and rerank.rst states "both limits are templated fields". Airflow's renderer passes non-str/list/dict values through untouched, so a literal top_n=2 is unaffected — but as soon as someone uses the advertised templating (top_n="{{ params.n }}") the rendered value stays a str. The Cohere client does no validation on these; V2Client.rerank puts them straight into the request body:

json={"model": model, "query": query, "documents": documents,
      "top_n": top_n, "return_documents": return_documents,
      "max_tokens_per_doc": max_tokens_per_doc},

so "top_n": "3" reaches the API as a JSON string. Either drop the two ints from template_fields (and the claim from the docs), or coerce with int(...) at the top of execute() after rendering.

3. Minor: None is serialised as JSON null rather than omitted

The client uses omit=OMIT where OMIT is Ellipsis, so the hook's unconditional top_n=top_n, max_tokens_per_doc=max_tokens_per_doc sends "top_n": null / "max_tokens_per_doc": null instead of omitting the keys. The Azure run in the description had max_tokens_per_doc=None and succeeded, so the API tolerates it — low risk, but building the kwargs conditionally is more robust against other Cohere-compatible endpoints.

The version floor is fine, for what it's worth: max_tokens_per_doc is present on ClientV2.rerank in cohere==5.13.4, the provider's minimum pin, so no dependency bump is needed.

Nits

  • CohereHook.rerank has no docstring, and CohereRerankOperator is missing the .. seealso:: :ref:`howto/operator:CohereRerankOperator` block that CohereEmbeddingOperator carries.
  • Neither test exercises the hook's default model — both pass model= explicitly. Covering the default would likely have surfaced point 1 during authoring.
  • test_rerank.py mocks with a bare MagicMock/patched attribute; the project's testing standards ask for spec/autospec.
  • The operator test covers execute() but not that hook is constructed with the given conn_id / timeout / request_options — that plumbing is currently untested.
  • The example DAG's from airflow import DAG matches the existing example_cohere_embedding_operator.py, so that's pre-existing provider style, not something to change here.

Drafted-by: Claude Code (Opus 5); reviewed by @potiuk before posting

@jeff3071

jeff3071 commented Sep 9, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed review. I’ve addressed the feedback:

  • Changed the default model to rerank-v3.5.
  • Added a configurable model parameter to the operator and pass to hook.
  • Omitted unset optional parameters instead of sending JSON null.
  • Added the missing docstring

@jeff3071
jeff3071 requested a review from potiuk September 9, 2026 03:16
@potiuk
potiuk merged commit fd896f2 into apache:main Sep 9, 2026
80 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants