id
stringlengths
14
16
text
stringlengths
13
2.7k
source
stringlengths
57
178
463f176f76a2-4
return "vertexai" @property def is_codey_model(self) -> bool: return is_codey_model(self.model_name) @property def _identifying_params(self) -> Dict[str, Any]: """Get the identifying parameters.""" return {**{"model_name": self.model_name}, **self._default_params} @property def _default_params(self) -> Dict[str, Any]: if self.is_codey_model: return { "temperature": self.temperature, "max_output_tokens": self.max_output_tokens, } else: return { "temperature": self.temperature, "max_output_tokens": self.max_output_tokens, "top_k": self.top_k, "top_p": self.top_p, "candidate_count": self.n, } @classmethod def _try_init_vertexai(cls, values: Dict) -> None: allowed_params = ["project", "location", "credentials"] params = {k: v for k, v in values.items() if k in allowed_params} init_vertexai(**params) return None def _prepare_params( self, stop: Optional[List[str]] = None, stream: bool = False, **kwargs: Any, ) -> dict: stop_sequences = stop or self.stop params_mapping = {"n": "candidate_count"} params = {params_mapping.get(k, k): v for k, v in kwargs.items()} params = {**self._default_params, "stop_sequences": stop_sequences, **params} if stream or self.streaming: params.pop("candidate_count") return params
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html
463f176f76a2-5
if stream or self.streaming: params.pop("candidate_count") return params [docs]class VertexAI(_VertexAICommon, BaseLLM): """Google Vertex AI large language models.""" model_name: str = "text-bison" "The name of the Vertex AI large language model." tuned_model_name: Optional[str] = None "The name of a tuned model. If provided, model_name is ignored." [docs] @classmethod def is_lc_serializable(self) -> bool: return True @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that the python package exists in environment.""" cls._try_init_vertexai(values) tuned_model_name = values.get("tuned_model_name") model_name = values["model_name"] try: if not is_codey_model(model_name): from vertexai.preview.language_models import TextGenerationModel if tuned_model_name: values["client"] = TextGenerationModel.get_tuned_model( tuned_model_name ) else: values["client"] = TextGenerationModel.from_pretrained(model_name) else: from vertexai.preview.language_models import CodeGenerationModel if tuned_model_name: values["client"] = CodeGenerationModel.get_tuned_model( tuned_model_name ) else: values["client"] = CodeGenerationModel.from_pretrained(model_name) except ImportError: raise_vertex_import_error() if values["streaming"] and values["n"] > 1: raise ValueError("Only one candidate can be generated with streaming!") return values [docs] def get_num_tokens(self, text: str) -> int:
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html
463f176f76a2-6
[docs] def get_num_tokens(self, text: str) -> int: """Get the number of tokens present in the text. Useful for checking if an input will fit in a model's context window. Args: text: The string input to tokenize. Returns: The integer number of tokens in the text. """ try: result = self.client.count_tokens(text) except AttributeError: raise NotImplementedError( "Your google-cloud-aiplatform version didn't implement count_tokens." "Please, install it with pip install google-cloud-aiplatform>=1.35.0" ) return result.total_tokens def _generate( self, prompts: List[str], stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, stream: Optional[bool] = None, **kwargs: Any, ) -> LLMResult: should_stream = stream if stream is not None else self.streaming params = self._prepare_params(stop=stop, stream=should_stream, **kwargs) generations = [] for prompt in prompts: if should_stream: generation = GenerationChunk(text="") for chunk in self._stream( prompt, stop=stop, run_manager=run_manager, **kwargs ): generation += chunk generations.append([generation]) else: res = completion_with_retry( self, prompt, run_manager=run_manager, **params ) if self.is_codey_model: generations.append([_response_to_generation(res)]) else: generations.append( [_response_to_generation(r) for r in res.candidates] )
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html
463f176f76a2-7
[_response_to_generation(r) for r in res.candidates] ) return LLMResult(generations=generations) async def _agenerate( self, prompts: List[str], stop: Optional[List[str]] = None, run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, **kwargs: Any, ) -> LLMResult: params = self._prepare_params(stop=stop, **kwargs) generations = [] for prompt in prompts: res = await acompletion_with_retry( self, prompt, run_manager=run_manager, **params ) generations.append([_response_to_generation(r) for r in res.candidates]) return LLMResult(generations=generations) def _stream( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> Iterator[GenerationChunk]: params = self._prepare_params(stop=stop, stream=True, **kwargs) for stream_resp in stream_completion_with_retry( self, prompt, run_manager=run_manager, **params ): chunk = _response_to_generation(stream_resp) yield chunk if run_manager: run_manager.on_llm_new_token( chunk.text, chunk=chunk, verbose=self.verbose, ) [docs]class VertexAIModelGarden(_VertexAIBase, BaseLLM): """Large language models served from Vertex AI Model Garden.""" client: "PredictionServiceClient" = None #: :meta private:
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html
463f176f76a2-8
client: "PredictionServiceClient" = None #: :meta private: async_client: "PredictionServiceAsyncClient" = None #: :meta private: endpoint_id: str "A name of an endpoint where the model has been deployed." allowed_model_args: Optional[List[str]] = None """Allowed optional args to be passed to the model.""" prompt_arg: str = "prompt" result_arg: str = "generated_text" @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that the python package exists in environment.""" try: from google.api_core.client_options import ClientOptions from google.cloud.aiplatform.gapic import ( PredictionServiceAsyncClient, PredictionServiceClient, ) except ImportError: raise_vertex_import_error() if values["project"] is None: raise ValueError( "A GCP project should be provided to run inference on Model Garden!" ) client_options = ClientOptions( api_endpoint=f"{values['location']}-aiplatform.googleapis.com" ) client_info = get_client_info(module="vertex-ai-model-garden") values["client"] = PredictionServiceClient( client_options=client_options, client_info=client_info ) values["async_client"] = PredictionServiceAsyncClient( client_options=client_options, client_info=client_info ) return values @property def _llm_type(self) -> str: return "vertexai_model_garden" def _generate( self, prompts: List[str], stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None,
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html
463f176f76a2-9
run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> LLMResult: """Run the LLM on the given prompt and input.""" try: from google.protobuf import json_format from google.protobuf.struct_pb2 import Value except ImportError: raise ImportError( "protobuf package not found, please install it with" " `pip install protobuf`" ) instances = [] for prompt in prompts: if self.allowed_model_args: instance = { k: v for k, v in kwargs.items() if k in self.allowed_model_args } else: instance = {} instance[self.prompt_arg] = prompt instances.append(instance) predict_instances = [ json_format.ParseDict(instance_dict, Value()) for instance_dict in instances ] endpoint = self.client.endpoint_path( project=self.project, location=self.location, endpoint=self.endpoint_id ) response = self.client.predict(endpoint=endpoint, instances=predict_instances) generations: List[List[Generation]] = [] for result in response.predictions: generations.append( [Generation(text=prediction[self.result_arg]) for prediction in result] ) return LLMResult(generations=generations) async def _agenerate( self, prompts: List[str], stop: Optional[List[str]] = None, run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, **kwargs: Any, ) -> LLMResult: """Run the LLM on the given prompt and input.""" try: from google.protobuf import json_format from google.protobuf.struct_pb2 import Value
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html
463f176f76a2-10
from google.protobuf import json_format from google.protobuf.struct_pb2 import Value except ImportError: raise ImportError( "protobuf package not found, please install it with" " `pip install protobuf`" ) instances = [] for prompt in prompts: if self.allowed_model_args: instance = { k: v for k, v in kwargs.items() if k in self.allowed_model_args } else: instance = {} instance[self.prompt_arg] = prompt instances.append(instance) predict_instances = [ json_format.ParseDict(instance_dict, Value()) for instance_dict in instances ] endpoint = self.async_client.endpoint_path( project=self.project, location=self.location, endpoint=self.endpoint_id ) response = await self.async_client.predict( endpoint=endpoint, instances=predict_instances ) generations: List[List[Generation]] = [] for result in response.predictions: generations.append( [Generation(text=prediction[self.result_arg]) for prediction in result] ) return LLMResult(generations=generations)
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html
c29bb7e5a646-0
Source code for langchain.llms.google_palm from __future__ import annotations import logging from typing import Any, Callable, Dict, List, Optional from tenacity import ( before_sleep_log, retry, retry_if_exception_type, stop_after_attempt, wait_exponential, ) from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms import BaseLLM from langchain.pydantic_v1 import BaseModel, root_validator from langchain.schema import Generation, LLMResult from langchain.utils import get_from_dict_or_env logger = logging.getLogger(__name__) def _create_retry_decorator() -> Callable[[Any], Any]: """Returns a tenacity retry decorator, preconfigured to handle PaLM exceptions""" try: import google.api_core.exceptions except ImportError: raise ImportError( "Could not import google-api-core python package. " "Please install it with `pip install google-api-core`." ) multiplier = 2 min_seconds = 1 max_seconds = 60 max_retries = 10 return retry( reraise=True, stop=stop_after_attempt(max_retries), wait=wait_exponential(multiplier=multiplier, min=min_seconds, max=max_seconds), retry=( retry_if_exception_type(google.api_core.exceptions.ResourceExhausted) | retry_if_exception_type(google.api_core.exceptions.ServiceUnavailable) | retry_if_exception_type(google.api_core.exceptions.GoogleAPIError) ), before_sleep=before_sleep_log(logger, logging.WARNING), ) [docs]def generate_with_retry(llm: GooglePalm, **kwargs: Any) -> Any: """Use tenacity to retry the completion call."""
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html
c29bb7e5a646-1
"""Use tenacity to retry the completion call.""" retry_decorator = _create_retry_decorator() @retry_decorator def _generate_with_retry(**kwargs: Any) -> Any: return llm.client.generate_text(**kwargs) return _generate_with_retry(**kwargs) def _strip_erroneous_leading_spaces(text: str) -> str: """Strip erroneous leading spaces from text. The PaLM API will sometimes erroneously return a single leading space in all lines > 1. This function strips that space. """ has_leading_space = all(not line or line[0] == " " for line in text.split("\n")[1:]) if has_leading_space: return text.replace("\n ", "\n") else: return text [docs]class GooglePalm(BaseLLM, BaseModel): """Google PaLM models.""" client: Any #: :meta private: google_api_key: Optional[str] model_name: str = "models/text-bison-001" """Model name to use.""" temperature: float = 0.7 """Run inference with this temperature. Must by in the closed interval [0.0, 1.0].""" top_p: Optional[float] = None """Decode using nucleus sampling: consider the smallest set of tokens whose probability sum is at least top_p. Must be in the closed interval [0.0, 1.0].""" top_k: Optional[int] = None """Decode using top-k sampling: consider the set of top_k most probable tokens. Must be positive.""" max_output_tokens: Optional[int] = None """Maximum number of tokens to include in a candidate. Must be greater than zero.
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html
c29bb7e5a646-2
"""Maximum number of tokens to include in a candidate. Must be greater than zero. If unset, will default to 64.""" n: int = 1 """Number of chat completions to generate for each prompt. Note that the API may not return the full n completions if duplicates are generated.""" @property def lc_secrets(self) -> Dict[str, str]: return {"google_api_key": "GOOGLE_API_KEY"} [docs] @classmethod def is_lc_serializable(self) -> bool: return True @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate api key, python package exists.""" google_api_key = get_from_dict_or_env( values, "google_api_key", "GOOGLE_API_KEY" ) try: import google.generativeai as genai genai.configure(api_key=google_api_key) except ImportError: raise ImportError( "Could not import google-generativeai python package. " "Please install it with `pip install google-generativeai`." ) values["client"] = genai if values["temperature"] is not None and not 0 <= values["temperature"] <= 1: raise ValueError("temperature must be in the range [0.0, 1.0]") if values["top_p"] is not None and not 0 <= values["top_p"] <= 1: raise ValueError("top_p must be in the range [0.0, 1.0]") if values["top_k"] is not None and values["top_k"] <= 0: raise ValueError("top_k must be positive")
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html
c29bb7e5a646-3
raise ValueError("top_k must be positive") if values["max_output_tokens"] is not None and values["max_output_tokens"] <= 0: raise ValueError("max_output_tokens must be greater than zero") return values def _generate( self, prompts: List[str], stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> LLMResult: generations = [] for prompt in prompts: completion = generate_with_retry( self, model=self.model_name, prompt=prompt, stop_sequences=stop, temperature=self.temperature, top_p=self.top_p, top_k=self.top_k, max_output_tokens=self.max_output_tokens, candidate_count=self.n, **kwargs, ) prompt_generations = [] for candidate in completion.candidates: raw_text = candidate["output"] stripped_text = _strip_erroneous_leading_spaces(raw_text) prompt_generations.append(Generation(text=stripped_text)) generations.append(prompt_generations) return LLMResult(generations=generations) @property def _llm_type(self) -> str: """Return type of llm.""" return "google_palm"
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html
9a65ddc07570-0
Source code for langchain.llms.beam import base64 import json import logging import subprocess import textwrap import time from typing import Any, Dict, List, Mapping, Optional import requests from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.pydantic_v1 import Extra, Field, root_validator from langchain.utils import get_from_dict_or_env logger = logging.getLogger(__name__) DEFAULT_NUM_TRIES = 10 DEFAULT_SLEEP_TIME = 4 [docs]class Beam(LLM): """Beam API for gpt2 large language model. To use, you should have the ``beam-sdk`` python package installed, and the environment variable ``BEAM_CLIENT_ID`` set with your client id and ``BEAM_CLIENT_SECRET`` set with your client secret. Information on how to get this is available here: https://docs.beam.cloud/account/api-keys. The wrapper can then be called as follows, where the name, cpu, memory, gpu, python version, and python packages can be updated accordingly. Once deployed, the instance can be called. Example: .. code-block:: python llm = Beam(model_name="gpt2", name="langchain-gpt2", cpu=8, memory="32Gi", gpu="A10G", python_version="python3.8", python_packages=[ "diffusers[torch]>=0.10", "transformers", "torch", "pillow", "accelerate", "safetensors", "xformers",], max_length=50) llm._deploy()
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/beam.html
9a65ddc07570-1
max_length=50) llm._deploy() call_result = llm._call(input) """ model_name: str = "" name: str = "" cpu: str = "" memory: str = "" gpu: str = "" python_version: str = "" python_packages: List[str] = [] max_length: str = "" url: str = "" """model endpoint to use""" model_kwargs: Dict[str, Any] = Field(default_factory=dict) """Holds any model parameters valid for `create` call not explicitly specified.""" beam_client_id: str = "" beam_client_secret: str = "" app_id: Optional[str] = None class Config: """Configuration for this pydantic config.""" extra = Extra.forbid @root_validator(pre=True) def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]: """Build extra kwargs from additional params that were passed in.""" all_required_field_names = {field.alias for field in cls.__fields__.values()} extra = values.get("model_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 model_kwargs. Please confirm that {field_name} is what you intended.""" ) extra[field_name] = values.pop(field_name) values["model_kwargs"] = extra return values @root_validator() def validate_environment(cls, values: Dict) -> Dict:
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/beam.html
9a65ddc07570-2
@root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" beam_client_id = get_from_dict_or_env( values, "beam_client_id", "BEAM_CLIENT_ID" ) beam_client_secret = get_from_dict_or_env( values, "beam_client_secret", "BEAM_CLIENT_SECRET" ) values["beam_client_id"] = beam_client_id values["beam_client_secret"] = beam_client_secret return values @property def _identifying_params(self) -> Mapping[str, Any]: """Get the identifying parameters.""" return { "model_name": self.model_name, "name": self.name, "cpu": self.cpu, "memory": self.memory, "gpu": self.gpu, "python_version": self.python_version, "python_packages": self.python_packages, "max_length": self.max_length, "model_kwargs": self.model_kwargs, } @property def _llm_type(self) -> str: """Return type of llm.""" return "beam" [docs] def app_creation(self) -> None: """Creates a Python file which will contain your Beam app definition.""" script = textwrap.dedent( """\ import beam # The environment your code will run on app = beam.App( name="{name}", cpu={cpu}, memory="{memory}", gpu="{gpu}", python_version="{python_version}", python_packages={python_packages}, ) app.Trigger.RestAPI(
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/beam.html
9a65ddc07570-3
python_packages={python_packages}, ) app.Trigger.RestAPI( inputs={{"prompt": beam.Types.String(), "max_length": beam.Types.String()}}, outputs={{"text": beam.Types.String()}}, handler="run.py:beam_langchain", ) """ ) script_name = "app.py" with open(script_name, "w") as file: file.write( script.format( name=self.name, cpu=self.cpu, memory=self.memory, gpu=self.gpu, python_version=self.python_version, python_packages=self.python_packages, ) ) [docs] def run_creation(self) -> None: """Creates a Python file which will be deployed on beam.""" script = textwrap.dedent( """ import os import transformers from transformers import GPT2LMHeadModel, GPT2Tokenizer model_name = "{model_name}" def beam_langchain(**inputs): prompt = inputs["prompt"] length = inputs["max_length"] tokenizer = GPT2Tokenizer.from_pretrained(model_name) model = GPT2LMHeadModel.from_pretrained(model_name) encodedPrompt = tokenizer.encode(prompt, return_tensors='pt') outputs = model.generate(encodedPrompt, max_length=int(length), do_sample=True, pad_token_id=tokenizer.eos_token_id) output = tokenizer.decode(outputs[0], skip_special_tokens=True) print(output) return {{"text": output}} """ ) script_name = "run.py" with open(script_name, "w") as file: file.write(script.format(model_name=self.model_name))
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/beam.html
9a65ddc07570-4
file.write(script.format(model_name=self.model_name)) def _deploy(self) -> str: """Call to Beam.""" try: import beam # type: ignore if beam.__path__ == "": raise ImportError except ImportError: raise ImportError( "Could not import beam python package. " "Please install it with `curl " "https://raw.githubusercontent.com/slai-labs" "/get-beam/main/get-beam.sh -sSfL | sh`." ) self.app_creation() self.run_creation() process = subprocess.run( "beam deploy app.py", shell=True, capture_output=True, text=True ) if process.returncode == 0: output = process.stdout logger.info(output) lines = output.split("\n") for line in lines: if line.startswith(" i Send requests to: https://apps.beam.cloud/"): self.app_id = line.split("/")[-1] self.url = line.split(":")[1].strip() return self.app_id raise ValueError( f"""Failed to retrieve the appID from the deployment output. Deployment output: {output}""" ) else: raise ValueError(f"Deployment failed. Error: {process.stderr}") @property def authorization(self) -> str: if self.beam_client_id: credential_str = self.beam_client_id + ":" + self.beam_client_secret else: credential_str = self.beam_client_secret return base64.b64encode(credential_str.encode()).decode() def _call( self, prompt: str, stop: Optional[list] = None,
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/beam.html
9a65ddc07570-5
self, prompt: str, stop: Optional[list] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Call to Beam.""" url = "https://apps.beam.cloud/" + self.app_id if self.app_id else self.url payload = {"prompt": prompt, "max_length": self.max_length} payload.update(kwargs) headers = { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Authorization": "Basic " + self.authorization, "Connection": "keep-alive", "Content-Type": "application/json", } for _ in range(DEFAULT_NUM_TRIES): request = requests.post(url, headers=headers, data=json.dumps(payload)) if request.status_code == 200: return request.json()["text"] time.sleep(DEFAULT_SLEEP_TIME) logger.warning("Unable to successfully call model.") return ""
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/beam.html
5c29157effa5-0
Source code for langchain.llms.anthropic import re import warnings from typing import ( Any, AsyncIterator, Callable, Dict, Iterator, List, Mapping, Optional, ) from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun, ) from langchain.llms.base import LLM from langchain.pydantic_v1 import Field, SecretStr, root_validator from langchain.schema.language_model import BaseLanguageModel from langchain.schema.output import GenerationChunk from langchain.schema.prompt import PromptValue from langchain.utils import ( check_package_version, get_from_dict_or_env, get_pydantic_field_names, ) from langchain.utils.utils import build_extra_kwargs, convert_to_secret_str class _AnthropicCommon(BaseLanguageModel): client: Any = None #: :meta private: async_client: Any = None #: :meta private: model: str = Field(default="claude-2", alias="model_name") """Model name to use.""" max_tokens_to_sample: int = Field(default=256, alias="max_tokens") """Denotes the number of tokens to predict per generation.""" temperature: Optional[float] = None """A non-negative float that tunes the degree of randomness in generation.""" top_k: Optional[int] = None """Number of most likely tokens to consider at each step.""" top_p: Optional[float] = None """Total probability mass of tokens to consider at each step.""" streaming: bool = False """Whether to stream the results.""" default_request_timeout: Optional[float] = None
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
5c29157effa5-1
"""Whether to stream the results.""" default_request_timeout: Optional[float] = None """Timeout for requests to Anthropic Completion API. Default is 600 seconds.""" anthropic_api_url: Optional[str] = None anthropic_api_key: Optional[SecretStr] = None HUMAN_PROMPT: Optional[str] = None AI_PROMPT: Optional[str] = None count_tokens: Optional[Callable[[str], int]] = None model_kwargs: Dict[str, Any] = Field(default_factory=dict) @root_validator(pre=True) def build_extra(cls, values: Dict) -> Dict: extra = values.get("model_kwargs", {}) all_required_field_names = get_pydantic_field_names(cls) values["model_kwargs"] = build_extra_kwargs( extra, values, all_required_field_names ) return values @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" values["anthropic_api_key"] = convert_to_secret_str( get_from_dict_or_env(values, "anthropic_api_key", "ANTHROPIC_API_KEY") ) # Get custom api url from environment. values["anthropic_api_url"] = get_from_dict_or_env( values, "anthropic_api_url", "ANTHROPIC_API_URL", default="https://api.anthropic.com", ) try: import anthropic check_package_version("anthropic", gte_version="0.3") values["client"] = anthropic.Anthropic( base_url=values["anthropic_api_url"], api_key=values["anthropic_api_key"].get_secret_value(),
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
5c29157effa5-2
api_key=values["anthropic_api_key"].get_secret_value(), timeout=values["default_request_timeout"], ) values["async_client"] = anthropic.AsyncAnthropic( base_url=values["anthropic_api_url"], api_key=values["anthropic_api_key"].get_secret_value(), timeout=values["default_request_timeout"], ) values["HUMAN_PROMPT"] = anthropic.HUMAN_PROMPT values["AI_PROMPT"] = anthropic.AI_PROMPT values["count_tokens"] = values["client"].count_tokens except ImportError: raise ImportError( "Could not import anthropic python package. " "Please it install it with `pip install anthropic`." ) return values @property def _default_params(self) -> Mapping[str, Any]: """Get the default parameters for calling Anthropic API.""" d = { "max_tokens_to_sample": self.max_tokens_to_sample, "model": self.model, } if self.temperature is not None: d["temperature"] = self.temperature if self.top_k is not None: d["top_k"] = self.top_k if self.top_p is not None: d["top_p"] = self.top_p return {**d, **self.model_kwargs} @property def _identifying_params(self) -> Mapping[str, Any]: """Get the identifying parameters.""" return {**{}, **self._default_params} def _get_anthropic_stop(self, stop: Optional[List[str]] = None) -> List[str]: if not self.HUMAN_PROMPT or not self.AI_PROMPT: raise NameError("Please ensure the anthropic package is loaded")
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
5c29157effa5-3
raise NameError("Please ensure the anthropic package is loaded") if stop is None: stop = [] # Never want model to invent new turns of Human / Assistant dialog. stop.extend([self.HUMAN_PROMPT]) return stop [docs]class Anthropic(LLM, _AnthropicCommon): """Anthropic large language models. To use, you should have the ``anthropic`` python package installed, and the environment variable ``ANTHROPIC_API_KEY`` set with your API key, or pass it as a named parameter to the constructor. Example: .. code-block:: python import anthropic from langchain.llms import Anthropic model = Anthropic(model="<model_name>", anthropic_api_key="my-api-key") # Simplest invocation, automatically wrapped with HUMAN_PROMPT # and AI_PROMPT. response = model("What are the biggest risks facing humanity?") # Or if you want to use the chat mode, build a few-shot-prompt, or # put words in the Assistant's mouth, use HUMAN_PROMPT and AI_PROMPT: raw_prompt = "What are the biggest risks facing humanity?" prompt = f"{anthropic.HUMAN_PROMPT} {prompt}{anthropic.AI_PROMPT}" response = model(prompt) """ class Config: """Configuration for this pydantic object.""" allow_population_by_field_name = True arbitrary_types_allowed = True @root_validator() def raise_warning(cls, values: Dict) -> Dict: """Raise warning that this class is deprecated.""" warnings.warn( "This Anthropic LLM is deprecated. "
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
5c29157effa5-4
warnings.warn( "This Anthropic LLM is deprecated. " "Please use `from langchain.chat_models import ChatAnthropic` instead" ) return values @property def _llm_type(self) -> str: """Return type of llm.""" return "anthropic-llm" def _wrap_prompt(self, prompt: str) -> str: if not self.HUMAN_PROMPT or not self.AI_PROMPT: raise NameError("Please ensure the anthropic package is loaded") if prompt.startswith(self.HUMAN_PROMPT): return prompt # Already wrapped. # Guard against common errors in specifying wrong number of newlines. corrected_prompt, n_subs = re.subn(r"^\n*Human:", self.HUMAN_PROMPT, prompt) if n_subs == 1: return corrected_prompt # As a last resort, wrap the prompt ourselves to emulate instruct-style. return f"{self.HUMAN_PROMPT} {prompt}{self.AI_PROMPT} Sure, here you go:\n" def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: r"""Call out to Anthropic's completion endpoint. Args: prompt: The prompt to pass into the model. stop: Optional list of stop words to use when generating. Returns: The string generated by the model. Example: .. code-block:: python prompt = "What are the biggest risks facing humanity?" prompt = f"\n\nHuman: {prompt}\n\nAssistant:"
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
5c29157effa5-5
prompt = f"\n\nHuman: {prompt}\n\nAssistant:" response = model(prompt) """ if self.streaming: completion = "" for chunk in self._stream( prompt=prompt, stop=stop, run_manager=run_manager, **kwargs ): completion += chunk.text return completion stop = self._get_anthropic_stop(stop) params = {**self._default_params, **kwargs} response = self.client.completions.create( prompt=self._wrap_prompt(prompt), stop_sequences=stop, **params, ) return response.completion [docs] def convert_prompt(self, prompt: PromptValue) -> str: return self._wrap_prompt(prompt.to_string()) async def _acall( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Call out to Anthropic's completion endpoint asynchronously.""" if self.streaming: completion = "" async for chunk in self._astream( prompt=prompt, stop=stop, run_manager=run_manager, **kwargs ): completion += chunk.text return completion stop = self._get_anthropic_stop(stop) params = {**self._default_params, **kwargs} response = await self.async_client.completions.create( prompt=self._wrap_prompt(prompt), stop_sequences=stop, **params, ) return response.completion def _stream( self, prompt: str, stop: Optional[List[str]] = None,
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
5c29157effa5-6
prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> Iterator[GenerationChunk]: r"""Call Anthropic completion_stream and return the resulting generator. Args: prompt: The prompt to pass into the model. stop: Optional list of stop words to use when generating. Returns: A generator representing the stream of tokens from Anthropic. Example: .. code-block:: python prompt = "Write a poem about a stream." prompt = f"\n\nHuman: {prompt}\n\nAssistant:" generator = anthropic.stream(prompt) for token in generator: yield token """ stop = self._get_anthropic_stop(stop) params = {**self._default_params, **kwargs} for token in self.client.completions.create( prompt=self._wrap_prompt(prompt), stop_sequences=stop, stream=True, **params ): chunk = GenerationChunk(text=token.completion) yield chunk if run_manager: run_manager.on_llm_new_token(chunk.text, chunk=chunk) async def _astream( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, **kwargs: Any, ) -> AsyncIterator[GenerationChunk]: r"""Call Anthropic completion_stream and return the resulting generator. Args: prompt: The prompt to pass into the model. stop: Optional list of stop words to use when generating. Returns: A generator representing the stream of tokens from Anthropic.
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
5c29157effa5-7
Returns: A generator representing the stream of tokens from Anthropic. Example: .. code-block:: python prompt = "Write a poem about a stream." prompt = f"\n\nHuman: {prompt}\n\nAssistant:" generator = anthropic.stream(prompt) for token in generator: yield token """ stop = self._get_anthropic_stop(stop) params = {**self._default_params, **kwargs} async for token in await self.async_client.completions.create( prompt=self._wrap_prompt(prompt), stop_sequences=stop, stream=True, **params, ): chunk = GenerationChunk(text=token.completion) yield chunk if run_manager: await run_manager.on_llm_new_token(chunk.text, chunk=chunk) [docs] def get_num_tokens(self, text: str) -> int: """Calculate number of tokens.""" if not self.count_tokens: raise NameError("Please ensure the anthropic package is loaded") return self.count_tokens(text)
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
8774c8ff6f9d-0
Source code for langchain.llms.ctransformers from functools import partial from typing import Any, Dict, List, Optional, Sequence from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun, ) from langchain.llms.base import LLM from langchain.pydantic_v1 import root_validator [docs]class CTransformers(LLM): """C Transformers LLM models. To use, you should have the ``ctransformers`` python package installed. See https://github.com/marella/ctransformers Example: .. code-block:: python from langchain.llms import CTransformers llm = CTransformers(model="/path/to/ggml-gpt-2.bin", model_type="gpt2") """ client: Any #: :meta private: model: str """The path to a model file or directory or the name of a Hugging Face Hub model repo.""" model_type: Optional[str] = None """The model type.""" model_file: Optional[str] = None """The name of the model file in repo or directory.""" config: Optional[Dict[str, Any]] = None """The config parameters. See https://github.com/marella/ctransformers#config""" lib: Optional[str] = None """The path to a shared library or one of `avx2`, `avx`, `basic`.""" @property def _identifying_params(self) -> Dict[str, Any]: """Get the identifying parameters.""" return { "model": self.model, "model_type": self.model_type, "model_file": self.model_file,
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/ctransformers.html
8774c8ff6f9d-1
"model_type": self.model_type, "model_file": self.model_file, "config": self.config, } @property def _llm_type(self) -> str: """Return type of llm.""" return "ctransformers" @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that ``ctransformers`` package is installed.""" try: from ctransformers import AutoModelForCausalLM except ImportError: raise ImportError( "Could not import `ctransformers` package. " "Please install it with `pip install ctransformers`" ) config = values["config"] or {} values["client"] = AutoModelForCausalLM.from_pretrained( values["model"], model_type=values["model_type"], model_file=values["model_file"], lib=values["lib"], **config, ) return values def _call( self, prompt: str, stop: Optional[Sequence[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Generate text from a prompt. Args: prompt: The prompt to generate text from. stop: A list of sequences to stop generation when encountered. Returns: The generated text. Example: .. code-block:: python response = llm("Tell me a joke.") """ text = [] _run_manager = run_manager or CallbackManagerForLLMRun.get_noop_manager()
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/ctransformers.html
8774c8ff6f9d-2
_run_manager = run_manager or CallbackManagerForLLMRun.get_noop_manager() for chunk in self.client(prompt, stop=stop, stream=True): text.append(chunk) _run_manager.on_llm_new_token(chunk, verbose=self.verbose) return "".join(text) async def _acall( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Asynchronous Call out to CTransformers generate method. Very helpful when streaming (like with websockets!) Args: prompt: The prompt to pass into the model. stop: A list of strings to stop generation when encountered. Returns: The string generated by the model. Example: .. code-block:: python response = llm("Once upon a time, ") """ text_callback = None if run_manager: text_callback = partial(run_manager.on_llm_new_token, verbose=self.verbose) text = "" for token in self.client(prompt, stop=stop, stream=True): if text_callback: await text_callback(token) text += token return text
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/ctransformers.html
c9ff28d924c7-0
Source code for langchain.llms.petals import logging from typing import Any, Dict, List, Mapping, Optional from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens from langchain.pydantic_v1 import Extra, Field, root_validator from langchain.utils import get_from_dict_or_env logger = logging.getLogger(__name__) [docs]class Petals(LLM): """Petals Bloom models. To use, you should have the ``petals`` python package installed, and the environment variable ``HUGGINGFACE_API_KEY`` set with your API key. Any parameters that are valid to be passed to the call can be passed in, even if not explicitly saved on this class. Example: .. code-block:: python from langchain.llms import petals petals = Petals() """ client: Any """The client to use for the API calls.""" tokenizer: Any """The tokenizer to use for the API calls.""" model_name: str = "bigscience/bloom-petals" """The model to use.""" temperature: float = 0.7 """What sampling temperature to use""" max_new_tokens: int = 256 """The maximum number of new tokens to generate in the completion.""" top_p: float = 0.9 """The cumulative probability for top-p sampling.""" top_k: Optional[int] = None """The number of highest probability vocabulary tokens to keep for top-k-filtering.""" do_sample: bool = True """Whether or not to use sampling; use greedy decoding otherwise.""" max_length: Optional[int] = None
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/petals.html
c9ff28d924c7-1
max_length: Optional[int] = None """The maximum length of the sequence to be generated.""" model_kwargs: Dict[str, Any] = Field(default_factory=dict) """Holds any model parameters valid for `create` call not explicitly specified.""" huggingface_api_key: Optional[str] = None class Config: """Configuration for this pydantic config.""" extra = Extra.forbid @root_validator(pre=True) def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]: """Build extra kwargs from additional params that were passed in.""" all_required_field_names = {field.alias for field in cls.__fields__.values()} extra = values.get("model_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"""WARNING! {field_name} is not default parameter. {field_name} was transferred to model_kwargs. Please confirm that {field_name} is what you intended.""" ) extra[field_name] = values.pop(field_name) values["model_kwargs"] = extra return values @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" huggingface_api_key = get_from_dict_or_env( values, "huggingface_api_key", "HUGGINGFACE_API_KEY" ) try: from petals import AutoDistributedModelForCausalLM from transformers import AutoTokenizer model_name = values["model_name"]
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/petals.html
c9ff28d924c7-2
from transformers import AutoTokenizer model_name = values["model_name"] values["tokenizer"] = AutoTokenizer.from_pretrained(model_name) values["client"] = AutoDistributedModelForCausalLM.from_pretrained( model_name ) values["huggingface_api_key"] = huggingface_api_key except ImportError: raise ImportError( "Could not import transformers or petals python package." "Please install with `pip install -U transformers petals`." ) return values @property def _default_params(self) -> Dict[str, Any]: """Get the default parameters for calling Petals API.""" normal_params = { "temperature": self.temperature, "max_new_tokens": self.max_new_tokens, "top_p": self.top_p, "top_k": self.top_k, "do_sample": self.do_sample, "max_length": self.max_length, } return {**normal_params, **self.model_kwargs} @property def _identifying_params(self) -> Mapping[str, Any]: """Get the identifying parameters.""" return {**{"model_name": self.model_name}, **self._default_params} @property def _llm_type(self) -> str: """Return type of llm.""" return "petals" def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Call the Petals API.""" params = self._default_params params = {**params, **kwargs}
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/petals.html
c9ff28d924c7-3
params = self._default_params params = {**params, **kwargs} inputs = self.tokenizer(prompt, return_tensors="pt")["input_ids"] outputs = self.client.generate(inputs, **params) text = self.tokenizer.decode(outputs[0]) if stop is not None: # I believe this is required since the stop tokens # are not enforced by the model parameters text = enforce_stop_tokens(text, stop) return text
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/petals.html
6dc18c4db5c3-0
Source code for langchain.llms.tongyi from __future__ import annotations import logging from typing import Any, Callable, Dict, List, Optional from requests.exceptions import HTTPError from tenacity import ( before_sleep_log, retry, retry_if_exception_type, stop_after_attempt, wait_exponential, ) from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.pydantic_v1 import Field, root_validator from langchain.schema import Generation, LLMResult from langchain.utils import get_from_dict_or_env logger = logging.getLogger(__name__) def _create_retry_decorator(llm: Tongyi) -> Callable[[Any], Any]: min_seconds = 1 max_seconds = 4 # 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(llm.max_retries), wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds), retry=(retry_if_exception_type(HTTPError)), before_sleep=before_sleep_log(logger, logging.WARNING), ) [docs]def generate_with_retry(llm: Tongyi, **kwargs: Any) -> Any: """Use tenacity to retry the completion call.""" retry_decorator = _create_retry_decorator(llm) @retry_decorator def _generate_with_retry(**_kwargs: Any) -> Any: resp = llm.client.call(**_kwargs) if resp.status_code == 200: return resp elif resp.status_code in [400, 401]: raise ValueError(
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/tongyi.html
6dc18c4db5c3-1
elif resp.status_code in [400, 401]: raise ValueError( f"status_code: {resp.status_code} \n " f"code: {resp.code} \n message: {resp.message}" ) else: raise HTTPError( f"HTTP error occurred: status_code: {resp.status_code} \n " f"code: {resp.code} \n message: {resp.message}", response=resp, ) return _generate_with_retry(**kwargs) [docs]def stream_generate_with_retry(llm: Tongyi, **kwargs: Any) -> Any: """Use tenacity to retry the completion call.""" retry_decorator = _create_retry_decorator(llm) @retry_decorator def _stream_generate_with_retry(**_kwargs: Any) -> Any: stream_resps = [] resps = llm.client.call(**_kwargs) for resp in resps: if resp.status_code == 200: stream_resps.append(resp) elif resp.status_code in [400, 401]: raise ValueError( f"status_code: {resp.status_code} \n " f"code: {resp.code} \n message: {resp.message}" ) else: raise HTTPError( f"HTTP error occurred: status_code: {resp.status_code} \n " f"code: {resp.code} \n message: {resp.message}", response=resp, ) return stream_resps return _stream_generate_with_retry(**kwargs) [docs]class Tongyi(LLM): """Tongyi Qwen large language models.
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/tongyi.html
6dc18c4db5c3-2
"""Tongyi Qwen large language models. To use, you should have the ``dashscope`` python package installed, and the environment variable ``DASHSCOPE_API_KEY`` set with your API key, or pass it as a named parameter to the constructor. Example: .. code-block:: python from langchain.llms import Tongyi Tongyi = tongyi() """ @property def lc_secrets(self) -> Dict[str, str]: return {"dashscope_api_key": "DASHSCOPE_API_KEY"} [docs] @classmethod def is_lc_serializable(cls) -> bool: return True client: Any #: :meta private: model_name: str = "qwen-plus-v1" """Model name to use.""" model_kwargs: Dict[str, Any] = Field(default_factory=dict) top_p: float = 0.8 """Total probability mass of tokens to consider at each step.""" dashscope_api_key: Optional[str] = None """Dashscope api key provide by alicloud.""" n: int = 1 """How many completions to generate for each prompt.""" streaming: bool = False """Whether to stream the results or not.""" max_retries: int = 10 """Maximum number of retries to make when generating.""" prefix_messages: List = Field(default_factory=list) """Series of messages for Chat input.""" @property def _llm_type(self) -> str: """Return type of llm.""" return "tongyi" @root_validator() def validate_environment(cls, values: Dict) -> Dict:
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/tongyi.html
6dc18c4db5c3-3
@root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" get_from_dict_or_env(values, "dashscope_api_key", "DASHSCOPE_API_KEY") try: import dashscope except ImportError: raise ImportError( "Could not import dashscope python package. " "Please install it with `pip install dashscope`." ) try: values["client"] = dashscope.Generation except AttributeError: raise ValueError( "`dashscope` has no `Generation` attribute, this is likely " "due to an old version of the dashscope package. Try upgrading it " "with `pip install --upgrade dashscope`." ) return values @property def _default_params(self) -> Dict[str, Any]: """Get the default parameters for calling OpenAI API.""" normal_params = { "top_p": self.top_p, } return {**normal_params, **self.model_kwargs} def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Call out to Tongyi's generate endpoint. Args: prompt: The prompt to pass into the model. Returns: The string generated by the model. Example: .. code-block:: python response = tongyi("Tell me a joke.") """ params: Dict[str, Any] = { **{"model": self.model_name}, **self._default_params,
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/tongyi.html
6dc18c4db5c3-4
**{"model": self.model_name}, **self._default_params, **kwargs, } completion = generate_with_retry( self, prompt=prompt, **params, ) return completion["output"]["text"] def _generate( self, prompts: List[str], stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> LLMResult: generations = [] params: Dict[str, Any] = { **{"model": self.model_name}, **self._default_params, **kwargs, } if self.streaming: if len(prompts) > 1: raise ValueError("Cannot stream results with multiple prompts.") params["stream"] = True for stream_resp in stream_generate_with_retry( self, prompt=prompts[0], **params ): generations.append( [ Generation( text=stream_resp["output"]["text"], generation_info=dict( finish_reason=stream_resp["output"]["finish_reason"], ), ) ] ) else: for prompt in prompts: completion = generate_with_retry( self, prompt=prompt, **params, ) generations.append( [ Generation( text=completion["output"]["text"], generation_info=dict( finish_reason=completion["output"]["finish_reason"], ), ) ] ) return LLMResult(generations=generations)
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/tongyi.html
c71012282eac-0
Source code for langchain.llms.fake import asyncio import time from typing import Any, AsyncIterator, Iterator, List, Mapping, Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun, ) from langchain.llms.base import LLM from langchain.schema.language_model import LanguageModelInput from langchain.schema.runnable import RunnableConfig [docs]class FakeListLLM(LLM): """Fake LLM for testing purposes.""" responses: List[str] sleep: Optional[float] = None i: int = 0 @property def _llm_type(self) -> str: """Return type of llm.""" return "fake-list" def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Return next response""" response = self.responses[self.i] if self.i < len(self.responses) - 1: self.i += 1 else: self.i = 0 return response async def _acall( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Return next response""" response = self.responses[self.i] if self.i < len(self.responses) - 1: self.i += 1 else: self.i = 0 return response @property
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/fake.html
c71012282eac-1
else: self.i = 0 return response @property def _identifying_params(self) -> Mapping[str, Any]: return {"responses": self.responses} [docs]class FakeStreamingListLLM(FakeListLLM): """Fake streaming list LLM for testing purposes.""" [docs] def stream( self, input: LanguageModelInput, config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any, ) -> Iterator[str]: result = self.invoke(input, config) for c in result: if self.sleep is not None: time.sleep(self.sleep) yield c [docs] async def astream( self, input: LanguageModelInput, config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any, ) -> AsyncIterator[str]: result = await self.ainvoke(input, config) for c in result: if self.sleep is not None: await asyncio.sleep(self.sleep) yield c
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/fake.html
7dd2e86421b2-0
Source code for langchain.llms.clarifai import logging from typing import Any, Dict, List, Optional from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens from langchain.pydantic_v1 import Extra, root_validator from langchain.schema import Generation, LLMResult from langchain.utils import get_from_dict_or_env logger = logging.getLogger(__name__) [docs]class Clarifai(LLM): """Clarifai large language models. To use, you should have an account on the Clarifai platform, the ``clarifai`` python package installed, and the environment variable ``CLARIFAI_PAT`` set with your PAT key, or pass it as a named parameter to the constructor. Example: .. code-block:: python from langchain.llms import Clarifai clarifai_llm = Clarifai(pat=CLARIFAI_PAT, \ user_id=USER_ID, app_id=APP_ID, model_id=MODEL_ID) """ stub: Any #: :meta private: userDataObject: Any model_id: Optional[str] = None """Model id to use.""" model_version_id: Optional[str] = None """Model version id to use.""" app_id: Optional[str] = None """Clarifai application id to use.""" user_id: Optional[str] = None """Clarifai user id to use.""" pat: Optional[str] = None api_base: str = "https://api.clarifai.com" class Config: """Configuration for this pydantic object.""" extra = Extra.forbid
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/clarifai.html
7dd2e86421b2-1
"""Configuration for this pydantic object.""" extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that we have all required info to access Clarifai platform and python package exists in environment.""" values["pat"] = get_from_dict_or_env(values, "pat", "CLARIFAI_PAT") user_id = values.get("user_id") app_id = values.get("app_id") model_id = values.get("model_id") if values["pat"] is None: raise ValueError("Please provide a pat.") if user_id is None: raise ValueError("Please provide a user_id.") if app_id is None: raise ValueError("Please provide a app_id.") if model_id is None: raise ValueError("Please provide a model_id.") try: from clarifai.auth.helper import ClarifaiAuthHelper from clarifai.client import create_stub except ImportError: raise ImportError( "Could not import clarifai python package. " "Please install it with `pip install clarifai`." ) auth = ClarifaiAuthHelper( user_id=user_id, app_id=app_id, pat=values["pat"], base=values["api_base"], ) values["userDataObject"] = auth.get_user_app_id_proto() values["stub"] = create_stub(auth) return values @property def _default_params(self) -> Dict[str, Any]: """Get the default parameters for calling Clarifai API.""" return {} @property def _identifying_params(self) -> Dict[str, Any]:
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/clarifai.html
7dd2e86421b2-2
@property def _identifying_params(self) -> Dict[str, Any]: """Get the identifying parameters.""" return { **{ "user_id": self.user_id, "app_id": self.app_id, "model_id": self.model_id, } } @property def _llm_type(self) -> str: """Return type of llm.""" return "clarifai" def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Call out to Clarfai's PostModelOutputs endpoint. Args: prompt: The prompt to pass into the model. stop: Optional list of stop words to use when generating. Returns: The string generated by the model. Example: .. code-block:: python response = clarifai_llm("Tell me a joke.") """ try: from clarifai_grpc.grpc.api import ( resources_pb2, service_pb2, ) from clarifai_grpc.grpc.api.status import status_code_pb2 except ImportError: raise ImportError( "Could not import clarifai python package. " "Please install it with `pip install clarifai`." ) # The userDataObject is created in the overview and # is required when using a PAT # If version_id None, Defaults to the latest model version post_model_outputs_request = service_pb2.PostModelOutputsRequest( user_app_id=self.userDataObject,
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/clarifai.html
7dd2e86421b2-3
user_app_id=self.userDataObject, model_id=self.model_id, version_id=self.model_version_id, inputs=[ resources_pb2.Input( data=resources_pb2.Data(text=resources_pb2.Text(raw=prompt)) ) ], ) post_model_outputs_response = self.stub.PostModelOutputs( post_model_outputs_request ) if post_model_outputs_response.status.code != status_code_pb2.SUCCESS: logger.error(post_model_outputs_response.status) first_model_failure = ( post_model_outputs_response.outputs[0].status if len(post_model_outputs_response.outputs) else None ) raise Exception( f"Post model outputs failed, status: " f"{post_model_outputs_response.status}, first output failure: " f"{first_model_failure}" ) text = post_model_outputs_response.outputs[0].data.text.raw # In order to make this consistent with other endpoints, we strip them. if stop is not None: text = enforce_stop_tokens(text, stop) return text def _generate( self, prompts: List[str], stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> LLMResult: """Run the LLM on the given prompt and input.""" try: from clarifai_grpc.grpc.api import ( resources_pb2, service_pb2, ) from clarifai_grpc.grpc.api.status import status_code_pb2 except ImportError: raise ImportError( "Could not import clarifai python package. "
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/clarifai.html
7dd2e86421b2-4
raise ImportError( "Could not import clarifai python package. " "Please install it with `pip install clarifai`." ) # TODO: add caching here. generations = [] batch_size = 32 for i in range(0, len(prompts), batch_size): batch = prompts[i : i + batch_size] post_model_outputs_request = service_pb2.PostModelOutputsRequest( user_app_id=self.userDataObject, model_id=self.model_id, version_id=self.model_version_id, inputs=[ resources_pb2.Input( data=resources_pb2.Data(text=resources_pb2.Text(raw=prompt)) ) for prompt in batch ], ) post_model_outputs_response = self.stub.PostModelOutputs( post_model_outputs_request ) if post_model_outputs_response.status.code != status_code_pb2.SUCCESS: logger.error(post_model_outputs_response.status) first_model_failure = ( post_model_outputs_response.outputs[0].status if len(post_model_outputs_response.outputs) else None ) raise Exception( f"Post model outputs failed, status: " f"{post_model_outputs_response.status}, first output failure: " f"{first_model_failure}" ) for output in post_model_outputs_response.outputs: if stop is not None: text = enforce_stop_tokens(output.data.text.raw, stop) else: text = output.data.text.raw generations.append([Generation(text=text)]) return LLMResult(generations=generations)
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/clarifai.html
a8c3a00041c0-0
Source code for langchain.llms.textgen import json import logging from typing import Any, AsyncIterator, Dict, Iterator, List, Optional import requests from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun, ) from langchain.llms.base import LLM from langchain.pydantic_v1 import Field from langchain.schema.output import GenerationChunk logger = logging.getLogger(__name__) [docs]class TextGen(LLM): """text-generation-webui models. To use, you should have the text-generation-webui installed, a model loaded, and --api added as a command-line option. Suggested installation, use one-click installer for your OS: https://github.com/oobabooga/text-generation-webui#one-click-installers Parameters below taken from text-generation-webui api example: https://github.com/oobabooga/text-generation-webui/blob/main/api-examples/api-example.py Example: .. code-block:: python from langchain.llms import TextGen llm = TextGen(model_url="http://localhost:8500") """ model_url: str """The full URL to the textgen webui including http[s]://host:port """ preset: Optional[str] = None """The preset to use in the textgen webui """ max_new_tokens: Optional[int] = 250 """The maximum number of tokens to generate.""" do_sample: bool = Field(True, alias="do_sample") """Do sample""" temperature: Optional[float] = 1.3 """Primary factor to control randomness of outputs. 0 = deterministic (only the most likely token is used). Higher value = more randomness."""
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html
a8c3a00041c0-1
(only the most likely token is used). Higher value = more randomness.""" top_p: Optional[float] = 0.1 """If not set to 1, select tokens with probabilities adding up to less than this number. Higher value = higher range of possible random results.""" typical_p: Optional[float] = 1 """If not set to 1, select only tokens that are at least this much more likely to appear than random tokens, given the prior text.""" epsilon_cutoff: Optional[float] = 0 # In units of 1e-4 """Epsilon cutoff""" eta_cutoff: Optional[float] = 0 # In units of 1e-4 """ETA cutoff""" repetition_penalty: Optional[float] = 1.18 """Exponential penalty factor for repeating prior tokens. 1 means no penalty, higher value = less repetition, lower value = more repetition.""" top_k: Optional[float] = 40 """Similar to top_p, but select instead only the top_k most likely tokens. Higher value = higher range of possible random results.""" min_length: Optional[int] = 0 """Minimum generation length in tokens.""" no_repeat_ngram_size: Optional[int] = 0 """If not set to 0, specifies the length of token sets that are completely blocked from repeating at all. Higher values = blocks larger phrases, lower values = blocks words or letters from repeating. Only 0 or high values are a good idea in most cases.""" num_beams: Optional[int] = 1 """Number of beams""" penalty_alpha: Optional[float] = 0 """Penalty Alpha""" length_penalty: Optional[float] = 1
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html
a8c3a00041c0-2
"""Penalty Alpha""" length_penalty: Optional[float] = 1 """Length Penalty""" early_stopping: bool = Field(False, alias="early_stopping") """Early stopping""" seed: int = Field(-1, alias="seed") """Seed (-1 for random)""" add_bos_token: bool = Field(True, alias="add_bos_token") """Add the bos_token to the beginning of prompts. Disabling this can make the replies more creative.""" truncation_length: Optional[int] = 2048 """Truncate the prompt up to this length. The leftmost tokens are removed if the prompt exceeds this length. Most models require this to be at most 2048.""" ban_eos_token: bool = Field(False, alias="ban_eos_token") """Ban the eos_token. Forces the model to never end the generation prematurely.""" skip_special_tokens: bool = Field(True, alias="skip_special_tokens") """Skip special tokens. Some specific models need this unset.""" stopping_strings: Optional[List[str]] = [] """A list of strings to stop generation when encountered.""" streaming: bool = False """Whether to stream the results, token by token.""" @property def _default_params(self) -> Dict[str, Any]: """Get the default parameters for calling textgen.""" return { "max_new_tokens": self.max_new_tokens, "do_sample": self.do_sample, "temperature": self.temperature, "top_p": self.top_p, "typical_p": self.typical_p, "epsilon_cutoff": self.epsilon_cutoff, "eta_cutoff": self.eta_cutoff, "repetition_penalty": self.repetition_penalty,
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html
a8c3a00041c0-3
"repetition_penalty": self.repetition_penalty, "top_k": self.top_k, "min_length": self.min_length, "no_repeat_ngram_size": self.no_repeat_ngram_size, "num_beams": self.num_beams, "penalty_alpha": self.penalty_alpha, "length_penalty": self.length_penalty, "early_stopping": self.early_stopping, "seed": self.seed, "add_bos_token": self.add_bos_token, "truncation_length": self.truncation_length, "ban_eos_token": self.ban_eos_token, "skip_special_tokens": self.skip_special_tokens, "stopping_strings": self.stopping_strings, } @property def _identifying_params(self) -> Dict[str, Any]: """Get the identifying parameters.""" return {**{"model_url": self.model_url}, **self._default_params} @property def _llm_type(self) -> str: """Return type of llm.""" return "textgen" def _get_parameters(self, stop: Optional[List[str]] = None) -> Dict[str, Any]: """ Performs sanity check, preparing parameters in format needed by textgen. Args: stop (Optional[List[str]]): List of stop sequences for textgen. Returns: Dictionary containing the combined parameters. """ # Raise error if stop sequences are in both input and default params # if self.stop and stop is not None: if self.stopping_strings and stop is not None: raise ValueError("`stop` found in both the input and default params.") if self.preset is None:
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html
a8c3a00041c0-4
if self.preset is None: params = self._default_params else: params = {"preset": self.preset} # then sets it as configured, or default to an empty list: params["stopping_strings"] = self.stopping_strings or stop or [] return params def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Call the textgen web API and return the output. Args: prompt: The prompt to use for generation. stop: A list of strings to stop generation when encountered. Returns: The generated text. Example: .. code-block:: python from langchain.llms import TextGen llm = TextGen(model_url="http://localhost:5000") llm("Write a story about llamas.") """ if self.streaming: combined_text_output = "" for chunk in self._stream( prompt=prompt, stop=stop, run_manager=run_manager, **kwargs ): combined_text_output += chunk.text result = combined_text_output else: url = f"{self.model_url}/api/v1/generate" params = self._get_parameters(stop) request = params.copy() request["prompt"] = prompt response = requests.post(url, json=request) if response.status_code == 200: result = response.json()["results"][0]["text"] else: print(f"ERROR: response: {response}") result = "" return result
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html
a8c3a00041c0-5
result = "" return result async def _acall( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Call the textgen web API and return the output. Args: prompt: The prompt to use for generation. stop: A list of strings to stop generation when encountered. Returns: The generated text. Example: .. code-block:: python from langchain.llms import TextGen llm = TextGen(model_url="http://localhost:5000") llm("Write a story about llamas.") """ if self.streaming: combined_text_output = "" async for chunk in self._astream( prompt=prompt, stop=stop, run_manager=run_manager, **kwargs ): combined_text_output += chunk.text result = combined_text_output else: url = f"{self.model_url}/api/v1/generate" params = self._get_parameters(stop) request = params.copy() request["prompt"] = prompt response = requests.post(url, json=request) if response.status_code == 200: result = response.json()["results"][0]["text"] else: print(f"ERROR: response: {response}") result = "" return result def _stream( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> Iterator[GenerationChunk]:
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html
a8c3a00041c0-6
**kwargs: Any, ) -> Iterator[GenerationChunk]: """Yields results objects as they are generated in real time. It also calls the callback manager's on_llm_new_token event with similar parameters to the OpenAI LLM class method of the same name. Args: prompt: The prompts to pass into the model. stop: Optional list of stop words to use when generating. Returns: A generator representing the stream of tokens being generated. Yields: A dictionary like objects containing a string token and metadata. See text-generation-webui docs and below for more. Example: .. code-block:: python from langchain.llms import TextGen llm = TextGen( model_url = "ws://localhost:5005" streaming=True ) for chunk in llm.stream("Ask 'Hi, how are you?' like a pirate:'", stop=["'","\n"]): print(chunk, end='', flush=True) """ try: import websocket except ImportError: raise ImportError( "The `websocket-client` package is required for streaming." ) params = {**self._get_parameters(stop), **kwargs} url = f"{self.model_url}/api/v1/stream" request = params.copy() request["prompt"] = prompt websocket_client = websocket.WebSocket() websocket_client.connect(url) websocket_client.send(json.dumps(request)) while True: result = websocket_client.recv() result = json.loads(result) if result["event"] == "text_stream": chunk = GenerationChunk( text=result["text"], generation_info=None, ) yield chunk
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html
a8c3a00041c0-7
text=result["text"], generation_info=None, ) yield chunk elif result["event"] == "stream_end": websocket_client.close() return if run_manager: run_manager.on_llm_new_token(token=chunk.text) async def _astream( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, **kwargs: Any, ) -> AsyncIterator[GenerationChunk]: """Yields results objects as they are generated in real time. It also calls the callback manager's on_llm_new_token event with similar parameters to the OpenAI LLM class method of the same name. Args: prompt: The prompts to pass into the model. stop: Optional list of stop words to use when generating. Returns: A generator representing the stream of tokens being generated. Yields: A dictionary like objects containing a string token and metadata. See text-generation-webui docs and below for more. Example: .. code-block:: python from langchain.llms import TextGen llm = TextGen( model_url = "ws://localhost:5005" streaming=True ) for chunk in llm.stream("Ask 'Hi, how are you?' like a pirate:'", stop=["'","\n"]): print(chunk, end='', flush=True) """ try: import websocket except ImportError: raise ImportError( "The `websocket-client` package is required for streaming." ) params = {**self._get_parameters(stop), **kwargs}
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html
a8c3a00041c0-8
) params = {**self._get_parameters(stop), **kwargs} url = f"{self.model_url}/api/v1/stream" request = params.copy() request["prompt"] = prompt websocket_client = websocket.WebSocket() websocket_client.connect(url) websocket_client.send(json.dumps(request)) while True: result = websocket_client.recv() result = json.loads(result) if result["event"] == "text_stream": chunk = GenerationChunk( text=result["text"], generation_info=None, ) yield chunk elif result["event"] == "stream_end": websocket_client.close() return if run_manager: await run_manager.on_llm_new_token(token=chunk.text)
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html
1bb0135bde89-0
Source code for langchain.llms.huggingface_pipeline from __future__ import annotations import importlib.util import logging from typing import Any, List, Mapping, Optional from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import BaseLLM from langchain.llms.utils import enforce_stop_tokens from langchain.pydantic_v1 import Extra from langchain.schema import Generation, LLMResult DEFAULT_MODEL_ID = "gpt2" DEFAULT_TASK = "text-generation" VALID_TASKS = ("text2text-generation", "text-generation", "summarization") DEFAULT_BATCH_SIZE = 4 logger = logging.getLogger(__name__) [docs]class HuggingFacePipeline(BaseLLM): """HuggingFace Pipeline API. To use, you should have the ``transformers`` python package installed. Only supports `text-generation`, `text2text-generation` and `summarization` for now. Example using from_model_id: .. code-block:: python from langchain.llms import HuggingFacePipeline hf = HuggingFacePipeline.from_model_id( model_id="gpt2", task="text-generation", pipeline_kwargs={"max_new_tokens": 10}, ) Example passing pipeline in directly: .. code-block:: python from langchain.llms import HuggingFacePipeline from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline model_id = "gpt2" tokenizer = AutoTokenizer.from_pretrained(model_id) model = AutoModelForCausalLM.from_pretrained(model_id) pipe = pipeline( "text-generation", model=model, tokenizer=tokenizer, max_new_tokens=10 ) hf = HuggingFacePipeline(pipeline=pipe)
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html
1bb0135bde89-1
) hf = HuggingFacePipeline(pipeline=pipe) """ pipeline: Any #: :meta private: model_id: str = DEFAULT_MODEL_ID """Model name to use.""" model_kwargs: Optional[dict] = None """Keyword arguments passed to the model.""" pipeline_kwargs: Optional[dict] = None """Keyword arguments passed to the pipeline.""" batch_size: int = DEFAULT_BATCH_SIZE """Batch size to use when passing multiple documents to generate.""" class Config: """Configuration for this pydantic object.""" extra = Extra.forbid [docs] @classmethod def from_model_id( cls, model_id: str, task: str, device: Optional[int] = -1, device_map: Optional[str] = None, model_kwargs: Optional[dict] = None, pipeline_kwargs: Optional[dict] = None, batch_size: int = DEFAULT_BATCH_SIZE, **kwargs: Any, ) -> HuggingFacePipeline: """Construct the pipeline object from model_id and task.""" try: from transformers import ( AutoModelForCausalLM, AutoModelForSeq2SeqLM, AutoTokenizer, ) from transformers import pipeline as hf_pipeline except ImportError: raise ValueError( "Could not import transformers python package. " "Please install it with `pip install transformers`." ) _model_kwargs = model_kwargs or {} tokenizer = AutoTokenizer.from_pretrained(model_id, **_model_kwargs) try: if task == "text-generation": model = AutoModelForCausalLM.from_pretrained(model_id, **_model_kwargs)
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html
1bb0135bde89-2
elif task in ("text2text-generation", "summarization"): model = AutoModelForSeq2SeqLM.from_pretrained(model_id, **_model_kwargs) else: raise ValueError( f"Got invalid task {task}, " f"currently only {VALID_TASKS} are supported" ) except ImportError as e: raise ValueError( f"Could not load the {task} model due to missing dependencies." ) from e if tokenizer.pad_token is None: tokenizer.pad_token_id = model.config.eos_token_id if ( getattr(model, "is_loaded_in_4bit", False) or getattr(model, "is_loaded_in_8bit", False) ) and device is not None: logger.warning( f"Setting the `device` argument to None from {device} to avoid " "the error caused by attempting to move the model that was already " "loaded on the GPU using the Accelerate module to the same or " "another device." ) device = None if device is not None and importlib.util.find_spec("torch") is not None: import torch cuda_device_count = torch.cuda.device_count() if device < -1 or (device >= cuda_device_count): raise ValueError( f"Got device=={device}, " f"device is required to be within [-1, {cuda_device_count})" ) if device_map is not None and device < 0: device = None if device is not None and device < 0 and cuda_device_count > 0: logger.warning( "Device has %d GPUs available. "
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html
1bb0135bde89-3
logger.warning( "Device has %d GPUs available. " "Provide device={deviceId} to `from_model_id` to use available" "GPUs for execution. deviceId is -1 (default) for CPU and " "can be a positive integer associated with CUDA device id.", cuda_device_count, ) if "trust_remote_code" in _model_kwargs: _model_kwargs = { k: v for k, v in _model_kwargs.items() if k != "trust_remote_code" } _pipeline_kwargs = pipeline_kwargs or {} pipeline = hf_pipeline( task=task, model=model, tokenizer=tokenizer, device=device, device_map=device_map, batch_size=batch_size, model_kwargs=_model_kwargs, **_pipeline_kwargs, ) if pipeline.task not in VALID_TASKS: raise ValueError( f"Got invalid task {pipeline.task}, " f"currently only {VALID_TASKS} are supported" ) return cls( pipeline=pipeline, model_id=model_id, model_kwargs=_model_kwargs, pipeline_kwargs=_pipeline_kwargs, batch_size=batch_size, **kwargs, ) @property def _identifying_params(self) -> Mapping[str, Any]: """Get the identifying parameters.""" return { "model_id": self.model_id, "model_kwargs": self.model_kwargs, "pipeline_kwargs": self.pipeline_kwargs, } @property def _llm_type(self) -> str: return "huggingface_pipeline" def _generate( self, prompts: List[str],
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html
1bb0135bde89-4
def _generate( self, prompts: List[str], stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> LLMResult: # List to hold all results text_generations: List[str] = [] for i in range(0, len(prompts), self.batch_size): batch_prompts = prompts[i : i + self.batch_size] # Process batch of prompts responses = self.pipeline(batch_prompts) # Process each response in the batch for j, response in enumerate(responses): if isinstance(response, list): # if model returns multiple generations, pick the top one response = response[0] if self.pipeline.task == "text-generation": try: from transformers.pipelines.text_generation import ReturnType remove_prompt = ( self.pipeline._postprocess_params.get("return_type") != ReturnType.NEW_TEXT ) except Exception as e: logger.warning( f"Unable to extract pipeline return_type. " f"Received error:\n\n{e}" ) remove_prompt = True if remove_prompt: text = response["generated_text"][len(batch_prompts[j]) :] else: text = response["generated_text"] elif self.pipeline.task == "text2text-generation": text = response["generated_text"] elif self.pipeline.task == "summarization": text = response["summary_text"] else: raise ValueError( f"Got invalid task {self.pipeline.task}, " f"currently only {VALID_TASKS} are supported" ) if stop:
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html
1bb0135bde89-5
) if stop: # Enforce stop tokens text = enforce_stop_tokens(text, stop) # Append the processed text to results text_generations.append(text) return LLMResult( generations=[[Generation(text=text)] for text in text_generations] )
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html
9e987a642600-0
Source code for langchain.llms.gigachat from __future__ import annotations import logging from functools import cached_property from typing import Any, AsyncIterator, Dict, Iterator, List, Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun, ) from langchain.llms.base import BaseLLM from langchain.load.serializable import Serializable from langchain.pydantic_v1 import root_validator from langchain.schema.output import Generation, GenerationChunk, LLMResult logger = logging.getLogger(__name__) class _BaseGigaChat(Serializable): base_url: Optional[str] = None """ Base API URL """ auth_url: Optional[str] = None """ Auth URL """ credentials: Optional[str] = None """ Auth Token """ scope: Optional[str] = None """ Permission scope for access token """ access_token: Optional[str] = None """ Access token for GigaChat """ model: Optional[str] = None """Model name to use.""" user: Optional[str] = None """ Username for authenticate """ password: Optional[str] = None """ Password for authenticate """ timeout: Optional[float] = None """ Timeout for request """ verify_ssl_certs: Optional[bool] = None """ Check certificates for all requests """ ca_bundle_file: Optional[str] = None cert_file: Optional[str] = None key_file: Optional[str] = None key_file_password: Optional[str] = None # Support for connection to GigaChat through SSL certificates profanity: bool = True """ Check for profanity """ streaming: bool = False """ Whether to stream the results or not. """
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gigachat.html
9e987a642600-1
streaming: bool = False """ Whether to stream the results or not. """ temperature: Optional[float] = None """What sampling temperature to use.""" max_tokens: Optional[int] = None """ Maximum number of tokens to generate """ @property def _llm_type(self) -> str: return "giga-chat-model" @property def lc_secrets(self) -> Dict[str, str]: return { "credentials": "GIGACHAT_CREDENTIALS", "access_token": "GIGACHAT_ACCESS_TOKEN", "password": "GIGACHAT_PASSWORD", "key_file_password": "GIGACHAT_KEY_FILE_PASSWORD", } @property def lc_serializable(self) -> bool: return True @cached_property def _client(self) -> Any: """Returns GigaChat API client""" import gigachat return gigachat.GigaChat( base_url=self.base_url, auth_url=self.auth_url, credentials=self.credentials, scope=self.scope, access_token=self.access_token, model=self.model, user=self.user, password=self.password, timeout=self.timeout, verify_ssl_certs=self.verify_ssl_certs, ca_bundle_file=self.ca_bundle_file, cert_file=self.cert_file, key_file=self.key_file, key_file_password=self.key_file_password, ) @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate authenticate data in environment and python package is installed.""" try: import gigachat # noqa: F401 except ImportError: raise ImportError(
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gigachat.html
9e987a642600-2
except ImportError: raise ImportError( "Could not import gigachat python package. " "Please install it with `pip install gigachat`." ) return values @property def _identifying_params(self) -> Dict[str, Any]: """Get the identifying parameters.""" return { "temperature": self.temperature, "model": self.model, "profanity": self.profanity, "streaming": self.streaming, "max_tokens": self.max_tokens, } [docs]class GigaChat(_BaseGigaChat, BaseLLM): """`GigaChat` large language models API. To use, you should pass login and password to access GigaChat API or use token. Example: .. code-block:: python from langchain.llms import GigaChat giga = GigaChat(credentials=..., verify_ssl_certs=False) """ def _build_payload(self, messages: List[str]) -> Dict[str, Any]: payload: Dict[str, Any] = { "messages": [{"role": "user", "content": m} for m in messages], "profanity_check": self.profanity, } if self.temperature is not None: payload["temperature"] = self.temperature if self.max_tokens is not None: payload["max_tokens"] = self.max_tokens if self.model: payload["model"] = self.model if self.verbose: logger.info("Giga request: %s", payload) return payload def _create_llm_result(self, response: Any) -> LLMResult: generations = [] for res in response.choices:
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gigachat.html
9e987a642600-3
generations = [] for res in response.choices: finish_reason = res.finish_reason gen = Generation( text=res.message.content, generation_info={"finish_reason": finish_reason}, ) generations.append([gen]) if finish_reason != "stop": logger.warning( "Giga generation stopped with reason: %s", finish_reason, ) if self.verbose: logger.info("Giga response: %s", res.message.content) token_usage = response.usage llm_output = {"token_usage": token_usage, "model_name": response.model} return LLMResult(generations=generations, llm_output=llm_output) def _generate( self, prompts: List[str], stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, stream: Optional[bool] = None, **kwargs: Any, ) -> LLMResult: should_stream = stream if stream is not None else self.streaming if should_stream: generation: Optional[GenerationChunk] = None stream_iter = self._stream( prompts[0], stop=stop, run_manager=run_manager, **kwargs ) for chunk in stream_iter: if generation is None: generation = chunk else: generation += chunk assert generation is not None return LLMResult(generations=[[generation]]) payload = self._build_payload(prompts) response = self._client.chat(payload) return self._create_llm_result(response) async def _agenerate( self, prompts: List[str],
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gigachat.html
9e987a642600-4
async def _agenerate( self, prompts: List[str], stop: Optional[List[str]] = None, run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, stream: Optional[bool] = None, **kwargs: Any, ) -> LLMResult: should_stream = stream if stream is not None else self.streaming if should_stream: generation: Optional[GenerationChunk] = None stream_iter = self._astream( prompts[0], stop=stop, run_manager=run_manager, **kwargs ) async for chunk in stream_iter: if generation is None: generation = chunk else: generation += chunk assert generation is not None return LLMResult(generations=[[generation]]) payload = self._build_payload(prompts) response = await self._client.achat(payload) return self._create_llm_result(response) def _stream( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> Iterator[GenerationChunk]: payload = self._build_payload([prompt]) for chunk in self._client.stream(payload): if chunk.choices: content = chunk.choices[0].delta.content yield GenerationChunk(text=content) if run_manager: run_manager.on_llm_new_token(content) async def _astream( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, **kwargs: Any,
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gigachat.html
9e987a642600-5
**kwargs: Any, ) -> AsyncIterator[GenerationChunk]: payload = self._build_payload([prompt]) async for chunk in self._client.astream(payload): if chunk.choices: content = chunk.choices[0].delta.content yield GenerationChunk(text=content) if run_manager: await run_manager.on_llm_new_token(content) [docs] def get_num_tokens(self, text: str) -> int: """Count approximate number of tokens""" return round(len(text) / 4.6)
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gigachat.html
d3adf7627ac8-0
Source code for langchain.llms.titan_takeoff from typing import Any, Iterator, List, Mapping, Optional import requests from requests.exceptions import ConnectionError from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens from langchain.schema.output import GenerationChunk [docs]class TitanTakeoff(LLM): """Wrapper around Titan Takeoff APIs.""" base_url: str = "http://localhost:8000" """Specifies the baseURL to use for the Titan Takeoff API. Default = http://localhost:8000. """ generate_max_length: int = 128 """Maximum generation length. Default = 128.""" sampling_topk: int = 1 """Sample predictions from the top K most probable candidates. Default = 1.""" sampling_topp: float = 1.0 """Sample from predictions whose cumulative probability exceeds this value. Default = 1.0. """ sampling_temperature: float = 1.0 """Sample with randomness. Bigger temperatures are associated with more randomness and 'creativity'. Default = 1.0. """ repetition_penalty: float = 1.0 """Penalise the generation of tokens that have been generated before. Set to > 1 to penalize. Default = 1 (no penalty). """ no_repeat_ngram_size: int = 0 """Prevent repetitions of ngrams of this size. Default = 0 (turned off).""" streaming: bool = False """Whether to stream the output. Default = False.""" @property def _default_params(self) -> Mapping[str, Any]:
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/titan_takeoff.html
d3adf7627ac8-1
@property def _default_params(self) -> Mapping[str, Any]: """Get the default parameters for calling Titan Takeoff Server.""" params = { "generate_max_length": self.generate_max_length, "sampling_topk": self.sampling_topk, "sampling_topp": self.sampling_topp, "sampling_temperature": self.sampling_temperature, "repetition_penalty": self.repetition_penalty, "no_repeat_ngram_size": self.no_repeat_ngram_size, } return params @property def _llm_type(self) -> str: """Return type of llm.""" return "titan_takeoff" def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Call out to Titan Takeoff generate endpoint. Args: prompt: The prompt to pass into the model. stop: Optional list of stop words to use when generating. Returns: The string generated by the model. Example: .. code-block:: python prompt = "What is the capital of the United Kingdom?" response = model(prompt) """ try: if self.streaming: text_output = "" for chunk in self._stream( prompt=prompt, stop=stop, run_manager=run_manager, ): text_output += chunk.text return text_output url = f"{self.base_url}/generate" params = {"text": prompt, **self._default_params} response = requests.post(url, json=params)
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/titan_takeoff.html
d3adf7627ac8-2
response = requests.post(url, json=params) response.raise_for_status() response.encoding = "utf-8" text = "" if "message" in response.json(): text = response.json()["message"] else: raise ValueError("Something went wrong.") if stop is not None: text = enforce_stop_tokens(text, stop) return text except ConnectionError: raise ConnectionError( "Could not connect to Titan Takeoff server. \ Please make sure that the server is running." ) def _stream( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> Iterator[GenerationChunk]: """Call out to Titan Takeoff stream endpoint. Args: prompt: The prompt to pass into the model. stop: Optional list of stop words to use when generating. Returns: The string generated by the model. Yields: A dictionary like object containing a string token. Example: .. code-block:: python prompt = "What is the capital of the United Kingdom?" response = model(prompt) """ url = f"{self.base_url}/generate_stream" params = {"text": prompt, **self._default_params} response = requests.post(url, json=params, stream=True) response.encoding = "utf-8" for text in response.iter_content(chunk_size=1, decode_unicode=True): if text: chunk = GenerationChunk(text=text) yield chunk if run_manager: run_manager.on_llm_new_token(token=chunk.text)
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/titan_takeoff.html
d3adf7627ac8-3
if run_manager: run_manager.on_llm_new_token(token=chunk.text) @property def _identifying_params(self) -> Mapping[str, Any]: """Get the identifying parameters.""" return {"base_url": self.base_url, **{}, **self._default_params}
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/titan_takeoff.html
363e03dcb9c2-0
Source code for langchain.llms.promptlayer_openai import datetime from typing import Any, List, Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun, ) from langchain.llms.openai import OpenAI, OpenAIChat from langchain.schema import LLMResult [docs]class PromptLayerOpenAI(OpenAI): """PromptLayer OpenAI large language models. To use, you should have the ``openai`` and ``promptlayer`` python package installed, and the environment variable ``OPENAI_API_KEY`` and ``PROMPTLAYER_API_KEY`` set with your openAI API key and promptlayer key respectively. All parameters that can be passed to the OpenAI LLM can also be passed here. The PromptLayerOpenAI LLM adds two optional parameters: ``pl_tags``: List of strings to tag the request with. ``return_pl_id``: If True, the PromptLayer request ID will be returned in the ``generation_info`` field of the ``Generation`` object. Example: .. code-block:: python from langchain.llms import PromptLayerOpenAI openai = PromptLayerOpenAI(model_name="text-davinci-003") """ pl_tags: Optional[List[str]] return_pl_id: Optional[bool] = False def _generate( self, prompts: List[str], stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> LLMResult: """Call OpenAI generate and then call PromptLayer API to log the request."""
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html
363e03dcb9c2-1
"""Call OpenAI generate and then call PromptLayer API to log the request.""" from promptlayer.utils import get_api_key, promptlayer_api_request request_start_time = datetime.datetime.now().timestamp() generated_responses = super()._generate(prompts, stop, run_manager) request_end_time = datetime.datetime.now().timestamp() for i in range(len(prompts)): prompt = prompts[i] generation = generated_responses.generations[i][0] resp = { "text": generation.text, "llm_output": generated_responses.llm_output, } params = {**self._identifying_params, **kwargs} pl_request_id = promptlayer_api_request( "langchain.PromptLayerOpenAI", "langchain", [prompt], params, self.pl_tags, resp, request_start_time, request_end_time, get_api_key(), return_pl_id=self.return_pl_id, ) if self.return_pl_id: if generation.generation_info is None or not isinstance( generation.generation_info, dict ): generation.generation_info = {} generation.generation_info["pl_request_id"] = pl_request_id return generated_responses async def _agenerate( self, prompts: List[str], stop: Optional[List[str]] = None, run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, **kwargs: Any, ) -> LLMResult: from promptlayer.utils import get_api_key, promptlayer_api_request_async request_start_time = datetime.datetime.now().timestamp() generated_responses = await super()._agenerate(prompts, stop, run_manager)
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html
363e03dcb9c2-2
generated_responses = await super()._agenerate(prompts, stop, run_manager) request_end_time = datetime.datetime.now().timestamp() for i in range(len(prompts)): prompt = prompts[i] generation = generated_responses.generations[i][0] resp = { "text": generation.text, "llm_output": generated_responses.llm_output, } params = {**self._identifying_params, **kwargs} pl_request_id = await promptlayer_api_request_async( "langchain.PromptLayerOpenAI.async", "langchain", [prompt], params, self.pl_tags, resp, request_start_time, request_end_time, get_api_key(), return_pl_id=self.return_pl_id, ) if self.return_pl_id: if generation.generation_info is None or not isinstance( generation.generation_info, dict ): generation.generation_info = {} generation.generation_info["pl_request_id"] = pl_request_id return generated_responses [docs]class PromptLayerOpenAIChat(OpenAIChat): """Wrapper around OpenAI large language models. To use, you should have the ``openai`` and ``promptlayer`` python package installed, and the environment variable ``OPENAI_API_KEY`` and ``PROMPTLAYER_API_KEY`` set with your openAI API key and promptlayer key respectively. All parameters that can be passed to the OpenAIChat LLM can also be passed here. The PromptLayerOpenAIChat adds two optional parameters: ``pl_tags``: List of strings to tag the request with.
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html
363e03dcb9c2-3
parameters: ``pl_tags``: List of strings to tag the request with. ``return_pl_id``: If True, the PromptLayer request ID will be returned in the ``generation_info`` field of the ``Generation`` object. Example: .. code-block:: python from langchain.llms import PromptLayerOpenAIChat openaichat = PromptLayerOpenAIChat(model_name="gpt-3.5-turbo") """ pl_tags: Optional[List[str]] return_pl_id: Optional[bool] = False def _generate( self, prompts: List[str], stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> LLMResult: """Call OpenAI generate and then call PromptLayer API to log the request.""" from promptlayer.utils import get_api_key, promptlayer_api_request request_start_time = datetime.datetime.now().timestamp() generated_responses = super()._generate(prompts, stop, run_manager) request_end_time = datetime.datetime.now().timestamp() for i in range(len(prompts)): prompt = prompts[i] generation = generated_responses.generations[i][0] resp = { "text": generation.text, "llm_output": generated_responses.llm_output, } params = {**self._identifying_params, **kwargs} pl_request_id = promptlayer_api_request( "langchain.PromptLayerOpenAIChat", "langchain", [prompt], params, self.pl_tags, resp, request_start_time, request_end_time,
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html
363e03dcb9c2-4
resp, request_start_time, request_end_time, get_api_key(), return_pl_id=self.return_pl_id, ) if self.return_pl_id: if generation.generation_info is None or not isinstance( generation.generation_info, dict ): generation.generation_info = {} generation.generation_info["pl_request_id"] = pl_request_id return generated_responses async def _agenerate( self, prompts: List[str], stop: Optional[List[str]] = None, run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, **kwargs: Any, ) -> LLMResult: from promptlayer.utils import get_api_key, promptlayer_api_request_async request_start_time = datetime.datetime.now().timestamp() generated_responses = await super()._agenerate(prompts, stop, run_manager) request_end_time = datetime.datetime.now().timestamp() for i in range(len(prompts)): prompt = prompts[i] generation = generated_responses.generations[i][0] resp = { "text": generation.text, "llm_output": generated_responses.llm_output, } params = {**self._identifying_params, **kwargs} pl_request_id = await promptlayer_api_request_async( "langchain.PromptLayerOpenAIChat.async", "langchain", [prompt], params, self.pl_tags, resp, request_start_time, request_end_time, get_api_key(), return_pl_id=self.return_pl_id, ) if self.return_pl_id: if generation.generation_info is None or not isinstance( generation.generation_info, dict
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html
363e03dcb9c2-5
generation.generation_info, dict ): generation.generation_info = {} generation.generation_info["pl_request_id"] = pl_request_id return generated_responses
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html
c860d32942c2-0
Source code for langchain.llms.manifest from typing import Any, Dict, List, Mapping, Optional from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.pydantic_v1 import Extra, root_validator [docs]class ManifestWrapper(LLM): """HazyResearch's Manifest library.""" client: Any #: :meta private: llm_kwargs: Optional[Dict] = None class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that python package exists in environment.""" try: from manifest import Manifest if not isinstance(values["client"], Manifest): raise ValueError except ImportError: raise ImportError( "Could not import manifest python package. " "Please install it with `pip install manifest-ml`." ) return values @property def _identifying_params(self) -> Mapping[str, Any]: kwargs = self.llm_kwargs or {} return { **self.client.client_pool.get_current_client().get_model_params(), **kwargs, } @property def _llm_type(self) -> str: """Return type of llm.""" return "manifest" def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Call out to LLM through Manifest.""" if stop is not None and len(stop) != 1: raise NotImplementedError(
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/manifest.html
c860d32942c2-1
if stop is not None and len(stop) != 1: raise NotImplementedError( f"Manifest currently only supports a single stop token, got {stop}" ) params = self.llm_kwargs or {} params = {**params, **kwargs} if stop is not None: params["stop_token"] = stop return self.client.run(prompt, **params)
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/manifest.html
02030726671a-0
Source code for langchain.llms.ai21 from typing import Any, Dict, List, Optional, cast import requests from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.pydantic_v1 import BaseModel, Extra, SecretStr, root_validator from langchain.utils import convert_to_secret_str, get_from_dict_or_env [docs]class AI21PenaltyData(BaseModel): """Parameters for AI21 penalty data.""" scale: int = 0 applyToWhitespaces: bool = True applyToPunctuations: bool = True applyToNumbers: bool = True applyToStopwords: bool = True applyToEmojis: bool = True [docs]class AI21(LLM): """AI21 large language models. To use, you should have the environment variable ``AI21_API_KEY`` set with your API key or pass it as a named parameter to the constructor. Example: .. code-block:: python from langchain.llms import AI21 ai21 = AI21(ai21_api_key="my-api-key", model="j2-jumbo-instruct") """ model: str = "j2-jumbo-instruct" """Model name to use.""" temperature: float = 0.7 """What sampling temperature to use.""" maxTokens: int = 256 """The maximum number of tokens to generate in the completion.""" minTokens: int = 0 """The minimum number of tokens to generate in the completion.""" topP: float = 1.0 """Total probability mass of tokens to consider at each step.""" presencePenalty: AI21PenaltyData = AI21PenaltyData()
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/ai21.html
02030726671a-1
presencePenalty: AI21PenaltyData = AI21PenaltyData() """Penalizes repeated tokens.""" countPenalty: AI21PenaltyData = AI21PenaltyData() """Penalizes repeated tokens according to count.""" frequencyPenalty: AI21PenaltyData = AI21PenaltyData() """Penalizes repeated tokens according to frequency.""" numResults: int = 1 """How many completions to generate for each prompt.""" logitBias: Optional[Dict[str, float]] = None """Adjust the probability of specific tokens being generated.""" ai21_api_key: Optional[SecretStr] = None stop: Optional[List[str]] = None base_url: Optional[str] = None """Base url to use, if None decides based on model name.""" class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key exists in environment.""" ai21_api_key = convert_to_secret_str( get_from_dict_or_env(values, "ai21_api_key", "AI21_API_KEY") ) values["ai21_api_key"] = ai21_api_key return values @property def _default_params(self) -> Dict[str, Any]: """Get the default parameters for calling AI21 API.""" return { "temperature": self.temperature, "maxTokens": self.maxTokens, "minTokens": self.minTokens, "topP": self.topP, "presencePenalty": self.presencePenalty.dict(), "countPenalty": self.countPenalty.dict(),
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/ai21.html
02030726671a-2
"countPenalty": self.countPenalty.dict(), "frequencyPenalty": self.frequencyPenalty.dict(), "numResults": self.numResults, "logitBias": self.logitBias, } @property def _identifying_params(self) -> Dict[str, Any]: """Get the identifying parameters.""" return {**{"model": self.model}, **self._default_params} @property def _llm_type(self) -> str: """Return type of llm.""" return "ai21" def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Call out to AI21's complete endpoint. Args: prompt: The prompt to pass into the model. stop: Optional list of stop words to use when generating. Returns: The string generated by the model. Example: .. code-block:: python response = ai21("Tell me a joke.") """ 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: stop = self.stop elif stop is None: stop = [] if self.base_url is not None: base_url = self.base_url else: if self.model in ("j1-grande-instruct",): base_url = "https://api.ai21.com/studio/v1/experimental" else: base_url = "https://api.ai21.com/studio/v1"
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/ai21.html
02030726671a-3
base_url = "https://api.ai21.com/studio/v1" params = {**self._default_params, **kwargs} self.ai21_api_key = cast(SecretStr, self.ai21_api_key) response = requests.post( url=f"{base_url}/{self.model}/complete", headers={"Authorization": f"Bearer {self.ai21_api_key.get_secret_value()}"}, json={"prompt": prompt, "stopSequences": stop, **params}, ) if response.status_code != 200: optional_detail = response.json().get("error") raise ValueError( f"AI21 /complete call failed with status code {response.status_code}." f" Details: {optional_detail}" ) response_json = response.json() return response_json["completions"][0]["data"]["text"]
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/ai21.html
0e61e5288e31-0
Source code for langchain.llms.mlflow_ai_gateway from __future__ import annotations from typing import Any, Dict, List, Mapping, Optional from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.pydantic_v1 import BaseModel, Extra # Ignoring type because below is valid pydantic code # Unexpected keyword argument "extra" for "__init_subclass__" of "object" [docs]class Params(BaseModel, extra=Extra.allow): # type: ignore[call-arg] """Parameters for the MLflow AI Gateway LLM.""" temperature: float = 0.0 candidate_count: int = 1 """The number of candidates to return.""" stop: Optional[List[str]] = None max_tokens: Optional[int] = None [docs]class MlflowAIGateway(LLM): """ Wrapper around completions LLMs in the MLflow AI Gateway. To use, you should have the ``mlflow[gateway]`` python package installed. For more information, see https://mlflow.org/docs/latest/gateway/index.html. Example: .. code-block:: python from langchain.llms import MlflowAIGateway completions = MlflowAIGateway( gateway_uri="<your-mlflow-ai-gateway-uri>", route="<your-mlflow-ai-gateway-completions-route>", params={ "temperature": 0.1 } ) """ route: str gateway_uri: Optional[str] = None params: Optional[Params] = None def __init__(self, **kwargs: Any): try: import mlflow.gateway
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/mlflow_ai_gateway.html
0e61e5288e31-1
try: import mlflow.gateway except ImportError as e: raise ImportError( "Could not import `mlflow.gateway` module. " "Please install it with `pip install mlflow[gateway]`." ) from e super().__init__(**kwargs) if self.gateway_uri: mlflow.gateway.set_gateway_uri(self.gateway_uri) @property def _default_params(self) -> Dict[str, Any]: params: Dict[str, Any] = { "gateway_uri": self.gateway_uri, "route": self.route, **(self.params.dict() if self.params else {}), } return params @property def _identifying_params(self) -> Mapping[str, Any]: return self._default_params def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: try: import mlflow.gateway except ImportError as e: raise ImportError( "Could not import `mlflow.gateway` module. " "Please install it with `pip install mlflow[gateway]`." ) from e data: Dict[str, Any] = { "prompt": prompt, **(self.params.dict() if self.params else {}), } if s := (stop or (self.params.stop if self.params else None)): data["stop"] = s resp = mlflow.gateway.query(self.route, data=data) return resp["candidates"][0]["text"] @property def _llm_type(self) -> str:
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/mlflow_ai_gateway.html
0e61e5288e31-2
@property def _llm_type(self) -> str: return "mlflow-ai-gateway"
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/mlflow_ai_gateway.html
3f746b5cba90-0
Source code for langchain.llms.mosaicml from typing import Any, Dict, List, Mapping, Optional import requests from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens from langchain.pydantic_v1 import Extra, root_validator from langchain.utils import get_from_dict_or_env INSTRUCTION_KEY = "### Instruction:" RESPONSE_KEY = "### Response:" INTRO_BLURB = ( "Below is an instruction that describes a task. " "Write a response that appropriately completes the request." ) PROMPT_FOR_GENERATION_FORMAT = """{intro} {instruction_key} {instruction} {response_key} """.format( intro=INTRO_BLURB, instruction_key=INSTRUCTION_KEY, instruction="{instruction}", response_key=RESPONSE_KEY, ) [docs]class MosaicML(LLM): """MosaicML LLM service. To use, you should have the environment variable ``MOSAICML_API_TOKEN`` set with your API token, or pass it as a named parameter to the constructor. Example: .. code-block:: python from langchain.llms import MosaicML endpoint_url = ( "https://models.hosted-on.mosaicml.hosting/mpt-7b-instruct/v1/predict" ) mosaic_llm = MosaicML( endpoint_url=endpoint_url, mosaicml_api_token="my-api-key" ) """ endpoint_url: str = ( "https://models.hosted-on.mosaicml.hosting/mpt-7b-instruct/v1/predict" )
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html
3f746b5cba90-1
) """Endpoint URL to use.""" inject_instruction_format: bool = False """Whether to inject the instruction format into the prompt.""" model_kwargs: Optional[dict] = None """Keyword arguments to pass to the model.""" retry_sleep: float = 1.0 """How long to try sleeping for if a rate limit is encountered""" mosaicml_api_token: Optional[str] = None class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" mosaicml_api_token = get_from_dict_or_env( values, "mosaicml_api_token", "MOSAICML_API_TOKEN" ) values["mosaicml_api_token"] = mosaicml_api_token return values @property def _identifying_params(self) -> Mapping[str, Any]: """Get the identifying parameters.""" _model_kwargs = self.model_kwargs or {} return { **{"endpoint_url": self.endpoint_url}, **{"model_kwargs": _model_kwargs}, } @property def _llm_type(self) -> str: """Return type of llm.""" return "mosaic" def _transform_prompt(self, prompt: str) -> str: """Transform prompt.""" if self.inject_instruction_format: prompt = PROMPT_FOR_GENERATION_FORMAT.format( instruction=prompt, ) return prompt def _call( self, prompt: str, stop: Optional[List[str]] = None,
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html
3f746b5cba90-2
prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, is_retry: bool = False, **kwargs: Any, ) -> str: """Call out to a MosaicML LLM inference endpoint. Args: prompt: The prompt to pass into the model. stop: Optional list of stop words to use when generating. Returns: The string generated by the model. Example: .. code-block:: python response = mosaic_llm("Tell me a joke.") """ _model_kwargs = self.model_kwargs or {} prompt = self._transform_prompt(prompt) payload = {"inputs": [prompt]} payload.update(_model_kwargs) payload.update(kwargs) # HTTP headers for authorization headers = { "Authorization": f"{self.mosaicml_api_token}", "Content-Type": "application/json", } # send request try: response = requests.post(self.endpoint_url, headers=headers, json=payload) except requests.exceptions.RequestException as e: raise ValueError(f"Error raised by inference endpoint: {e}") try: if response.status_code == 429: if not is_retry: import time time.sleep(self.retry_sleep) return self._call(prompt, stop, run_manager, is_retry=True) raise ValueError( f"Error raised by inference API: rate limit exceeded.\nResponse: " f"{response.text}" ) parsed_response = response.json() # The inference API has changed a couple of times, so we add some handling # to be robust to multiple response formats.
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html
3f746b5cba90-3
# to be robust to multiple response formats. if isinstance(parsed_response, dict): output_keys = ["data", "output", "outputs"] for key in output_keys: if key in parsed_response: output_item = parsed_response[key] break else: raise ValueError( f"No valid key ({', '.join(output_keys)}) in response:" f" {parsed_response}" ) if isinstance(output_item, list): text = output_item[0] else: text = output_item else: raise ValueError(f"Unexpected response type: {parsed_response}") # Older versions of the API include the input in the output response if text.startswith(prompt): text = text[len(prompt) :] except requests.exceptions.JSONDecodeError as e: raise ValueError( f"Error raised by inference API: {e}.\nResponse: {response.text}" ) # TODO: replace when MosaicML supports custom stop tokens natively if stop is not None: text = enforce_stop_tokens(text, stop) return text
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html
4d2648316a32-0
Source code for langchain.llms.gradient_ai import asyncio import logging from concurrent.futures import ThreadPoolExecutor from typing import Any, Dict, List, Mapping, Optional, Sequence, TypedDict import aiohttp import requests from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun, ) from langchain.llms.base import BaseLLM from langchain.llms.utils import enforce_stop_tokens from langchain.pydantic_v1 import Extra, Field, root_validator from langchain.schema import Generation, LLMResult from langchain.utils import get_from_dict_or_env [docs]class TrainResult(TypedDict): """Train result.""" loss: float [docs]class GradientLLM(BaseLLM): """Gradient.ai LLM Endpoints. GradientLLM is a class to interact with LLMs on gradient.ai To use, set the environment variable ``GRADIENT_ACCESS_TOKEN`` with your API token and ``GRADIENT_WORKSPACE_ID`` for your gradient workspace, or alternatively provide them as keywords to the constructor of this class. Example: .. code-block:: python from langchain.llms import GradientLLM GradientLLM( model="99148c6d-c2a0-4fbe-a4a7-e7c05bdb8a09_base_ml_model", model_kwargs={ "max_generated_token_count": 128, "temperature": 0.75, "top_p": 0.95, "top_k": 20, "stop": [], }, gradient_workspace_id="12345614fc0_workspace", gradient_access_token="gradientai-access_token", ) """
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gradient_ai.html
4d2648316a32-1
gradient_access_token="gradientai-access_token", ) """ model_id: str = Field(alias="model", min_length=2) "Underlying gradient.ai model id (base or fine-tuned)." gradient_workspace_id: Optional[str] = None "Underlying gradient.ai workspace_id." gradient_access_token: Optional[str] = None """gradient.ai API Token, which can be generated by going to https://auth.gradient.ai/select-workspace and selecting "Access tokens" under the profile drop-down. """ model_kwargs: Optional[dict] = None """Keyword arguments to pass to the model.""" gradient_api_url: str = "https://api.gradient.ai/api" """Endpoint URL to use.""" aiosession: Optional[aiohttp.ClientSession] = None #: :meta private: """ClientSession, private, subject to change in upcoming releases.""" # LLM call kwargs class Config: """Configuration for this pydantic object.""" allow_population_by_field_name = True extra = Extra.forbid @root_validator(allow_reuse=True) def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" values["gradient_access_token"] = get_from_dict_or_env( values, "gradient_access_token", "GRADIENT_ACCESS_TOKEN" ) values["gradient_workspace_id"] = get_from_dict_or_env( values, "gradient_workspace_id", "GRADIENT_WORKSPACE_ID" ) if ( values["gradient_access_token"] is None or len(values["gradient_access_token"]) < 10 ):
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gradient_ai.html
4d2648316a32-2
or len(values["gradient_access_token"]) < 10 ): raise ValueError("env variable `GRADIENT_ACCESS_TOKEN` must be set") if ( values["gradient_workspace_id"] is None or len(values["gradient_access_token"]) < 3 ): raise ValueError("env variable `GRADIENT_WORKSPACE_ID` must be set") if values["model_kwargs"]: kw = values["model_kwargs"] if not 0 <= kw.get("temperature", 0.5) <= 1: raise ValueError("`temperature` must be in the range [0.0, 1.0]") if not 0 <= kw.get("top_p", 0.5) <= 1: raise ValueError("`top_p` must be in the range [0.0, 1.0]") if 0 >= kw.get("top_k", 0.5): raise ValueError("`top_k` must be positive") if 0 >= kw.get("max_generated_token_count", 1): raise ValueError("`max_generated_token_count` must be positive") values["gradient_api_url"] = get_from_dict_or_env( values, "gradient_api_url", "GRADIENT_API_URL" ) try: import gradientai # noqa except ImportError: logging.warning( "DeprecationWarning: `GradientLLM` will use " "`pip install gradientai` in future releases of langchain." ) except Exception: pass return values @property def _identifying_params(self) -> Mapping[str, Any]: """Get the identifying parameters.""" _model_kwargs = self.model_kwargs or {} return {
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gradient_ai.html
4d2648316a32-3
_model_kwargs = self.model_kwargs or {} return { **{"gradient_api_url": self.gradient_api_url}, **{"model_kwargs": _model_kwargs}, } @property def _llm_type(self) -> str: """Return type of llm.""" return "gradient" def _kwargs_post_fine_tune_request( self, inputs: Sequence[str], kwargs: Mapping[str, Any] ) -> Mapping[str, Any]: """Build the kwargs for the Post request, used by sync Args: prompt (str): prompt used in query kwargs (dict): model kwargs in payload Returns: Dict[str, Union[str,dict]]: _description_ """ _model_kwargs = self.model_kwargs or {} _params = {**_model_kwargs, **kwargs} multipliers = _params.get("multipliers", None) return dict( url=f"{self.gradient_api_url}/models/{self.model_id}/fine-tune", headers={ "authorization": f"Bearer {self.gradient_access_token}", "x-gradient-workspace-id": f"{self.gradient_workspace_id}", "accept": "application/json", "content-type": "application/json", }, json=dict( samples=tuple( { "inputs": input, } for input in inputs ) if multipliers is None else tuple( { "inputs": input, "fineTuningParameters": { "multiplier": multiplier, }, } for input, multiplier in zip(inputs, multipliers) ), ), ) def _kwargs_post_request(
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gradient_ai.html
4d2648316a32-4
), ), ) def _kwargs_post_request( self, prompt: str, kwargs: Mapping[str, Any] ) -> Mapping[str, Any]: """Build the kwargs for the Post request, used by sync Args: prompt (str): prompt used in query kwargs (dict): model kwargs in payload Returns: Dict[str, Union[str,dict]]: _description_ """ _model_kwargs = self.model_kwargs or {} _params = {**_model_kwargs, **kwargs} return dict( url=f"{self.gradient_api_url}/models/{self.model_id}/complete", headers={ "authorization": f"Bearer {self.gradient_access_token}", "x-gradient-workspace-id": f"{self.gradient_workspace_id}", "accept": "application/json", "content-type": "application/json", }, json=dict( query=prompt, maxGeneratedTokenCount=_params.get("max_generated_token_count", None), temperature=_params.get("temperature", None), topK=_params.get("top_k", None), topP=_params.get("top_p", None), ), ) def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Call to Gradients API `model/{id}/complete`. Args: prompt: The prompt to pass into the model. stop: Optional list of stop words to use when generating. Returns: The string generated by the model. """ try:
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gradient_ai.html
4d2648316a32-5
Returns: The string generated by the model. """ try: response = requests.post(**self._kwargs_post_request(prompt, kwargs)) if response.status_code != 200: raise Exception( f"Gradient returned an unexpected response with status " f"{response.status_code}: {response.text}" ) except requests.exceptions.RequestException as e: raise Exception(f"RequestException while calling Gradient Endpoint: {e}") text = response.json()["generatedOutput"] if stop is not None: # Apply stop tokens when making calls to Gradient text = enforce_stop_tokens(text, stop) return text async def _acall( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Async Call to Gradients API `model/{id}/complete`. Args: prompt: The prompt to pass into the model. stop: Optional list of stop words to use when generating. Returns: The string generated by the model. """ if not self.aiosession: async with aiohttp.ClientSession() as session: async with session.post( **self._kwargs_post_request(prompt=prompt, kwargs=kwargs) ) as response: if response.status != 200: raise Exception( f"Gradient returned an unexpected response with status " f"{response.status}: {response.text}" ) text = (await response.json())["generatedOutput"] else: async with self.aiosession.post(
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gradient_ai.html
4d2648316a32-6
else: async with self.aiosession.post( **self._kwargs_post_request(prompt=prompt, kwargs=kwargs) ) as response: if response.status != 200: raise Exception( f"Gradient returned an unexpected response with status " f"{response.status}: {response.text}" ) text = (await response.json())["generatedOutput"] if stop is not None: # Apply stop tokens when making calls to Gradient text = enforce_stop_tokens(text, stop) return text def _generate( self, prompts: List[str], stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> LLMResult: """Run the LLM on the given prompt and input.""" # same thing with threading def _inner_generate(prompt: str) -> List[Generation]: return [ Generation( text=self._call( prompt=prompt, stop=stop, run_manager=run_manager, **kwargs ) ) ] if len(prompts) <= 1: generations = list(map(_inner_generate, prompts)) else: with ThreadPoolExecutor(min(8, len(prompts))) as p: generations = list(p.map(_inner_generate, prompts)) return LLMResult(generations=generations) async def _agenerate( self, prompts: List[str], stop: Optional[List[str]] = None, run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, **kwargs: Any, ) -> LLMResult:
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gradient_ai.html
4d2648316a32-7
**kwargs: Any, ) -> LLMResult: """Run the LLM on the given prompt and input.""" generations = [] for generation in asyncio.gather( [self._acall(prompt, stop=stop, run_manager=run_manager, **kwargs)] for prompt in prompts ): generations.append([Generation(text=generation)]) return LLMResult(generations=generations) [docs] def train_unsupervised( self, inputs: Sequence[str], **kwargs: Any, ) -> TrainResult: try: response = requests.post( **self._kwargs_post_fine_tune_request(inputs, kwargs) ) if response.status_code != 200: raise Exception( f"Gradient returned an unexpected response with status " f"{response.status_code}: {response.text}" ) except requests.exceptions.RequestException as e: raise Exception(f"RequestException while calling Gradient Endpoint: {e}") response_json = response.json() loss = response_json["sumLoss"] / response_json["numberOfTrainableTokens"] return TrainResult(loss=loss) [docs] async def atrain_unsupervised( self, inputs: Sequence[str], **kwargs: Any, ) -> TrainResult: if not self.aiosession: async with aiohttp.ClientSession() as session: async with session.post( **self._kwargs_post_fine_tune_request(inputs, kwargs) ) as response: if response.status != 200: raise Exception( f"Gradient returned an unexpected response with status " f"{response.status}: {response.text}" )
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gradient_ai.html
4d2648316a32-8
f"{response.status}: {response.text}" ) response_json = await response.json() loss = ( response_json["sumLoss"] / response_json["numberOfTrainableTokens"] ) else: async with self.aiosession.post( **self._kwargs_post_fine_tune_request(inputs, kwargs) ) as response: if response.status != 200: raise Exception( f"Gradient returned an unexpected response with status " f"{response.status}: {response.text}" ) response_json = await response.json() loss = ( response_json["sumLoss"] / response_json["numberOfTrainableTokens"] ) return TrainResult(loss=loss)
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gradient_ai.html
bb51a9ee8dd6-0
Source code for langchain.llms.bedrock import json import warnings from abc import ABC from typing import Any, Dict, Iterator, List, Mapping, Optional from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens from langchain.pydantic_v1 import BaseModel, Extra, root_validator from langchain.schema.output import GenerationChunk from langchain.utilities.anthropic import ( get_num_tokens_anthropic, get_token_ids_anthropic, ) from langchain.utils import get_from_dict_or_env HUMAN_PROMPT = "\n\nHuman:" ASSISTANT_PROMPT = "\n\nAssistant:" ALTERNATION_ERROR = ( "Error: Prompt must alternate between '\n\nHuman:' and '\n\nAssistant:'." ) def _add_newlines_before_ha(input_text: str) -> str: new_text = input_text for word in ["Human:", "Assistant:"]: new_text = new_text.replace(word, "\n\n" + word) for i in range(2): new_text = new_text.replace("\n\n\n" + word, "\n\n" + word) return new_text def _human_assistant_format(input_text: str) -> str: if input_text.count("Human:") == 0 or ( input_text.find("Human:") > input_text.find("Assistant:") and "Assistant:" in input_text ): input_text = HUMAN_PROMPT + " " + input_text # SILENT CORRECTION if input_text.count("Assistant:") == 0: input_text = input_text + ASSISTANT_PROMPT # SILENT CORRECTION
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html
bb51a9ee8dd6-1
if input_text[: len("Human:")] == "Human:": input_text = "\n\n" + input_text input_text = _add_newlines_before_ha(input_text) count = 0 # track alternation for i in range(len(input_text)): if input_text[i : i + len(HUMAN_PROMPT)] == HUMAN_PROMPT: if count % 2 == 0: count += 1 else: warnings.warn(ALTERNATION_ERROR + f" Received {input_text}") if input_text[i : i + len(ASSISTANT_PROMPT)] == ASSISTANT_PROMPT: if count % 2 == 1: count += 1 else: warnings.warn(ALTERNATION_ERROR + f" Received {input_text}") if count % 2 == 1: # Only saw Human, no Assistant input_text = input_text + ASSISTANT_PROMPT # SILENT CORRECTION return input_text [docs]class LLMInputOutputAdapter: """Adapter class to prepare the inputs from Langchain to a format that LLM model expects. It also provides helper function to extract the generated text from the model response.""" provider_to_output_key_map = { "anthropic": "completion", "amazon": "outputText", "cohere": "text", } [docs] @classmethod def prepare_input( cls, provider: str, prompt: str, model_kwargs: Dict[str, Any] ) -> Dict[str, Any]: input_body = {**model_kwargs} if provider == "anthropic": input_body["prompt"] = _human_assistant_format(prompt)
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html
bb51a9ee8dd6-2
input_body["prompt"] = _human_assistant_format(prompt) elif provider == "ai21" or provider == "cohere": input_body["prompt"] = prompt elif provider == "amazon": input_body = dict() input_body["inputText"] = prompt input_body["textGenerationConfig"] = {**model_kwargs} else: input_body["inputText"] = prompt if provider == "anthropic" and "max_tokens_to_sample" not in input_body: input_body["max_tokens_to_sample"] = 256 return input_body [docs] @classmethod def prepare_output(cls, provider: str, response: Any) -> str: if provider == "anthropic": response_body = json.loads(response.get("body").read().decode()) return response_body.get("completion") else: response_body = json.loads(response.get("body").read()) if provider == "ai21": return response_body.get("completions")[0].get("data").get("text") elif provider == "cohere": return response_body.get("generations")[0].get("text") else: return response_body.get("results")[0].get("outputText") [docs] @classmethod def prepare_output_stream( cls, provider: str, response: Any, stop: Optional[List[str]] = None ) -> Iterator[GenerationChunk]: stream = response.get("body") if not stream: return if provider not in cls.provider_to_output_key_map: raise ValueError( f"Unknown streaming response output key for provider: {provider}" ) for event in stream: chunk = event.get("chunk")
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html