jeff3071 opened a new pull request, #72501:
URL: https://github.com/apache/airflow/pull/72501
<!-- SPDX-License-Identifier: Apache-2.0
https://www.apache.org/licenses/LICENSE-2.0 -->
<!--
Thank you for contributing!
Please provide above a brief description of the changes made in this pull
request.
Write a good git commit message following this guide:
https://chris.beams.io/posts/git-commit/
Please make sure that your code changes are covered with tests.
And in case of new features or big changes remember to adjust the
documentation.
For user-facing UI changes, please attach before/after screenshots (or a
short
screen recording) so reviewers can assess the visual impact.
Feel free to ping (in general) for the review if you do not see reaction for
a few days
(72 Hours is the minimum reaction time you can expect from volunteers) - we
sometimes miss notifications.
In case of an existing issue, reference it using one of the following:
* closes: #ISSUE
* related: #ISSUE
-->
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).
```python
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?
<!--
If generative AI tooling has been used in the process of authoring this PR,
please
change below checkbox to `[X]` followed by the name of the tool, uncomment
the "Generated-by".
-->
- [x] Yes (GPT 5.6 sol)
Generated-by: [GPT 5.6 sol] following [the
guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#gen-ai-assisted-contributions)
---
* Read the **[Pull Request
Guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#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](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Improvement+Proposals))
is needed.
* When adding dependency, check compliance with the [ASF 3rd Party License
Policy](https://www.apache.org/legal/resolved.html#category-x).
* For significant user-facing changes create newsfragment:
`{pr_number}.significant.rst`, in
[airflow-core/newsfragments](https://github.com/apache/airflow/tree/main/airflow-core/newsfragments).
You can add this file in a follow-up commit after the PR is created so you
know the PR number.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]