Questions when using Rerank of huggingface text-embeddings-inference #5055

Closed
opened 2026-02-21 18:09:10 -05:00 by yindo · 4 comments
Owner

Originally created by @upskyy on GitHub (Aug 15, 2024).

Self Checks

  • This is only for bug report, if you would like to ask a question, please head to Discussions.
  • I have searched for existing issues search for existing issues, including closed ones.
  • I confirm that I am using English to submit this report (我已阅读并同意 Language Policy).
  • [FOR CHINESE USERS] 请务必使用英文提交 Issue,否则会被关闭。谢谢!:)
  • Please do not modify this template :) and fill in all the required fields.

Dify version

0.7.0

Cloud or Self Hosted

Self Hosted (Docker)

Steps to reproduce

I have a question about using rerank of huggingface text-embeddings-inference(TEI).
text-embeddings-inference(TEI) repo uses query(str) and texts(list of str) as arguments when calling the server with curl, and the code uses query and docs.
Is this compatible with text-embeddings-inference server?

https://github.com/langgenius/dify/blob/main/api/core/model_runtime/model_providers/huggingface_tei/rerank/rerank.py#L21-L35

curl 127.0.0.1:8080/rerank \
    -X POST \
    -d '{"query":"What is Deep Learning?", "texts": ["Deep Learning is not...", "Deep learning is..."]}' \
    -H 'Content-Type: application/json'

✔️ Expected Behavior

No response

Actual Behavior

No response

Originally created by @upskyy on GitHub (Aug 15, 2024). ### Self Checks - [X] This is only for bug report, if you would like to ask a question, please head to [Discussions](https://github.com/langgenius/dify/discussions/categories/general). - [X] I have searched for existing issues [search for existing issues](https://github.com/langgenius/dify/issues), including closed ones. - [X] I confirm that I am using English to submit this report (我已阅读并同意 [Language Policy](https://github.com/langgenius/dify/issues/1542)). - [X] [FOR CHINESE USERS] 请务必使用英文提交 Issue,否则会被关闭。谢谢!:) - [X] Please do not modify this template :) and fill in all the required fields. ### Dify version 0.7.0 ### Cloud or Self Hosted Self Hosted (Docker) ### Steps to reproduce I have a question about using **rerank** of huggingface text-embeddings-inference(TEI). [text-embeddings-inference(TEI) repo](https://github.com/huggingface/text-embeddings-inference#using-re-rankers-models) uses `query(str)` and `texts(list of str)` as arguments when calling the server with curl, and the code uses `query` and `docs`. Is this compatible with text-embeddings-inference server? https://github.com/langgenius/dify/blob/main/api/core/model_runtime/model_providers/huggingface_tei/rerank/rerank.py#L21-L35 ```bash curl 127.0.0.1:8080/rerank \ -X POST \ -d '{"query":"What is Deep Learning?", "texts": ["Deep Learning is not...", "Deep learning is..."]}' \ -H 'Content-Type: application/json' ``` ### ✔️ Expected Behavior _No response_ ### ❌ Actual Behavior _No response_
yindo added the 🙋‍♂️ question label 2026-02-21 18:09:10 -05:00
yindo closed this issue 2026-02-21 18:09:10 -05:00
Author
Owner

@dosubot[bot] commented on GitHub (Aug 15, 2024):

Hello @upskyy! I'm here to help you with any bugs or questions you have while using Dify. I can also assist you in becoming a contributor. Let me know how I can assist you today!

Yes, using query and docs as arguments is compatible with the text-embeddings-inference server for the rerank feature in your self-hosted Dify version 0.7.0 setup.

Supporting evidence from the provided code:

