|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2023-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | +import asyncio |
| 16 | +from contextvars import ContextVar |
| 17 | +from typing import List |
| 18 | + |
| 19 | +from .base import EmbeddingModel |
| 20 | + |
| 21 | +# We set the Cohere async client in an asyncio context variable because we need it |
| 22 | +# to be scoped at the asyncio loop level. The client caches it somewhere, and if the loop |
| 23 | +# is changed, it will fail. |
| 24 | +async_client_var: ContextVar = ContextVar("async_client", default=None) |
| 25 | + |
| 26 | + |
| 27 | +class CohereEmbeddingModel(EmbeddingModel): |
| 28 | + """ |
| 29 | + Embedding model using Cohere API. |
| 30 | +
|
| 31 | + To use, you must have either: |
| 32 | + 1. The ``COHERE_API_KEY`` environment variable set with your API key, or |
| 33 | + 2. Pass your API key using the api_key kwarg to the Cohere constructor. |
| 34 | +
|
| 35 | + Args: |
| 36 | + embedding_model (str): The name of the embedding model. |
| 37 | + input_type (str): The type of input for the embedding model, default is "search_document". |
| 38 | + "search_document", "search_query", "classification", "clustering", "image" |
| 39 | +
|
| 40 | + Attributes: |
| 41 | + model (str): The name of the embedding model. |
| 42 | + embedding_size (int): The size of the embeddings. |
| 43 | +
|
| 44 | + Methods: |
| 45 | + encode: Encode a list of documents into embeddings. |
| 46 | + """ |
| 47 | + |
| 48 | + engine_name = "cohere" |
| 49 | + |
| 50 | + def __init__( |
| 51 | + self, |
| 52 | + embedding_model: str, |
| 53 | + input_type: str = "search_document", |
| 54 | + **kwargs, |
| 55 | + ): |
| 56 | + try: |
| 57 | + import cohere |
| 58 | + from cohere import AsyncClient, Client |
| 59 | + except ImportError: |
| 60 | + raise ImportError( |
| 61 | + "Could not import cohere, please install it with " |
| 62 | + "`pip install cohere`." |
| 63 | + ) |
| 64 | + |
| 65 | + self.model = embedding_model |
| 66 | + self.input_type = input_type |
| 67 | + self.client = cohere.Client(**kwargs) |
| 68 | + |
| 69 | + self.embedding_size_dict = { |
| 70 | + "embed-v4.0": 1536, |
| 71 | + "embed-english-v3.0": 1024, |
| 72 | + "embed-english-light-v3.0": 384, |
| 73 | + "embed-multilingual-v3.0": 1024, |
| 74 | + "embed-multilingual-light-v3.0": 384, |
| 75 | + } |
| 76 | + |
| 77 | + if self.model in self.embedding_size_dict: |
| 78 | + self.embedding_size = self.embedding_size_dict[self.model] |
| 79 | + else: |
| 80 | + # Perform a first encoding to get the embedding size |
| 81 | + self.embedding_size = len(self.encode(["test"])[0]) |
| 82 | + |
| 83 | + async def encode_async(self, documents: List[str]) -> List[List[float]]: |
| 84 | + """Encode a list of documents into embeddings. |
| 85 | +
|
| 86 | + Args: |
| 87 | + documents (List[str]): The list of documents to be encoded. |
| 88 | +
|
| 89 | + Returns: |
| 90 | + List[List[float]]: The encoded embeddings. |
| 91 | +
|
| 92 | + """ |
| 93 | + loop = asyncio.get_running_loop() |
| 94 | + embeddings = await loop.run_in_executor(None, self.encode, documents) |
| 95 | + |
| 96 | + # NOTE: The async implementation below has some edge cases because of |
| 97 | + # httpx and async and returns "Event loop is closed." errors. Falling back to |
| 98 | + # a thread-based implementation for now. |
| 99 | + |
| 100 | + # # We do lazy initialization of the async client to make sure it's on the correct loop |
| 101 | + # async_client = async_client_var.get() |
| 102 | + # if async_client is None: |
| 103 | + # async_client = AsyncClient() |
| 104 | + # async_client_var.set(async_client) |
| 105 | + # |
| 106 | + # # Make embedding request to Cohere API |
| 107 | + # embeddings = await async_client.embed(texts=documents, model=self.model, input_type=self.input_type).embeddings |
| 108 | + |
| 109 | + return embeddings |
| 110 | + |
| 111 | + def encode(self, documents: List[str]) -> List[List[float]]: |
| 112 | + """Encode a list of documents into embeddings. |
| 113 | +
|
| 114 | + Args: |
| 115 | + documents (List[str]): The list of documents to be encoded. |
| 116 | +
|
| 117 | + Returns: |
| 118 | + List[List[float]]: The encoded embeddings. |
| 119 | +
|
| 120 | + """ |
| 121 | + |
| 122 | + # Make embedding request to Cohere API |
| 123 | + return self.client.embed( |
| 124 | + texts=documents, model=self.model, input_type=self.input_type |
| 125 | + ).embeddings |
0 commit comments