Source code for langchain_community.llms.pipelineai

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

from langchain_core.callbacks import CallbackManagerForLLMRun
from langchain_core.language_models.llms import LLM
from langchain_core.pydantic_v1 import (
    BaseModel,
    Extra,
    Field,
    SecretStr,
    root_validator,
)
from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env

from langchain_community.llms.utils import enforce_stop_tokens

logger = logging.getLogger(__name__)


[docs]class PipelineAI(LLM, BaseModel): """PipelineAI大型语言模型。 要使用,您应该已安装``pipeline-ai`` python包,并设置环境变量``PIPELINE_API_KEY``为您的API密钥。 可以传递给调用的任何有效参数都可以传递,即使在此类上没有明确保存。 示例: .. code-block:: python from langchain_community.llms import PipelineAI pipeline = PipelineAI(pipeline_key="") """ pipeline_key: str = "" """目标管道的ID或标签""" pipeline_kwargs: Dict[str, Any] = Field(default_factory=dict) """保存任何管道参数,适用于“create”调用,未明确指定的参数。""" pipeline_api_key: Optional[SecretStr] = None class Config: """这是用于pydantic配置的设置。""" extra = Extra.forbid @root_validator(pre=True) def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]: """从传入的额外参数构建额外的kwargs。""" all_required_field_names = {field.alias for field in cls.__fields__.values()} extra = values.get("pipeline_kwargs", {}) for field_name in list(values): if field_name not in all_required_field_names: if field_name in extra: raise ValueError(f"Found {field_name} supplied twice.") logger.warning( f"""{field_name} was transferred to pipeline_kwargs. Please confirm that {field_name} is what you intended.""" ) extra[field_name] = values.pop(field_name) values["pipeline_kwargs"] = extra return values @root_validator() def validate_environment(cls, values: Dict) -> Dict: """验证环境中是否存在API密钥和Python包。""" pipeline_api_key = convert_to_secret_str( get_from_dict_or_env(values, "pipeline_api_key", "PIPELINE_API_KEY") ) values["pipeline_api_key"] = pipeline_api_key return values @property def _identifying_params(self) -> Mapping[str, Any]: """获取识别参数。""" return { **{"pipeline_key": self.pipeline_key}, **{"pipeline_kwargs": self.pipeline_kwargs}, } @property def _llm_type(self) -> str: """llm的返回类型。""" return "pipeline_ai" def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """调用Pipeline Cloud端点。""" try: from pipeline import PipelineCloud except ImportError: raise ImportError( "Could not import pipeline-ai python package. " "Please install it with `pip install pipeline-ai`." ) client = PipelineCloud(token=self.pipeline_api_key.get_secret_value()) # type: ignore[union-attr] params = self.pipeline_kwargs or {} params = {**params, **kwargs} run = client.run_pipeline(self.pipeline_key, [prompt, params]) try: text = run.result_preview[0][0] except AttributeError: raise AttributeError( f"A pipeline run should have a `result_preview` attribute." f"Run was: {run}" ) if stop is not None: # I believe this is required since the stop tokens # are not enforced by the pipeline parameters text = enforce_stop_tokens(text, stop) return text