@staticmethod
def invoke_rerank(server_url: str, query: str, docs: list[str]) -> list[dict]:
    """
    Invoke rerank endpoint

    Example response:
    [
        {
            "index": 0,
            "text": "Deep Learning is ...",
            "score": 0.9950755
        }
    ]

    :param server_url: server url
    :param texts: texts to rerank
    :param candidates: candidates to rerank
    """
    params = {'query': query, 'texts': docs, 'return_text': True}

    response = httpx.post(
        server_url + '/rerank',
        json=params,
    )
    response.raise_for_status() 
    return response.json()

Additionally, the HuggingfaceTeiRerankModel class in the Dify codebase further confirms this compatibility:

def _invoke(self, model: str, credentials: dict,
            query: str, docs: list[str], score_threshold: Optional[float] = None, top_n: Optional[int] = None,
            user: Optional[str] = None) -> RerankResult:
    """
    Invoke rerank model

    :param model: model name
    :param credentials: model credentials
    :param query: search query
    :param docs: docs for reranking
    :param score_threshold: score threshold
    :param top_n: top n documents to return
    :param user: unique user id
    :return: rerank result
    """
    if len(docs) == 0:
        return RerankResult(model=model, docs=[])

    server_url = credentials['server_url']
    if server_url.endswith('/'):
        server_url = server_url[:-1]

    try:
        results = TeiHelper.invoke_rerank(server_url, query, docs)

        rerank_documents = []
        for result in results:  
            rerank_document = RerankDocument(
                index=result['index'],
                text=result['text'],
                score=result['score'],
            )
            if score_threshold is None or result['score'] >= score_threshold:
                rerank_documents.append(rerank_document)
            if top_n is not None and len(rerank_documents) >= top_n:
                break

        return RerankResult(model=model, docs=rerank_documents)
    except httpx.HTTPStatusError as e:
        raise InvokeServerUnavailableError(str(e))  

The invoke_rerank method and the _invoke method in HuggingfaceTeiRerankModel both show that they accept query and docs as arguments and use them to call the rerank endpoint.

Furthermore, the mock implementation in the integration tests also supports this:

def invoke_rerank(server_url: str, query: str, texts: list[str]) -> list[dict]:
    # Example response:
    # [
    #     {
    #         "index": 0,
    #         "text": "Deep Learning is ...",
    #         "score": 0.9950755
    #     }
    # ]
    reranked_docs = []
    for idx, text in enumerate(texts):
        reranked_docs.append(
            {
                'index': idx,
                'text': text,
                'score': 0.9,
            }
        )
        # For mock, only return the first document
        break
    return reranked_docs

This mock implementation further confirms that query and texts (equivalent to docs) are used as arguments for the rerank feature [1][2][3][4][5].

To continue talking to Dosu, mention @dosu.

