Source code for langchain_community.llms.cohere

from __future__ import annotations

import logging
from typing import Any, Callable, Dict, List, Optional

from langchain_core._api.deprecation import deprecated
from langchain_core.callbacks import (
    AsyncCallbackManagerForLLMRun,
    CallbackManagerForLLMRun,
)
from langchain_core.language_models.llms import LLM
from langchain_core.load.serializable import Serializable
from langchain_core.pydantic_v1 import Extra, Field, SecretStr, root_validator
from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env
from tenacity import (
    before_sleep_log,
    retry,
    retry_if_exception_type,
    stop_after_attempt,
    wait_exponential,
)

from langchain_community.llms.utils import enforce_stop_tokens

logger = logging.getLogger(__name__)


def _create_retry_decorator(max_retries: int) -> Callable[[Any], Any]:
    import cohere

    # support v4 and v5
    retry_conditions = (
        retry_if_exception_type(cohere.error.CohereError)
        if hasattr(cohere, "error")
        else retry_if_exception_type(Exception)
    )

    min_seconds = 4
    max_seconds = 10
    # Wait 2^x * 1 second between each retry starting with
    # 4 seconds, then up to 10 seconds, then 10 seconds afterwards
    return retry(
        reraise=True,
        stop=stop_after_attempt(max_retries),
        wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds),
        retry=retry_conditions,
        before_sleep=before_sleep_log(logger, logging.WARNING),
    )


[docs]def completion_with_retry(llm: Cohere, **kwargs: Any) -> Any: """使用tenacity来重试完成调用。""" retry_decorator = _create_retry_decorator(llm.max_retries) @retry_decorator def _completion_with_retry(**kwargs: Any) -> Any: return llm.client.generate(**kwargs) return _completion_with_retry(**kwargs)
[docs]def acompletion_with_retry(llm: Cohere, **kwargs: Any) -> Any: """使用tenacity来重试完成调用。""" retry_decorator = _create_retry_decorator(llm.max_retries) @retry_decorator async def _completion_with_retry(**kwargs: Any) -> Any: return await llm.async_client.generate(**kwargs) return _completion_with_retry(**kwargs)
[docs]@deprecated( since="0.0.30", removal="0.3.0", alternative_import="langchain_cohere.BaseCohere" ) class BaseCohere(Serializable): """用于Cohere模型的基类。""" client: Any #: :meta private: async_client: Any #: :meta private: model: Optional[str] = Field(default=None) """要使用的模型名称。""" temperature: float = 0.75 """一个非负浮点数,用于调整生成过程中的随机程度。""" cohere_api_key: Optional[SecretStr] = None """Cohere API密钥。如果未提供,将从环境变量中读取。""" stop: Optional[List[str]] = None streaming: bool = Field(default=False) """是否流式传输结果。""" user_agent: str = "langchain" """用于发出请求的应用程序的标识符。""" @root_validator() def validate_environment(cls, values: Dict) -> Dict: """验证环境中是否存在API密钥和Python包。""" try: import cohere except ImportError: raise ImportError( "Could not import cohere python package. " "Please install it with `pip install cohere`." ) else: values["cohere_api_key"] = convert_to_secret_str( get_from_dict_or_env(values, "cohere_api_key", "COHERE_API_KEY") ) client_name = values["user_agent"] values["client"] = cohere.Client( api_key=values["cohere_api_key"].get_secret_value(), client_name=client_name, ) values["async_client"] = cohere.AsyncClient( api_key=values["cohere_api_key"].get_secret_value(), client_name=client_name, ) return values
[docs]@deprecated( since="0.1.14", removal="0.3.0", alternative_import="langchain_cohere.Cohere" ) class Cohere(LLM, BaseCohere): """连接大型语言模型。 要使用,您应该安装``cohere`` python包,并设置环境变量``COHERE_API_KEY``为您的API密钥,或将其作为命名参数传递给构造函数。 示例: .. code-block:: python from langchain_community.llms import Cohere cohere = Cohere(model="gptd-instruct-tft", cohere_api_key="my-api-key") """ max_tokens: int = 256 """表示每代要预测的令牌数量。""" k: int = 0 """每个步骤考虑的最有可能的令牌数量。""" p: int = 1 """每一步需要考虑的标记的总概率质量。""" frequency_penalty: float = 0.0 """根据频率惩罚重复的标记。取值范围在0到1之间。""" presence_penalty: float = 0.0 """惩罚重复的标记。取值范围在0到1之间。""" truncate: Optional[str] = None """指定客户端如何处理超过最大令牌长度的输入:从开头截断,结尾截断或不截断。""" max_retries: int = 10 """生成时最大的重试次数。""" class Config: """此pydantic对象的配置。""" extra = Extra.forbid @property def _default_params(self) -> Dict[str, Any]: """获取调用Cohere API的默认参数。""" return { "max_tokens": self.max_tokens, "temperature": self.temperature, "k": self.k, "p": self.p, "frequency_penalty": self.frequency_penalty, "presence_penalty": self.presence_penalty, "truncate": self.truncate, } @property def lc_secrets(self) -> Dict[str, str]: return {"cohere_api_key": "COHERE_API_KEY"} @property def _identifying_params(self) -> Dict[str, Any]: """获取识别参数。""" return {**{"model": self.model}, **self._default_params} @property def _llm_type(self) -> str: """llm的返回类型。""" return "cohere" def _invocation_params(self, stop: Optional[List[str]], **kwargs: Any) -> dict: params = self._default_params if self.stop is not None and stop is not None: raise ValueError("`stop` found in both the input and default params.") elif self.stop is not None: params["stop_sequences"] = self.stop else: params["stop_sequences"] = stop return {**params, **kwargs} def _process_response(self, response: Any, stop: Optional[List[str]]) -> str: text = response.generations[0].text # If stop tokens are provided, Cohere's endpoint returns them. # In order to make this consistent with other endpoints, we strip them. if stop: text = enforce_stop_tokens(text, stop) return text def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """调用Cohere的生成端点。 参数: prompt: 传递给模型的提示。 stop: 生成时可选的停止词列表。 返回: 模型生成的字符串。 示例: .. code-block:: python response = cohere("Tell me a joke.") """ params = self._invocation_params(stop, **kwargs) response = completion_with_retry( self, model=self.model, prompt=prompt, **params ) _stop = params.get("stop_sequences") return self._process_response(response, _stop) async def _acall( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """异步调用Cohere的生成端点。 参数: prompt: 传递给模型的提示。 stop: 生成时可选的停止词列表。 返回: 模型生成的字符串。 示例: .. code-block:: python response = await cohere("Tell me a joke.") """ params = self._invocation_params(stop, **kwargs) response = await acompletion_with_retry( self, model=self.model, prompt=prompt, **params ) _stop = params.get("stop_sequences") return self._process_response(response, _stop)