id
stringlengths
14
16
text
stringlengths
4
1.28k
source
stringlengths
54
121
ac1774410b1b-41
return "openai-chat" [docs] def get_token_ids(self, text: str) -> List[int]: """Get the token IDs using the tiktoken package.""" # tiktoken NOT supported for Python < 3.8 if sys.version_info[1] < 8: return super().get_token_ids(text) try: import tiktoken ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
e1555fe29a1c-0
Source code for langchain.llms.databricks import os from abc import ABC, abstractmethod from typing import Any, Callable, Dict, List, Optional import requests from pydantic import BaseModel, Extra, Field, PrivateAttr, root_validator, validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langch...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
e1555fe29a1c-1
if not response.ok: raise ValueError(f"HTTP {response.status_code} error: {response.text}") return response.json() @abstractmethod def post(self, request: Any) -> Any: ... class _DatabricksServingEndpointClient(_DatabricksClientBase): """An API client that talks to a Databricks s...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
e1555fe29a1c-2
return values def post(self, request: Any) -> Any: # See https://docs.databricks.com/machine-learning/model-serving/score-model-serving-endpoints.html wrapped_request = {"dataframe_records": [request]} response = self.post_raw(wrapped_request)["predictions"] # For a single-record que...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
e1555fe29a1c-3
host = values["host"] cluster_id = values["cluster_id"] port = values["cluster_driver_port"] api_url = f"https://{host}/driver-proxy-api/o/0/{cluster_id}/{port}" values["api_url"] = api_url return values def post(self, request: Any) -> Any: return self...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
e1555fe29a1c-4
Raises an error if the hostname cannot be automatically determined. """ host = os.getenv("DATABRICKS_HOST") if not host: try: host = get_repl_context().browserHostName if not host: raise ValueError("context doesn't contain browserHostName.") except Exc...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
e1555fe29a1c-5
""" if api_token := os.getenv("DATABRICKS_TOKEN"): return api_token try: api_token = get_repl_context().apiToken if not api_token: raise ValueError("context doesn't contain apiToken.") except Exception as e: raise ValueError( "api_token was not set and...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
e1555fe29a1c-6
To wrap it as an LLM you must have "Can Query" permission to the endpoint. Set ``endpoint_name`` accordingly and do not set ``cluster_id`` and ``cluster_driver_port``. The expected model signature is: * inputs:: [{"name": "prompt", "type": "string"}, {"name": "stop", "type":...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
e1555fe29a1c-7
the driver IP address or simply ``0.0.0.0`` instead of localhost only. To wrap it as an LLM you must have "Can Attach To" permission to the cluster. Set ``cluster_id`` and ``cluster_driver_port`` and do not set ``endpoint_name``. The expected server schema (using JSON schema) is: * inputs:: ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
e1555fe29a1c-8
transformations before and after the query. """ host: str = Field(default_factory=get_default_host) """Databricks workspace hostname. If not provided, the default value is determined by * the ``DATABRICKS_HOST`` environment variable if present, or * the hostname of the current Databricks workspa...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
e1555fe29a1c-9
"no isolation shared" mode. """ endpoint_name: Optional[str] = None """Name of the model serving endpont. You must specify the endpoint name to connect to a model serving endpoint. You must not set both ``endpoint_name`` and ``cluster_id``. """ cluster_id: Optional[str] = None """ID of t...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
e1555fe29a1c-10
"""The port number used by the HTTP server running on the cluster driver node. The server should listen on the driver IP address or simply ``0.0.0.0`` to connect. We recommend the server using a port number between ``[3000, 8000]``. """ model_kwargs: Optional[Dict[str, Any]] = None """Extra paramete...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
e1555fe29a1c-11
""" _client: _DatabricksClientBase = PrivateAttr() class Config: extra = Extra.forbid underscore_attrs_are_private = True @validator("cluster_id", always=True) def set_cluster_id(cls, v: Any, values: Dict[str, Any]) -> Optional[str]: if v and values["endpoint_name"]: ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
e1555fe29a1c-12
f" error: {e}" ) @validator("cluster_driver_port", always=True) def set_cluster_driver_port(cls, v: Any, values: Dict[str, Any]) -> Optional[str]: if v and values["endpoint_name"]: raise ValueError("Cannot set both endpoint_name and cluster_driver_port.") elif values[...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
e1555fe29a1c-13
if v: assert "prompt" not in v, "model_kwargs must not contain key 'prompt'" assert "stop" not in v, "model_kwargs must not contain key 'stop'" return v def __init__(self, **data: Any): super().__init__(**data) if self.endpoint_name: self._client = _Databr...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
e1555fe29a1c-14
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: Optional[Li...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
e1555fe29a1c-15
response = self._client.post(request) if self.transform_output_fn: response = self.transform_output_fn(response) return response
https://api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
84cb46746fcc-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://api.python.langchain.com/en/latest/_modules/langchain/llms/petals.html
84cb46746fcc-1
.. 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.""" t...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/petals.html
84cb46746fcc-2
do_sample: bool = True """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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/petals.html
84cb46746fcc-3
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. ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/petals.html
84cb46746fcc-4
) try: from petals import DistributedBloomForCausalLM from transformers import BloomTokenizerFast model_name = values["model_name"] values["tokenizer"] = BloomTokenizerFast.from_pretrained(model_name) values["client"] = DistributedBloomForCausalLM.from...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/petals.html
84cb46746fcc-5
"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.""" ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/petals.html
84cb46746fcc-6
"""Call the Petals API.""" 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: ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/petals.html
0ab1005c6d1a-0
Source code for langchain.llms.openllm """Wrapper around OpenLLM APIs.""" from __future__ import annotations import copy import json import logging from typing import ( TYPE_CHECKING, Any, Dict, List, Literal, Optional, TypedDict, Union, overload, ) from pydantic import PrivateAttr f...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html
0ab1005c6d1a-1
embedded: bool llm_kwargs: Dict[str, Any] logger = logging.getLogger(__name__) [docs]class OpenLLM(LLM): """Wrapper for accessing OpenLLM, supporting both in-process model instance and remote OpenLLM servers. To use, you should have the openllm library installed: .. code-block:: bash pip ins...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html
0ab1005c6d1a-2
For all available supported models, you can run 'openllm models'. If you have a OpenLLM server running, you can also use it remotely: .. code-block:: python from langchain.llms import OpenLLM llm = OpenLLM(server_url='http://localhost:3000') llm("What is the difference be...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html
0ab1005c6d1a-3
server_type: ServerType = "http" """Optional server type. Either 'http' or 'grpc'.""" embedded: bool = True """Initialize this LLM instance in current process by default. Should only set to False when using in conjunction with BentoML Service.""" llm_kwargs: Dict[str, Any] """Key word arguments...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html
0ab1005c6d1a-4
model_id: Optional[str] = ..., embedded: Literal[True, False] = ..., **llm_kwargs: Any, ) -> None: ... @overload def __init__( self, *, server_url: str = ..., server_type: Literal["grpc", "http"] = ..., **llm_kwargs: Any, ) -> None: ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html
0ab1005c6d1a-5
except ImportError as e: raise ImportError( "Could not import openllm. Make sure to install it with " "'pip install openllm.'" ) from e llm_kwargs = llm_kwargs or {} if server_url is not None: logger.debug("'server_url' is provided, ret...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html
0ab1005c6d1a-6
} ) self._runner = None # type: ignore self._client = client else: assert model_name is not None, "Must provide 'model_name' or 'server_url'" # since the LLM are relatively huge, we don't actually want to convert the # Runner with embedded...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html
0ab1005c6d1a-7
"model_name": model_name, "model_id": model_id, "embedded": embedded, "llm_kwargs": llm_kwargs, } ) self._client = None # type: ignore self._runner = runner @property def runner(self) -> openllm.LLMR...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html
0ab1005c6d1a-8
) svc = bentoml.Service("langchain-openllm", runners=[llm.runner]) @svc.api(input=Text(), output=Text()) def chat(input_text: str): return agent.run(input_text) """ if self._runner is None: raise ValueError("OpenLLM must be initialized loca...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html
0ab1005c6d1a-9
model_id = self.model_id try: self.llm_kwargs.update( json.loads(self._runner.identifying_params["configuration"]) ) except (TypeError, json.JSONDecodeError): pass return IdentifyingParams( server_url=self.se...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html
0ab1005c6d1a-10
) -> str: try: import openllm except ImportError as e: raise ImportError( "Could not import openllm. Make sure to install it with " "'pip install openllm'." ) from e copied = copy.deepcopy(self.llm_kwargs) copied.update(...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html
0ab1005c6d1a-11
run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: try: import openllm except ImportError as e: raise ImportError( "Could not import openllm. Make sure to install it with " "'pip install openllm'." ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html
0ab1005c6d1a-12
postprocess_kwargs, ) = self._runner.llm.sanitize_parameters(prompt, **kwargs) generated_result = await self._runner.generate.async_run( prompt, **generate_kwargs ) return self._runner.llm.postprocess_generate( prompt, generated_result, **p...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html
7edf09928a1b-0
Source code for langchain.llms.huggingface_hub """Wrapper around HuggingFace 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.llms.utils import enf...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html
7edf09928a1b-1
Only supports `text-generation`, `text2text-generation` and `summarization` for now. Example: .. code-block:: python from langchain.llms import HuggingFaceHub hf = HuggingFaceHub(repo_id="gpt2", huggingfacehub_api_token="my-api-key") """ client: Any #: :meta private: rep...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html
7edf09928a1b-2
extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" huggingfacehub_api_token = get_from_dict_or_env( values, "huggingfacehub_api_token", "HUGGINGFACEHUB_API_TOKEN" ) ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html
7edf09928a1b-3
values["client"] = client except ImportError: raise ValueError( "Could not import huggingface_hub python package. " "Please install it with `pip install huggingface_hub`." ) return values @property def _identifying_params(self) -> Mapping[s...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html
7edf09928a1b-4
run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Call out to HuggingFace Hub's inference endpoint. Args: prompt: The prompt to pass into the model. stop: Optional list of stop words to use when generating. Returns: ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html
7edf09928a1b-5
text = response[0]["generated_text"][len(prompt) :] elif self.client.task == "text2text-generation": text = response[0]["generated_text"] elif self.client.task == "summarization": text = response[0]["summary_text"] else: raise ValueError( f"Got...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html
56a03ee7e000-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://api.python.langchain.com/en/latest/_modules/langchain/llms/forefrontai.html
56a03ee7e000-1
"""Model name to use.""" temperature: float = 0.7 """What sampling temperature to use.""" length: int = 256 """The maximum number of tokens to generate in the completion.""" top_p: float = 1.0 """Total probability mass of tokens to consider at each step.""" top_k: int = 40 """The number ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/forefrontai.html
56a03ee7e000-2
@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://api.python.langchain.com/en/latest/_modules/langchain/llms/forefrontai.html
56a03ee7e000-3
"""Get the identifying parameters.""" return {**{"endpoint_url": self.endpoint_url}, **self._default_params} @property def _llm_type(self) -> str: """Return type of llm.""" return "forefrontai" def _call( self, prompt: str, stop: Optional[List[str]] = None, ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/forefrontai.html
56a03ee7e000-4
""" 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, **kwargs}, ) ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/forefrontai.html
0b70df5a9374-0
Source code for langchain.llms.bananadev """Wrapper around Banana 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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html
0b70df5a9374-1
.. code-block:: python from langchain.llms import Banana banana = Banana(model_key="") """ model_key: str = "" """model endpoint to use""" model_kwargs: Dict[str, Any] = Field(default_factory=dict) """Holds any model parameters valid for `create` call not explicitly speci...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html
0b70df5a9374-2
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 transfered to model_kwargs. ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html
0b70df5a9374-3
return values @property def _identifying_params(self) -> Mapping[str, Any]: """Get the identifying parameters.""" return { **{"model_key": self.model_key}, **{"model_kwargs": self.model_kwargs}, } @property def _llm_type(self) -> str: """Return typ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html
0b70df5a9374-4
"Please install it with `pip install banana-dev`." ) params = self.model_kwargs or {} params = {**params, **kwargs} api_key = self.banana_api_key model_key = self.model_key model_inputs = { # a json specific to your model. "prompt": prompt, ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html
0b70df5a9374-5
"\n- modify app.py to return the above schema" "\n- deploy that as a custom repo" ) 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) re...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html
8a835eb40695-0
Source code for langchain.llms.anthropic """Wrapper around Anthropic APIs.""" import re import warnings from typing import Any, Callable, Dict, Generator, List, Mapping, Optional, Tuple, Union from pydantic import BaseModel, root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
8a835eb40695-1
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[Union[float, Tupl...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
8a835eb40695-2
anthropic_api_key = get_from_dict_or_env( values, "anthropic_api_key", "ANTHROPIC_API_KEY" ) """Get custom api url from environment.""" anthropic_api_url = get_from_dict_or_env( values, "anthropic_api_url", "ANTHROPIC_API_URL", default=...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
8a835eb40695-3
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 parameter...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
8a835eb40695-4
"""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") if stop is No...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
8a835eb40695-5
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. re...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
8a835eb40695-6
"""Raise warning that this class is deprecated.""" 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.""" ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
8a835eb40695-7
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...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
8a835eb40695-8
prompt = f"\n\nHuman: {prompt}\n\nAssistant:" response = model(prompt) """ stop = self._get_anthropic_stop(stop) params = {**self._default_params, **kwargs} if self.streaming: stream_resp = self.client.completion_stream( prompt=self._wrap_promp...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
8a835eb40695-9
) return response["completion"] 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.""" ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
8a835eb40695-10
if run_manager: await run_manager.on_llm_new_token(delta, **data) return current_completion response = await self.client.acompletion( prompt=self._wrap_prompt(prompt), stop_sequences=stop, **params, ) return response["completion...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
8a835eb40695-11
.. 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(st...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
3e56a593f5d5-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://api.python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html
3e56a593f5d5-1
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...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html
3e56a593f5d5-2
) 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: return llm.client.generate_text(**kwargs) return _generate_with_retr...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html
3e56a593f5d5-3
else: return text [docs]class GooglePalm(BaseLLM, BaseModel): 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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html
3e56a593f5d5-4
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://api.python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html
3e56a593f5d5-5
"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 <=...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html
3e56a593f5d5-6
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_r...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html
3e56a593f5d5-7
prompt_generations.append(Generation(text=stripped_text)) generations.append(prompt_generations) return LLMResult(generations=generations) async def _agenerate( self, prompts: List[str], stop: Optional[List[str]] = None, run_manager: Optional[AsyncCallbackManagerF...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html
e55ef48f0c95-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://api.python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html
e55ef48f0c95-1
Example: .. code-block:: python from langchain.llms import DeepInfra di = DeepInfra(model_id="google/flan-t5-xl", deepinfra_api_token="my-api-key") """ model_id: str = DEFAULT_MODEL_ID model_kwargs: Optional[dict] = None deepinfra_api_token...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html
e55ef48f0c95-2
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://api.python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html
e55ef48f0c95-3
Returns: The string generated by the model. Example: .. code-block:: python response = di("Tell me a joke.") """ _model_kwargs = self.model_kwargs or {} _model_kwargs = {**_model_kwargs, **kwargs} # HTTP headers for authorization he...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html
e55ef48f0c95-4
raise ValueError( "Error raised by inference API HTTP code: %s, %s" % (res.status_code, res.text) ) try: t = res.json() text = t["results"][0]["generated_text"] except requests.exceptions.JSONDecodeError as e: raise ValueErr...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html
1c780cef8e5c-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://api.python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html
1c780cef8e5c-1
OpenAI API key as well. Example: .. code-block:: python pgllm = PredictionGuard(model="MPT-7B-Instruct", token="my-access-token", output={ "type": "boolean" ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html
1c780cef8e5c-2
"""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://api.python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html
1c780cef8e5c-3
return { "max_tokens": self.max_tokens, "temperature": self.temperature, } @property def _identifying_params(self) -> Dict[str, Any]: """Get the identifying parameters.""" return {**{"model": self.model}, **self._default_params} @property def _llm_type(sel...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html
1c780cef8e5c-4
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 ValueError("`stop` fo...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html
1c780cef8e5c-5
# In order to make this consistent with other endpoints, we strip them. if stop is not None or self.stop is not None: text = enforce_stop_tokens(text, params["stop_sequences"]) return text
https://api.python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html
6a88b19e0b54-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://api.python.langchain.com/en/latest/_modules/langchain/llms/openlm.html
51a16bc2fda2-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://api.python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
51a16bc2fda2-1
model_name: str = "finetuned-gpt-neox-20b" """Model name to use.""" temperature: float = 0.7 """What sampling temperature to use.""" min_length: int = 1 """The minimum number of tokens to generate in the completion.""" max_length: int = 256 """The maximum number of tokens to generate in the ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
51a16bc2fda2-2
top_p: int = 1 """Total probability mass of tokens to consider at each step.""" top_k: int = 50 """The number of highest probability tokens to keep for top-k filtering.""" repetition_penalty: float = 1.0 """Penalizes repeated tokens. 1.0 means no penalty.""" length_penalty: float = 1.0 """Ex...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
51a16bc2fda2-3
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.""" nlpcloud_api_key = get_from_dict_or_env( value...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
51a16bc2fda2-4
"""Get the default parameters for calling NLPCloud API.""" return { "temperature": self.temperature, "min_length": self.min_length, "max_length": self.max_length, "length_no_input": self.length_no_input, "remove_input": self.remove_input, "...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
51a16bc2fda2-5
} @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 "nlpcloud" def _call( ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
51a16bc2fda2-6
Example: .. code-block:: python response = nlpcloud("Tell me a joke.") """ if stop and len(stop) > 1: raise ValueError( "NLPCloud only supports a single stop sequence per generation." "Pass in a list of length 1." ) ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
e803b998817f-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://api.python.langchain.com/en/latest/_modules/langchain/llms/cohere.html
e803b998817f-1
# 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(cohere.error.CohereError)), before_sleep=...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/cohere.html
e803b998817f-2
[docs]class Cohere(LLM): """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...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/cohere.html
e803b998817f-3
k: int = 0 """Number of most likely tokens to consider at each step.""" p: int = 1 """Total probability mass of tokens to consider at each step.""" frequency_penalty: float = 0.0 """Penalizes repeated tokens according to frequency. Between 0 and 1.""" presence_penalty: float = 0.0 """Penaliz...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/cohere.html
e803b998817f-4
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://api.python.langchain.com/en/latest/_modules/langchain/llms/cohere.html
e803b998817f-5
"temperature": self.temperature, "k": self.k, "p": self.p, "frequency_penalty": self.frequency_penalty, "presence_penalty": self.presence_penalty, "truncate": self.truncate, } @property def _identifying_params(self) -> Dict[str, Any]: "...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/cohere.html
e803b998817f-6
) -> str: """Call out to Cohere's 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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/cohere.html