@dosubot[bot] commented on GitHub (Aug 15, 2024): <!-- Greeting --> Hello @upskyy! I'm here to help you with any bugs or questions you have while using Dify. I can also assist you in becoming a contributor. Let me know how I can assist you today! <!-- Answer --> Yes, using `query` and `docs` as arguments is compatible with the text-embeddings-inference server for the **rerank** feature in your self-hosted Dify version 0.7.0 setup. Supporting evidence from the provided code: ```python @staticmethod def invoke_rerank(server_url: str, query: str, docs: list[str]) -> list[dict]: """ Invoke rerank endpoint Example response: [ { "index": 0, "text": "Deep Learning is ...", "score": 0.9950755 } ] :param server_url: server url :param texts: texts to rerank :param candidates: candidates to rerank """ params = {'query': query, 'texts': docs, 'return_text': True} response = httpx.post( server_url + '/rerank', json=params, ) response.raise_for_status() return response.json() ``` Additionally, the `HuggingfaceTeiRerankModel` class in the Dify codebase further confirms this compatibility: ```python def _invoke(self, model: str, credentials: dict, query: str, docs: list[str], score_threshold: Optional[float] = None, top_n: Optional[int] = None, user: Optional[str] = None) -> RerankResult: """ Invoke rerank model :param model: model name :param credentials: model credentials :param query: search query :param docs: docs for reranking :param score_threshold: score threshold :param top_n: top n documents to return :param user: unique user id :return: rerank result """ if len(docs) == 0: return RerankResult(model=model, docs=[]) server_url = credentials['server_url'] if server_url.endswith('/'): server_url = server_url[:-1] try: results = TeiHelper.invoke_rerank(server_url, query, docs) rerank_documents = [] for result in results: rerank_document = RerankDocument( index=result['index'], text=result['text'], score=result['score'], ) if score_threshold is None or result['score'] >= score_threshold: rerank_documents.append(rerank_document) if top_n is not None and len(rerank_documents) >= top_n: break return RerankResult(model=model, docs=rerank_documents) except httpx.HTTPStatusError as e: raise InvokeServerUnavailableError(str(e)) ``` The `invoke_rerank` method and the `_invoke` method in `HuggingfaceTeiRerankModel` both show that they accept `query` and `docs` as arguments and use them to call the rerank endpoint. Furthermore, the mock implementation in the integration tests also supports this: ```python def invoke_rerank(server_url: str, query: str, texts: list[str]) -> list[dict]: # Example response: # [ # { # "index": 0, # "text": "Deep Learning is ...", # "score": 0.9950755 # } # ] reranked_docs = [] for idx, text in enumerate(texts): reranked_docs.append( { 'index': idx, 'text': text, 'score': 0.9, } ) # For mock, only return the first document break return reranked_docs ``` This mock implementation further confirms that `query` and `texts` (equivalent to `docs`) are used as arguments for the rerank feature <sup>[[1]](https://github.com/langgenius/dify/blob/main/api/core/model_runtime/model_providers/huggingface_tei/tei_helper.py)</sup><sup>[[2]](https://github.com/langgenius/dify/blob/main/api/core/model_runtime/model_providers/xinference/rerank/rerank.py)</sup><sup>[[3]](https://github.com/langgenius/dify/blob/main/api/core/model_runtime/model_providers/localai/rerank/rerank.py)</sup><sup>[[4]](https://github.com/langgenius/dify/blob/main/api/tests/integration_tests/model_runtime/__mock/huggingface_tei.py)</sup><sup>[[5]](https://github.com/langgenius/dify/blob/main/api/core/model_runtime/model_providers/huggingface_tei/rerank/rerank.py)</sup>. <!-- Dosu Comment Footer --> *To continue talking to [Dosu](https://dosu.dev), mention @dosu.*
Author
Owner

@crazywoola commented on GitHub (Aug 15, 2024):

@liuyanyi Could you take a look at this?

@crazywoola commented on GitHub (Aug 15, 2024): @liuyanyi Could you take a look at this?
Author
Owner

@liuyanyi commented on GitHub (Aug 15, 2024):

Hi, the query and doc in L31~L35 are the parameter names used by the abstract methods in base_rerank_model of dify.

The code that actually calls TEI is located in tei_helper.py, and you can see that the actual request sent in the invoke_rerank method is correct

https://github.com/langgenius/dify/blob/c7df6783dffac516643038ad12633bd6ba45ff3f/api/core/model_runtime/model_providers/huggingface_tei/tei_helper.py#L176

@liuyanyi commented on GitHub (Aug 15, 2024): Hi, the query and doc in L31~L35 are the parameter names used by the abstract methods in base_rerank_model of dify. The code that actually calls TEI is located in tei_helper.py, and you can see that the actual request sent in the invoke_rerank method is correct https://github.com/langgenius/dify/blob/c7df6783dffac516643038ad12633bd6ba45ff3f/api/core/model_runtime/model_providers/huggingface_tei/tei_helper.py#L176
Author
Owner

@upskyy commented on GitHub (Aug 15, 2024):

I have confirmed that TEI works well.
Thank you for checking.

@upskyy commented on GitHub (Aug 15, 2024): I have confirmed that TEI works well. Thank you for checking.
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: langgenius/dify#5055