id
stringlengths
14
16
text
stringlengths
36
2.73k
source
stringlengths
49
117
21dde289d2bc-7
) else: raise ValueError( "Must specify either endpoint_name or cluster_id/cluster_driver_port." ) @property def _llm_type(self) -> str: """Return type of llm.""" return "databricks" def _call( self, prompt: str, stop: O...
https://python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
5460f2ff577b-0
Source code for langchain.llms.fake """Fake LLM wrapper for testing purposes.""" from typing import Any, List, Mapping, Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun, ) from langchain.llms.base import LLM [docs]class FakeListLLM(LLM): """Fake LLM ...
https://python.langchain.com/en/latest/_modules/langchain/llms/fake.html
54f028dac958-0
Source code for langchain.llms.cohere """Wrapper around Cohere APIs.""" from __future__ import annotations import logging from typing import Any, Callable, Dict, List, Optional from pydantic import Extra, root_validator from tenacity import ( before_sleep_log, retry, retry_if_exception_type, stop_after_...
https://python.langchain.com/en/latest/_modules/langchain/llms/cohere.html
54f028dac958-1
"""Wrapper around Cohere large language models. To use, you should have the ``cohere`` python package installed, and the environment variable ``COHERE_API_KEY`` set with your API key, or pass it as a named parameter to the constructor. Example: .. code-block:: python from langchain.l...
https://python.langchain.com/en/latest/_modules/langchain/llms/cohere.html
54f028dac958-2
extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" cohere_api_key = get_from_dict_or_env( values, "cohere_api_key", "COHERE_API_KEY" ) try: impor...
https://python.langchain.com/en/latest/_modules/langchain/llms/cohere.html
54f028dac958-3
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 = cohere("Tell me a joke.") """ ...
https://python.langchain.com/en/latest/_modules/langchain/llms/cohere.html
fcda3b7ab57b-0
Source code for langchain.llms.vertexai """Wrapper around Google VertexAI models.""" from typing import TYPE_CHECKING, Any, Dict, List, Optional from pydantic import BaseModel, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils i...
https://python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html
fcda3b7ab57b-1
"The default custom credentials (google.auth.credentials.Credentials) to use " "when making API calls. If not provided, credentials will be ascertained from " "the environment." @property def _default_params(self) -> Dict[str, Any]: base_params = { "temperature": self.temperature, ...
https://python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html
fcda3b7ab57b-2
"The name of a tuned model, if it's provided, model_name is ignored." @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that the python package exists in environment.""" cls._try_init_vertexai(values) try: from vertexai.preview.language_models...
https://python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html
372ecf19248d-0
Source code for langchain.llms.predictionguard """Wrapper around Prediction Guard APIs.""" import logging from typing import Any, Dict, List, Optional from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils...
https://python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html
372ecf19248d-1
"""Your Prediction Guard access token.""" stop: Optional[List[str]] = None class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that the access token and python package ...
https://python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html
372ecf19248d-2
Returns: The string generated by the model. Example: .. code-block:: python response = pgllm("Tell me a joke.") """ import predictionguard as pg params = self._default_params if self.stop is not None and stop is not None: raise ...
https://python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html
3e23e4c538bf-0
Source code for langchain.llms.petals """Wrapper around Petals API.""" import logging from typing import Any, Dict, List, Mapping, Optional from pydantic import Extra, Field, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils imp...
https://python.langchain.com/en/latest/_modules/langchain/llms/petals.html
3e23e4c538bf-1
"""Whether or not to use sampling; use greedy decoding otherwise.""" 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.""...
https://python.langchain.com/en/latest/_modules/langchain/llms/petals.html
3e23e4c538bf-2
from petals import DistributedBloomForCausalLM from transformers import BloomTokenizerFast model_name = values["model_name"] values["tokenizer"] = BloomTokenizerFast.from_pretrained(model_name) values["client"] = DistributedBloomForCausalLM.from_pretrained(model_name) ...
https://python.langchain.com/en/latest/_modules/langchain/llms/petals.html
3e23e4c538bf-3
"""Call the Petals API.""" params = self._default_params 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...
https://python.langchain.com/en/latest/_modules/langchain/llms/petals.html
8a3f0e10b1ca-0
Source code for langchain.llms.replicate """Wrapper around Replicate API.""" import logging from typing import Any, Dict, List, Mapping, Optional from pydantic import Extra, Field, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.utils im...
https://python.langchain.com/en/latest/_modules/langchain/llms/replicate.html
8a3f0e10b1ca-1
"""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 ...
https://python.langchain.com/en/latest/_modules/langchain/llms/replicate.html
8a3f0e10b1ca-2
raise ImportError( "Could not import replicate python package. " "Please install it with `pip install replicate`." ) # get the model and version model_str, version_str = self.model.split(":") model = replicate_python.models.get(model_str) versi...
https://python.langchain.com/en/latest/_modules/langchain/llms/replicate.html
b56a5c174365-0
Source code for langchain.llms.deepinfra """Wrapper around DeepInfra APIs.""" from typing import Any, Dict, List, Mapping, Optional import requests from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils im...
https://python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html
b56a5c174365-1
return values @property def _identifying_params(self) -> Mapping[str, Any]: """Get the identifying parameters.""" return { **{"model_id": self.model_id}, **{"model_kwargs": self.model_kwargs}, } @property def _llm_type(self) -> str: """Return type ...
https://python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html
b56a5c174365-2
% (res.status_code, res.text) ) try: t = res.json() text = t["results"][0]["generated_text"] except requests.exceptions.JSONDecodeError as e: raise ValueError( f"Error raised by inference API: {e}.\nResponse: {res.text}" ) ...
https://python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html
d73cbb9a2c56-0
Source code for langchain.llms.baseten """Wrapper around Baseten deployed model API.""" import logging from typing import Any, Dict, List, Mapping, Optional from pydantic import Field from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM logger = logging.getLogger(__name__...
https://python.langchain.com/en/latest/_modules/langchain/llms/baseten.html
d73cbb9a2c56-1
"""Return type of model.""" return "baseten" def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, ) -> str: """Call to Baseten deployed model endpoint.""" try: import baseten ...
https://python.langchain.com/en/latest/_modules/langchain/llms/baseten.html
df79ddfb6efb-0
Source code for langchain.llms.ai21 """Wrapper around AI21 APIs.""" from typing import Any, Dict, List, Optional import requests from pydantic import BaseModel, Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.utils import get_from...
https://python.langchain.com/en/latest/_modules/langchain/llms/ai21.html
df79ddfb6efb-1
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.""" logitBia...
https://python.langchain.com/en/latest/_modules/langchain/llms/ai21.html
df79ddfb6efb-2
"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" ...
https://python.langchain.com/en/latest/_modules/langchain/llms/ai21.html
df79ddfb6efb-3
headers={"Authorization": f"Bearer {self.ai21_api_key}"}, json={"prompt": prompt, "stopSequences": stop, **self._default_params}, ) if response.status_code != 200: optional_detail = response.json().get("error") raise ValueError( f"AI21 /complete call f...
https://python.langchain.com/en/latest/_modules/langchain/llms/ai21.html
31e2cb48f314-0
Source code for langchain.llms.openlm from typing import Any, Dict from pydantic import root_validator from langchain.llms.openai import BaseOpenAI [docs]class OpenLM(BaseOpenAI): @property def _invocation_params(self) -> Dict[str, Any]: return {**{"model": self.model_name}, **super()._invocation_params...
https://python.langchain.com/en/latest/_modules/langchain/llms/openlm.html
28b3748908ef-0
Source code for langchain.llms.self_hosted """Run model inference on self-hosted remote hardware.""" import importlib.util import logging import pickle from typing import Any, Callable, List, Mapping, Optional from pydantic import Extra from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llm...
https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
28b3748908ef-1
) if device < 0 and cuda_device_count > 0: logger.warning( "Device has %d GPUs available. " "Provide device={deviceId} to `from_model_id` to use available" "GPUs for execution. deviceId is -1 for CPU and " "can be a positive integer ass...
https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
28b3748908ef-2
llm = SelfHostedPipeline( model_load_fn=load_pipeline, hardware=gpu, model_reqs=model_reqs, inference_fn=inference_fn ) Example for <2GB model (can be serialized and sent directly to the server): .. code-block:: python from langchain.ll...
https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
28b3748908ef-3
load_fn_kwargs: Optional[dict] = None """Key word arguments to pass to the model load function.""" model_reqs: List[str] = ["./", "torch"] """Requirements to install on hardware to inference the model.""" class Config: """Configuration for this pydantic object.""" extra = Extra.forbid ...
https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
28b3748908ef-4
if not isinstance(pipeline, str): logger.warning( "Serializing pipeline to send to remote hardware. " "Note, it can be quite slow" "to serialize and send large models with each execution. " "Consider sending the pipeline" "to th...
https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
91d08857f164-0
Source code for langchain.llms.modal """Wrapper around Modal API.""" import logging from typing import Any, Dict, List, Mapping, Optional import requests from pydantic import Extra, Field, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain....
https://python.langchain.com/en/latest/_modules/langchain/llms/modal.html
91d08857f164-1
logger.warning( f"""{field_name} was transfered 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 @property d...
https://python.langchain.com/en/latest/_modules/langchain/llms/modal.html
a238c1f73048-0
Source code for langchain.llms.beam """Wrapper around Beam API.""" import base64 import json import logging import subprocess import textwrap import time from typing import Any, Dict, List, Mapping, Optional import requests from pydantic import Extra, Field, root_validator from langchain.callbacks.manager import Callba...
https://python.langchain.com/en/latest/_modules/langchain/llms/beam.html
a238c1f73048-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 endpoi...
https://python.langchain.com/en/latest/_modules/langchain/llms/beam.html
a238c1f73048-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( ...
https://python.langchain.com/en/latest/_modules/langchain/llms/beam.html
a238c1f73048-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....
https://python.langchain.com/en/latest/_modules/langchain/llms/beam.html
a238c1f73048-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...
https://python.langchain.com/en/latest/_modules/langchain/llms/beam.html
a238c1f73048-5
self, prompt: str, stop: Optional[list] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, ) -> 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...
https://python.langchain.com/en/latest/_modules/langchain/llms/beam.html
9409707c4934-0
Source code for langchain.llms.openai """Wrapper around OpenAI APIs.""" from __future__ import annotations import logging import sys import warnings from typing import ( AbstractSet, Any, Callable, Collection, Dict, Generator, List, Literal, Mapping, Optional, Set, Tuple,...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
9409707c4934-1
"finish_reason" ] response["choices"][0]["logprobs"] = stream_response["choices"][0]["logprobs"] def _streaming_response_template() -> Dict[str, Any]: return { "choices": [ { "text": "", "finish_reason": None, "logprobs": None, ...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
9409707c4934-2
return llm.client.create(**kwargs) return _completion_with_retry(**kwargs) async def acompletion_with_retry( llm: Union[BaseOpenAI, OpenAIChat], **kwargs: Any ) -> Any: """Use tenacity to retry the async completion call.""" retry_decorator = _create_retry_decorator(llm) @retry_decorator async de...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
9409707c4934-3
model_kwargs: Dict[str, Any] = Field(default_factory=dict) """Holds any model parameters valid for `create` call not explicitly specified.""" openai_api_key: Optional[str] = None openai_api_base: Optional[str] = None openai_organization: Optional[str] = None # to support explicit proxy for OpenAI ...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
9409707c4934-4
"no longer supported. Instead, please use: " "`from langchain.chat_models import ChatOpenAI`" ) return OpenAIChat(**data) return super().__new__(cls) class Config: """Configuration for this pydantic object.""" extra = Extra.ignore allow_populat...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
9409707c4934-5
values, "openai_api_key", "OPENAI_API_KEY" ) values["openai_api_base"] = get_from_dict_or_env( values, "openai_api_base", "OPENAI_API_BASE", default="", ) values["openai_proxy"] = get_from_dict_or_env( values, "opena...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
9409707c4934-6
"logit_bias": self.logit_bias, } # Azure gpt-35-turbo doesn't support best_of # don't specify best_of if it is 1 if self.best_of > 1: normal_params["best_of"] = self.best_of return {**normal_params, **self.model_kwargs} def _generate( self, prompts...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
9409707c4934-7
self, prompt=_prompts, **params ): if run_manager: run_manager.on_llm_new_token( stream_resp["choices"][0]["text"], verbose=self.verbose, logprobs=stream_resp["choices"][0]["lo...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
9409707c4934-8
self, prompt=_prompts, **params ): if run_manager: await run_manager.on_llm_new_token( stream_resp["choices"][0]["text"], verbose=self.verbose, logprobs=stream_resp["choices"][...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
9409707c4934-9
) -> LLMResult: """Create the LLMResult from the choices and prompts.""" generations = [] for i, _ in enumerate(prompts): sub_choices = choices[i * self.n : (i + 1) * self.n] generations.append( [ Generation( tex...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
9409707c4934-10
"""Prepare the params for streaming.""" params = self._invocation_params if "best_of" in params and params["best_of"] != 1: raise ValueError("OpenAI only supports best_of == 1 for streaming") if stop is not None: if "stop" in params: raise ValueError("`sto...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
9409707c4934-11
return super().get_num_tokens(text) try: import tiktoken except ImportError: raise ImportError( "Could not import tiktoken python package. " "This is needed in order to calculate get_num_tokens. " "Please install it with `pip instal...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
9409707c4934-12
"davinci": 2049, "text-davinci-003": 4097, "text-davinci-002": 4097, "code-davinci-002": 8001, "code-davinci-001": 8001, "code-cushman-002": 2048, "code-cushman-001": 2048, } # handling finetuned models if "ft-" in modelname...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
9409707c4934-13
environment variable ``OPENAI_API_KEY`` set with your API key. Any parameters that are valid to be passed to the openai.create call can be passed in, even if not explicitly saved on this class. Example: .. code-block:: python from langchain.llms import OpenAI openai = OpenAI(...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
9409707c4934-14
"openai_api_type", "OPENAI_API_TYPE", ) return values @property def _identifying_params(self) -> Mapping[str, Any]: return { **{"deployment_name": self.deployment_name}, **super()._identifying_params, } @property def _invocation_params(...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
9409707c4934-15
"""Holds any model parameters valid for `create` call not explicitly specified.""" openai_api_key: Optional[str] = None openai_api_base: Optional[str] = None # to support explicit proxy for OpenAI openai_proxy: Optional[str] = None max_retries: int = 6 """Maximum number of retries to make when g...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
9409707c4934-16
openai_api_key = get_from_dict_or_env( values, "openai_api_key", "OPENAI_API_KEY" ) openai_api_base = get_from_dict_or_env( values, "openai_api_base", "OPENAI_API_BASE", default="", ) openai_proxy = get_from_dict_or_env( ...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
9409707c4934-17
"no longer supported. Instead, please use: " "`from langchain.chat_models import ChatOpenAI`" ) return values @property def _default_params(self) -> Dict[str, Any]: """Get the default parameters for calling OpenAI API.""" return self.model_kwargs def _get_chat_par...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
9409707c4934-18
token = stream_resp["choices"][0]["delta"].get("content", "") response += token if run_manager: run_manager.on_llm_new_token( token, ) return LLMResult( generations=[[Generation(text=response)]], ...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
9409707c4934-19
llm_output = { "token_usage": full_response["usage"], "model_name": self.model_name, } return LLMResult( generations=[ [Generation(text=full_response["choices"][0]["message"]["content"])] ], llm_o...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
a21ad27f64e6-0
Source code for langchain.llms.mosaicml """Wrapper around MosaicML APIs.""" from typing import Any, Dict, List, Mapping, Optional import requests from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils impo...
https://python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html
a21ad27f64e6-1
) """ endpoint_url: str = ( "https://models.hosted-on.mosaicml.hosting/mpt-7b-instruct/v1/predict" ) """Endpoint URL to use.""" inject_instruction_format: bool = False """Whether to inject the instruction format into the prompt.""" model_kwargs: Optional[dict] = None """Key word ...
https://python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html
a21ad27f64e6-2
instruction=prompt, ) return prompt def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, is_retry: bool = False, ) -> str: """Call out to a MosaicML LLM inference endpoint. ...
https://python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html
a21ad27f64e6-3
raise ValueError( f"Error raised by inference API: {parsed_response['error']}" ) if "data" not in parsed_response: raise ValueError( f"Error raised by inference API, no key data: {parsed_response}" ) generate...
https://python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html
a317a43f272f-0
Source code for langchain.llms.huggingface_text_gen_inference """Wrapper around Huggingface text generation inference API.""" from functools import partial from typing import Any, Dict, List, Optional from pydantic import Extra, Field, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
a317a43f272f-1
inference_server_url = "http://localhost:8010/", max_new_tokens = 512, top_k = 10, top_p = 0.95, typical_p = 0.95, temperature = 0.01, repetition_penalty = 1.03, ) print(llm("What is Deep Learning?"))...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
a317a43f272f-2
@root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that python package exists in environment.""" try: import text_generation values["client"] = text_generation.Client( values["inference_server_url"], timeout=values["timeout"] ...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
a317a43f272f-3
text_callback = None if run_manager: text_callback = partial( run_manager.on_llm_new_token, verbose=self.verbose ) params = { "stop_sequences": stop, "max_new_tokens": self.max_new_tokens, "top_k"...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
44c87699d824-0
Source code for langchain.llms.aviary """Wrapper around Aviary""" from typing import Any, Dict, List, Mapping, Optional import requests from pydantic import Extra, Field, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import ...
https://python.langchain.com/en/latest/_modules/langchain/llms/aviary.html
44c87699d824-1
"""Validate that api key and python package exists in environment.""" aviary_url = get_from_dict_or_env(values, "aviary_url", "AVIARY_URL") if not aviary_url.endswith("/"): aviary_url += "/" values["aviary_url"] = aviary_url aviary_token = get_from_dict_or_env( va...
https://python.langchain.com/en/latest/_modules/langchain/llms/aviary.html
44c87699d824-2
prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, ) -> str: """Call out to Aviary Args: prompt: The prompt to pass into the model. Returns: The string generated by the model. Example: ...
https://python.langchain.com/en/latest/_modules/langchain/llms/aviary.html
8f9321254114-0
Source code for langchain.llms.pipelineai """Wrapper around Pipeline Cloud API.""" import logging from typing import Any, Dict, List, Mapping, Optional from pydantic import BaseModel, Extra, Field, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from l...
https://python.langchain.com/en/latest/_modules/langchain/llms/pipelineai.html
8f9321254114-1
extra = values.get("pipeline_kwargs", {}) for field_name in list(values): if field_name not in all_required_field_names: if field_name in extra: raise ValueError(f"Found {field_name} supplied twice.") logger.warning( f"""{field_...
https://python.langchain.com/en/latest/_modules/langchain/llms/pipelineai.html
8f9321254114-2
"Please install it with `pip install pipeline-ai`." ) client = PipelineCloud(token=self.pipeline_api_key) params = self.pipeline_kwargs or {} run = client.run_pipeline(self.pipeline_key, [prompt, params]) try: text = run.result_preview[0][0] except Attribu...
https://python.langchain.com/en/latest/_modules/langchain/llms/pipelineai.html
fca098a09614-0
Source code for langchain.llms.forefrontai """Wrapper around ForefrontAI APIs.""" from typing import Any, Dict, List, Mapping, Optional import requests from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.util...
https://python.langchain.com/en/latest/_modules/langchain/llms/forefrontai.html
fca098a09614-1
@root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key exists in environment.""" forefrontai_api_key = get_from_dict_or_env( values, "forefrontai_api_key", "FOREFRONTAI_API_KEY" ) values["forefrontai_api_key"] = forefrontai_api_key...
https://python.langchain.com/en/latest/_modules/langchain/llms/forefrontai.html
fca098a09614-2
""" response = requests.post( url=self.endpoint_url, headers={ "Authorization": f"Bearer {self.forefrontai_api_key}", "Content-Type": "application/json", }, json={"text": prompt, **self._default_params}, ) response_j...
https://python.langchain.com/en/latest/_modules/langchain/llms/forefrontai.html
4e4b2eb83482-0
Source code for langchain.llms.huggingface_pipeline """Wrapper around HuggingFace Pipeline APIs.""" import importlib.util import logging from typing import Any, List, Mapping, Optional from pydantic import Extra from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from la...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html
4e4b2eb83482-1
""" pipeline: Any #: :meta private: model_id: str = DEFAULT_MODEL_ID """Model name to use.""" model_kwargs: Optional[dict] = None """Key word arguments passed to the model.""" pipeline_kwargs: Optional[dict] = None """Key word arguments passed to the pipeline.""" class Config: "...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html
4e4b2eb83482-2
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." ...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html
4e4b2eb83482-3
) return cls( pipeline=pipeline, model_id=model_id, model_kwargs=_model_kwargs, pipeline_kwargs=_pipeline_kwargs, **kwargs, ) @property def _identifying_params(self) -> Mapping[str, Any]: """Get the identifying parameters.""" ...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html
4e4b2eb83482-4
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html
218d51ba3501-0
Source code for langchain.llms.sagemaker_endpoint """Wrapper around Sagemaker InvokeEndpoint API.""" from abc import abstractmethod from typing import Any, Dict, Generic, List, Mapping, Optional, TypeVar, Union from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun f...
https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
218d51ba3501-1
"""The MIME type of the response data returned from endpoint""" @abstractmethod def transform_input(self, prompt: INPUT_TYPE, model_kwargs: Dict) -> bytes: """Transforms the input to a format that model can accept as the request Body. Should return bytes or seekable file like object in t...
https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
218d51ba3501-2
) credentials_profile_name = ( "default" ) se = SagemakerEndpoint( endpoint_name=endpoint_name, region_name=region_name, credentials_profile_name=credentials_profile_name ) """ client: Any #: :meta p...
https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
218d51ba3501-3
def transform_output(self, output: bytes) -> str: response_json = json.loads(output.read().decode("utf-8")) return response_json[0]["generated_text"] """ model_kwargs: Optional[Dict] = None """Key word arguments to pass to the model.""" endpoint_kwargs: Optional[D...
https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
218d51ba3501-4
@property def _identifying_params(self) -> Mapping[str, Any]: """Get the identifying parameters.""" _model_kwargs = self.model_kwargs or {} return { **{"endpoint_name": self.endpoint_name}, **{"model_kwargs": _model_kwargs}, } @property def _llm_type(s...
https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
218d51ba3501-5
if stop is not None: # This is a bit hacky, but I can't figure out a better way to enforce # stop tokens when making calls to the sagemaker endpoint. text = enforce_stop_tokens(text, stop) return text By Harrison Chase © Copyright 2023, Harrison Chase. Las...
https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
8453e6974cb9-0
Source code for langchain.llms.google_palm """Wrapper arround Google's PaLM Text APIs.""" from __future__ import annotations import logging from typing import Any, Callable, Dict, List, Optional from pydantic import BaseModel, root_validator from tenacity import ( before_sleep_log, retry, retry_if_exception...
https://python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html
8453e6974cb9-1
), before_sleep=before_sleep_log(logger, logging.WARNING), ) def generate_with_retry(llm: GooglePalm, **kwargs: Any) -> Any: """Use tenacity to retry the completion call.""" retry_decorator = _create_retry_decorator() @retry_decorator def _generate_with_retry(**kwargs: Any) -> Any: r...
https://python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html
8453e6974cb9-2
Must be positive.""" max_output_tokens: Optional[int] = None """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 ...
https://python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html
8453e6974cb9-3
return values def _generate( self, prompts: List[str], stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, ) -> LLMResult: generations = [] for prompt in prompts: completion = generate_with_retry( s...
https://python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html
00f41dc33a86-0
Source code for langchain.llms.human from typing import Any, Callable, List, Mapping, Optional from pydantic import Field from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens def _display_prompt(prompt: str) -> None: ...
https://python.langchain.com/en/latest/_modules/langchain/llms/human.html
00f41dc33a86-1
"""Returns the type of LLM.""" return "human-input" def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, ) -> str: """ Displays the prompt to the user and returns their input as a response....
https://python.langchain.com/en/latest/_modules/langchain/llms/human.html
2bd4ae40bfd3-0
Source code for langchain.llms.anyscale """Wrapper around Anyscale""" from typing import Any, Dict, List, Mapping, Optional import requests from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enf...
https://python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html
2bd4ae40bfd3-1
@root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" anyscale_service_url = get_from_dict_or_env( values, "anyscale_service_url", "ANYSCALE_SERVICE_URL" ) anyscale_service_route = get_...
https://python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html
2bd4ae40bfd3-2
) -> str: """Call out to Anyscale Service 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 ...
https://python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html
b61218194d0e-0
Source code for langchain.llms.nlpcloud """Wrapper around NLPCloud APIs.""" from typing import Any, Dict, List, Mapping, Optional from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.utils import get_from_dict_or_e...
https://python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html