Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 14 additions & 11 deletions providers/cohere/src/airflow/providers/cohere/hooks/cohere.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@

import logging
import warnings
from functools import cached_property
from typing import TYPE_CHECKING, Any

import cohere
Expand Down Expand Up @@ -65,6 +64,7 @@ def __init__(
self.timeout = timeout
self.max_retries = max_retries
self.request_options = request_options
self._client: cohere.ClientV2 | None = None

if self.max_retries:
warnings.warn(
Expand All @@ -77,20 +77,23 @@ def __init__(
else:
self.request_options.update({"max_retries": self.max_retries})

@cached_property
def get_conn(self) -> cohere.ClientV2: # type: ignore[override]
conn = self.get_connection(self.conn_id)
return cohere.ClientV2(
api_key=conn.password,
timeout=self.timeout,
base_url=conn.host or None,
)
def get_conn(self) -> cohere.ClientV2:
"""Return a new or cached Cohere client instance."""
if self._client is None:
# create a new client instance if there is no existing client
conn = self.get_connection(self.conn_id)
self._client = cohere.ClientV2(
api_key=conn.password,
timeout=self.timeout,
base_url=conn.host or None,
)
return self._client

def create_embeddings(
self, texts: list[str], model: str = "embed-multilingual-v3.0"
) -> EmbedByTypeResponseEmbeddings:
logger.info("Creating embeddings with model: embed-multilingual-v3.0")
response = self.get_conn.embed(
response = self.get_conn().embed(
texts=texts,
model=model,
input_type="search_document",
Expand All @@ -117,7 +120,7 @@ def test_connection(
try:
if messages is None:
messages = [UserChatMessageV2(role="user", content="hello world!")]
self.get_conn.chat(model=model, messages=messages)
self.get_conn().chat(model=model, messages=messages)
return True, "Connection successfully established."
except Exception as e:
return False, f"Unexpected error: {str(e)}"
2 changes: 1 addition & 1 deletion providers/cohere/tests/unit/cohere/hooks/test_cohere.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,5 +42,5 @@ def test__get_api_key(self):
patch("cohere.ClientV2") as client,
):
hook = CohereHook(timeout=timeout)
_ = hook.get_conn
_ = hook.get_conn()
client.assert_called_once_with(api_key=api_key, timeout=timeout, base_url=base_url)