-
Notifications
You must be signed in to change notification settings - Fork 530
feat: add Cohere embedding integration #1305
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
bwook00
wants to merge
8
commits into
NVIDIA:develop
Choose a base branch
from
bwook00:feature/cohere-embedding
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
3fa3a4d
add cohere embedding provider
bwook00 3063df5
add annotation about setting api_key
bwook00 dd62471
add configuration-guide.md
bwook00 b1539a4
add cohere at provider's init
bwook00 825f916
add test code
bwook00 cae3b91
add blank line
bwook00 4605eca
run pre-commit
bwook00 025c4f7
Merge branch 'develop' into feature/cohere-embedding
bwook00 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,125 @@ | ||
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
# SPDX-License-Identifier: Apache-2.0 | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
import asyncio | ||
from contextvars import ContextVar | ||
from typing import List | ||
|
||
from .base import EmbeddingModel | ||
|
||
# We set the Cohere async client in an asyncio context variable because we need it | ||
# to be scoped at the asyncio loop level. The client caches it somewhere, and if the loop | ||
# is changed, it will fail. | ||
async_client_var: ContextVar = ContextVar("async_client", default=None) | ||
|
||
|
||
class CohereEmbeddingModel(EmbeddingModel): | ||
""" | ||
Embedding model using Cohere API. | ||
|
||
To use, you must have either: | ||
1. The ``COHERE_API_KEY`` environment variable set with your API key, or | ||
2. Pass your API key using the api_key kwarg to the Cohere constructor. | ||
|
||
Args: | ||
embedding_model (str): The name of the embedding model. | ||
input_type (str): The type of input for the embedding model, default is "search_document". | ||
"search_document", "search_query", "classification", "clustering", "image" | ||
|
||
Attributes: | ||
model (str): The name of the embedding model. | ||
embedding_size (int): The size of the embeddings. | ||
|
||
Methods: | ||
encode: Encode a list of documents into embeddings. | ||
""" | ||
|
||
engine_name = "cohere" | ||
|
||
def __init__( | ||
self, | ||
embedding_model: str, | ||
input_type: str = "search_document", | ||
**kwargs, | ||
): | ||
try: | ||
import cohere | ||
from cohere import AsyncClient, Client | ||
except ImportError: | ||
raise ImportError( | ||
"Could not import cohere, please install it with " | ||
"`pip install cohere`." | ||
) | ||
|
||
self.model = embedding_model | ||
self.input_type = input_type | ||
self.client = cohere.Client(**kwargs) | ||
|
||
self.embedding_size_dict = { | ||
"embed-v4.0": 1536, | ||
"embed-english-v3.0": 1024, | ||
"embed-english-light-v3.0": 384, | ||
"embed-multilingual-v3.0": 1024, | ||
"embed-multilingual-light-v3.0": 384, | ||
} | ||
|
||
if self.model in self.embedding_size_dict: | ||
self.embedding_size = self.embedding_size_dict[self.model] | ||
else: | ||
# Perform a first encoding to get the embedding size | ||
self.embedding_size = len(self.encode(["test"])[0]) | ||
|
||
async def encode_async(self, documents: List[str]) -> List[List[float]]: | ||
"""Encode a list of documents into embeddings. | ||
|
||
Args: | ||
documents (List[str]): The list of documents to be encoded. | ||
|
||
Returns: | ||
List[List[float]]: The encoded embeddings. | ||
|
||
""" | ||
loop = asyncio.get_running_loop() | ||
embeddings = await loop.run_in_executor(None, self.encode, documents) | ||
|
||
# NOTE: The async implementation below has some edge cases because of | ||
# httpx and async and returns "Event loop is closed." errors. Falling back to | ||
# a thread-based implementation for now. | ||
|
||
# # We do lazy initialization of the async client to make sure it's on the correct loop | ||
# async_client = async_client_var.get() | ||
# if async_client is None: | ||
# async_client = AsyncClient() | ||
# async_client_var.set(async_client) | ||
# | ||
# # Make embedding request to Cohere API | ||
# embeddings = await async_client.embed(texts=documents, model=self.model, input_type=self.input_type).embeddings | ||
|
||
return embeddings | ||
|
||
def encode(self, documents: List[str]) -> List[List[float]]: | ||
"""Encode a list of documents into embeddings. | ||
|
||
Args: | ||
documents (List[str]): The list of documents to be encoded. | ||
|
||
Returns: | ||
List[List[float]]: The encoded embeddings. | ||
|
||
""" | ||
|
||
# Make embedding request to Cohere API | ||
return self.client.embed( | ||
texts=documents, model=self.model, input_type=self.input_type | ||
).embeddings |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
define user ask capabilities | ||
"What can you do?" | ||
"What can you help me with?" | ||
"tell me what you can do" | ||
"tell me about you" | ||
|
||
define bot inform capabilities | ||
"I am an AI assistant that helps answer questions." | ||
|
||
define flow | ||
user ask capabilities | ||
bot inform capabilities |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
models: | ||
- type: main | ||
engine: openai | ||
model: gpt-3.5-turbo-instruct | ||
|
||
- type: embeddings | ||
engine: cohere | ||
model: embed-multilingual-v3.0 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,97 @@ | ||
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
# SPDX-License-Identifier: Apache-2.0 | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
import os | ||
|
||
import pytest | ||
|
||
from nemoguardrails import LLMRails, RailsConfig | ||
|
||
try: | ||
from nemoguardrails.embeddings.providers.cohere import CohereEmbeddingModel | ||
except ImportError: | ||
# Ignore this if running in test environment when cohere not installed. | ||
CohereEmbeddingModel = None | ||
|
||
CONFIGS_FOLDER = os.path.join(os.path.dirname(__file__), ".", "test_configs") | ||
|
||
LIVE_TEST_MODE = os.environ.get("LIVE_TEST") | ||
|
||
|
||
@pytest.fixture | ||
def app(): | ||
"""Load the configuration where we replace FastEmbed with Cohere.""" | ||
config = RailsConfig.from_path( | ||
os.path.join(CONFIGS_FOLDER, "with_cohere_embeddings") | ||
) | ||
|
||
return LLMRails(config) | ||
|
||
|
||
@pytest.mark.skipif(not LIVE_TEST_MODE, reason="Not in live mode.") | ||
def test_custom_llm_registration(app): | ||
assert isinstance( | ||
app.llm_generation_actions.flows_index._model, CohereEmbeddingModel | ||
) | ||
|
||
|
||
@pytest.mark.skipif(not LIVE_TEST_MODE, reason="Not in live mode.") | ||
@pytest.mark.asyncio | ||
async def test_live_query(): | ||
config = RailsConfig.from_path( | ||
os.path.join(CONFIGS_FOLDER, "with_cohere_embeddings") | ||
) | ||
app = LLMRails(config) | ||
|
||
result = await app.generate_async( | ||
messages=[{"role": "user", "content": "tell me what you can do"}] | ||
) | ||
|
||
assert result == { | ||
"role": "assistant", | ||
"content": "I am an AI assistant that helps answer questions.", | ||
} | ||
|
||
|
||
@pytest.mark.skipif(not LIVE_TEST_MODE, reason="Not in live mode.") | ||
@pytest.mark.asyncio | ||
def test_live_query(app): | ||
result = app.generate( | ||
messages=[{"role": "user", "content": "tell me what you can do"}] | ||
) | ||
|
||
assert result == { | ||
"role": "assistant", | ||
"content": "I am an AI assistant that helps answer questions.", | ||
} | ||
|
||
|
||
@pytest.mark.skipif(not LIVE_TEST_MODE, reason="Not in live mode.") | ||
def test_sync_embeddings(): | ||
model = CohereEmbeddingModel("embed-multilingual-v3.0") | ||
|
||
result = model.encode(["test"]) | ||
|
||
assert len(result[0]) == 1024 | ||
|
||
|
||
@pytest.mark.skipif(not LIVE_TEST_MODE, reason="Not in live mode.") | ||
@pytest.mark.asyncio | ||
async def test_async_embeddings(): | ||
model = CohereEmbeddingModel("embed-multilingual-v3.0") | ||
|
||
result = await model.encode_async(["test"]) | ||
|
||
assert len(result[0]) == 1024 |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.