id
stringlengths
14
16
text
stringlengths
31
2.41k
source
stringlengths
53
121
aa045f555b24-0
Source code for langchain.llms.clarifai """Wrapper around Clarifai's 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 import enfor...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/clarifai.html
aa045f555b24-1
api_base: str = "https://api.clarifai.com" 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 we have all required info to access...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/clarifai.html
aa045f555b24-2
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 s...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/clarifai.html
aa045f555b24-3
# 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, model_id=self.model_id, ...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/clarifai.html
8ae927e30afe-0
Source code for langchain.llms.cerebriumai """Wrapper around CerebriumAI 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...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/cerebriumai.html
8ae927e30afe-1
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...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/cerebriumai.html
8ae927e30afe-2
"""Call to CerebriumAI endpoint.""" try: from cerebrium import model_api_request except ImportError: raise ValueError( "Could not import cerebrium python package. " "Please install it with `pip install cerebrium`." ) params = se...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/cerebriumai.html
3ec9d98307bb-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/stable/_modules/langchain/llms/forefrontai.html
3ec9d98307bb-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://api.python.langchain.com/en/stable/_modules/langchain/llms/forefrontai.html
3ec9d98307bb-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, **kwargs}, ) ...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/forefrontai.html
bec63db63b6c-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://api.python.langchain.com/en/stable/_modules/langchain/llms/fake.html
557f8f25beb7-0
Source code for langchain.llms.aviary """Wrapper around Aviary""" import dataclasses import os from typing import Any, Dict, List, Mapping, Optional, Union, cast import requests from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LL...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/aviary.html
557f8f25beb7-1
) from e result = sorted( [k.lstrip("/").replace("--", "/") for k in result.keys() if "--" in k] ) return result def get_completions( model: str, prompt: str, use_prompt_format: bool = True, version: str = "", ) -> Dict[str, Union[str, float, int]]: """Get completions from Aviary...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/aviary.html
557f8f25beb7-2
os.environ["AVIARY_TOKEN"] = "<TOKEN>" light = Aviary(model='amazon/LightGPT') output = light('How do you make fried rice?') """ model: str = "amazon/LightGPT" aviary_url: Optional[str] = None aviary_token: Optional[str] = None # If True the prompt template for the model will...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/aviary.html
557f8f25beb7-3
"aviary_url": self.aviary_url, } @property def _llm_type(self) -> str: """Return type of llm.""" return f"aviary-{self.model.replace('/', '-')}" def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLM...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/aviary.html
feb113ae9e18-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/stable/_modules/langchain/llms/openllm.html
feb113ae9e18-1
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/stable/_modules/langchain/llms/openllm.html
feb113ae9e18-2
*, 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, ) -> No...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/openllm.html
feb113ae9e18-3
"llm_kwargs": llm_kwargs, } ) 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 conv...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/openllm.html
feb113ae9e18-4
tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION ) 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 ...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/openllm.html
feb113ae9e18-5
**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'." ) from e copied = copy.deepcopy(self.llm_kwargs) ...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/openllm.html
feb113ae9e18-6
( prompt, generate_kwargs, postprocess_kwargs, ) = self._runner.llm.sanitize_parameters(prompt, **kwargs) generated_result = await self._runner.generate.async_run( prompt, **generate_kwargs ) return self._run...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/openllm.html
bab47f46c652-0
Source code for langchain.llms.huggingface_endpoint """Wrapper around HuggingFace 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....
https://api.python.langchain.com/en/stable/_modules/langchain/llms/huggingface_endpoint.html
bab47f46c652-1
huggingfacehub_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.""" hugging...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/huggingface_endpoint.html
bab47f46c652-2
return "huggingface_endpoint" def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Call out to HuggingFace Hub's inference endpoint. Args: prompt: Th...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/huggingface_endpoint.html
bab47f46c652-3
elif self.task == "text2text-generation": text = generated_text[0]["generated_text"] elif self.task == "summarization": text = generated_text[0]["summary_text"] else: raise ValueError( f"Got invalid task {self.task}, " f"currently only ...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/huggingface_endpoint.html
d0177e8a7bf3-0
Source code for langchain.llms.azureml_endpoint """Wrapper around AzureML Managed Online Endpoint API.""" import json import urllib.request from abc import abstractmethod from typing import Any, Dict, List, Mapping, Optional from pydantic import BaseModel, validator from langchain.callbacks.manager import CallbackManag...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/azureml_endpoint.html
d0177e8a7bf3-1
.. code-block:: python class ContentFormatter(ContentFormatterBase): content_type = "application/json" accepts = "application/json" def format_request_payload( self, prompt: str, ...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/azureml_endpoint.html
d0177e8a7bf3-2
) return str.encode(input_str) def format_response_payload(self, output: bytes) -> str: response_json = json.loads(output) return response_json[0]["0"] class HFContentFormatter(ContentFormatterBase): """Content handler for LLMs from the HuggingFace catalog.""" def format_request_payl...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/azureml_endpoint.html
d0177e8a7bf3-3
) """ # noqa: E501 endpoint_url: str = "" """URL of pre-existing Endpoint. Should be passed to constructor or specified as env var `AZUREML_ENDPOINT_URL`.""" endpoint_api_key: str = "" """Authentication Key for Endpoint. Should be passed to constructor or specified as env var `AZUR...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/azureml_endpoint.html
d0177e8a7bf3-4
"""Get the identifying parameters.""" _model_kwargs = self.model_kwargs or {} return { **{"deployment_name": self.deployment_name}, **{"model_kwargs": _model_kwargs}, } @property def _llm_type(self) -> str: """Return type of llm.""" return "azureml...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/azureml_endpoint.html
e60794e89e20-0
Source code for langchain.llms.promptlayer_openai """PromptLayer wrapper.""" import datetime from typing import Any, List, Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun, ) from langchain.llms import OpenAI, OpenAIChat from langchain.schema import LLMR...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/promptlayer_openai.html
e60794e89e20-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 = ...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/promptlayer_openai.html
e60794e89e20-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": gene...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/promptlayer_openai.html
e60794e89e20-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 impo...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/promptlayer_openai.html
e60794e89e20-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_in...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/promptlayer_openai.html
e60794e89e20-5
generation.generation_info, dict ): generation.generation_info = {} generation.generation_info["pl_request_id"] = pl_request_id return generated_responses
https://api.python.langchain.com/en/stable/_modules/langchain/llms/promptlayer_openai.html
d70be5320f74-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://api.python.langchain.com/en/stable/_modules/langchain/llms/anyscale.html
d70be5320f74-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://api.python.langchain.com/en/stable/_modules/langchain/llms/anyscale.html
d70be5320f74-2
def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Call out to Anyscale Service endpoint. Args: prompt: The prompt to pass into the model. ...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/anyscale.html
38b0c61dc874-0
Source code for langchain.llms.octoai_endpoint """Wrapper around OctoAI 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 enforce_...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/octoai_endpoint.html
38b0c61dc874-1
"""OCTOAI API Token""" class Config: """Configuration for this pydantic object.""" 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.""" octoai_api_toke...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/octoai_endpoint.html
38b0c61dc874-2
_model_kwargs = self.model_kwargs or {} # Prepare the payload JSON parameter_payload = {"inputs": prompt, "parameters": _model_kwargs} try: # Initialize the OctoAI client from octoai import client octoai_client = client.Client(token=self.octoai_api_token) ...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/octoai_endpoint.html
a67451801017-0
Source code for langchain.llms.ctransformers """Wrapper around the C Transformers library.""" from typing import Any, Dict, Optional, Sequence from pydantic import root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM [docs]class CTransformers(LLM): """W...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/ctransformers.html
a67451801017-1
"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...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/ctransformers.html
a67451801017-2
text.append(chunk) _run_manager.on_llm_new_token(chunk, verbose=self.verbose) return "".join(text)
https://api.python.langchain.com/en/stable/_modules/langchain/llms/ctransformers.html
7a85b46087f0-0
Source code for langchain.llms.vertexai """Wrapper around Google VertexAI models.""" import asyncio from concurrent.futures import Executor, ThreadPoolExecutor from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional from pydantic import BaseModel, root_validator from langchain.callbacks.manager import ( ...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/vertexai.html
7a85b46087f0-1
project: Optional[str] = None "The default GCP project to use when making Vertex API calls." location: str = "us-central1" "The default location to use when making API calls." credentials: Any = None "The default custom credentials (google.auth.credentials.Credentials) to use " "when making API ...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/vertexai.html
7a85b46087f0-2
if stop is None and self.stop is not None: stop = self.stop if stop: return enforce_stop_tokens(text, stop) return text @property def _llm_type(self) -> str: return "vertexai" @classmethod def _get_task_executor(cls, request_parallelism: int = 5) -> Execut...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/vertexai.html
7a85b46087f0-3
tuned_model_name ) else: values["client"] = TextGenerationModel.from_pretrained(model_name) else: from vertexai.preview.language_models import CodeGenerationModel values["client"] = CodeGenerationModel.from_pretrained(mo...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/vertexai.html
64ebcec70aa1-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://api.python.langchain.com/en/stable/_modules/langchain/llms/ai21.html
64ebcec70aa1-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://api.python.langchain.com/en/stable/_modules/langchain/llms/ai21.html
64ebcec70aa1-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://api.python.langchain.com/en/stable/_modules/langchain/llms/ai21.html
64ebcec70aa1-3
response = requests.post( url=f"{base_url}/{self.model}/complete", headers={"Authorization": f"Bearer {self.ai21_api_key}"}, json={"prompt": prompt, "stopSequences": stop, **params}, ) if response.status_code != 200: optional_detail = response.json().get("...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/ai21.html
d5c5dd5c7e7d-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://api.python.langchain.com/en/stable/_modules/langchain/llms/pipelineai.html
d5c5dd5c7e7d-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://api.python.langchain.com/en/stable/_modules/langchain/llms/pipelineai.html
d5c5dd5c7e7d-2
"Please install it with `pip install pipeline-ai`." ) client = PipelineCloud(token=self.pipeline_api_key) params = self.pipeline_kwargs or {} params = {**params, **kwargs} run = client.run_pipeline(self.pipeline_key, [prompt, params]) try: text = run.resul...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/pipelineai.html
bbac85703043-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://api.python.langchain.com/en/stable/_modules/langchain/llms/human.html
bbac85703043-1
"""Returns the type of LLM.""" return "human-input" def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """ Displays the prompt to the user and returns the...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/human.html
d09b1937c265-0
Source code for langchain.llms.bedrock import json 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 enforce_stop_tokens class LLMInputOutp...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/bedrock.html
d09b1937c265-1
else: return response_body.get("results")[0].get("outputText") [docs]class Bedrock(LLM): """LLM provider to invoke Bedrock models. To authenticate, the AWS client uses the following methods to automatically load credentials: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/crede...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/bedrock.html
d09b1937c265-2
equivalent to the modelId property in the list-foundation-models api""" model_kwargs: Optional[Dict] = None """Key word arguments to pass to the model.""" class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @root_validator() def validate_environment(cls, ...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/bedrock.html
d09b1937c265-3
"""Return type of llm.""" return "amazon_bedrock" def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Call out to Bedrock service model. Args: ...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/bedrock.html
7e9775428d5d-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/stable/_modules/langchain/llms/databricks.html
7e9775428d5d-1
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/stable/_modules/langchain/llms/databricks.html
7e9775428d5d-2
"""Gets the default Databricks workspace hostname. 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("contex...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/databricks.html
7e9775428d5d-3
We assume that an LLM was registered and deployed to a serving endpoint. 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:: ...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/databricks.html
7e9775428d5d-4
you can use `transform_input_fn` and `transform_output_fn` to apply necessary 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`` enviro...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/databricks.html
7e9775428d5d-5
""" cluster_driver_port: Optional[str] = None """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:...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/databricks.html
7e9775428d5d-6
"And the cluster_id cannot be automatically determined. Received" 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 Val...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/databricks.html
7e9775428d5d-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://api.python.langchain.com/en/stable/_modules/langchain/llms/databricks.html
6641981c3615-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/stable/_modules/langchain/llms/anthropic.html
6641981c3615-1
"""Validate that api key and python package exists in environment.""" 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, ...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/anthropic.html
6641981c3615-2
@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 NameEr...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/anthropic.html
6641981c3615-3
response = model(prompt) """ @root_validator() def raise_warning(cls, values: Dict) -> Dict: """Raise warning that this class is deprecated.""" warnings.warn( "This Anthropic LLM is deprecated. " "Please use `from langchain.chat_models import ChatAnthropic` instead" ...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/anthropic.html
6641981c3615-4
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:" response = model(prompt) """ stop = self._get_a...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/anthropic.html
6641981c3615-5
) current_completion = "" async for data in stream_resp: delta = data["completion"][len(current_completion) :] current_completion = data["completion"] if run_manager: await run_manager.on_llm_new_token(delta, **data) ...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/anthropic.html
fa2eb6b9f399-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/stable/_modules/langchain/llms/petals.html
fa2eb6b9f399-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://api.python.langchain.com/en/stable/_modules/langchain/llms/petals.html
fa2eb6b9f399-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://api.python.langchain.com/en/stable/_modules/langchain/llms/petals.html
fa2eb6b9f399-3
"""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/stable/_modules/langchain/llms/petals.html
29e2571819ee-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 ( AsyncCallbackManagerFor...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/huggingface_text_gen_inference.html
29e2571819ee-1
- _acall: Async generates text based on a given prompt and stop sequences. - _llm_type: Returns the type of LLM. """ """ Example: .. code-block:: python # Basic Example (no streaming) llm = HuggingFaceTextGenInference( inference_server_url = "http://localh...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/huggingface_text_gen_inference.html
29e2571819ee-2
seed: Optional[int] = None inference_server_url: str = "" timeout: int = 120 server_kwargs: Dict[str, Any] = Field(default_factory=dict) stream: bool = False client: Any async_client: Any class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @ro...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/huggingface_text_gen_inference.html
29e2571819ee-3
res = self.client.generate( prompt, stop_sequences=stop, max_new_tokens=self.max_new_tokens, top_k=self.top_k, top_p=self.top_p, typical_p=self.typical_p, temperature=self.temperature, repetit...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/huggingface_text_gen_inference.html
29e2571819ee-4
prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: if stop is None: stop = self.stop_sequences else: stop += self.stop_sequences if not self.stream: r...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/huggingface_text_gen_inference.html
29e2571819ee-5
token = res.token is_stop = False for stop_seq in stop: if stop_seq in token.text: is_stop = True break if is_stop: break if not token.special: if t...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/huggingface_text_gen_inference.html
ee033db54369-0
Source code for langchain.llms.amazon_api_gateway from typing import Any, Dict, List, Mapping, Optional import requests from pydantic import Extra from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens class ContentHandle...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/amazon_api_gateway.html
ee033db54369-1
**{"model_kwargs": _model_kwargs}, } @property def _llm_type(self) -> str: """Return type of llm.""" return "amazon_api_gateway" def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, ...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/amazon_api_gateway.html
b948fd7bc7b3-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://api.python.langchain.com/en/stable/_modules/langchain/llms/huggingface_pipeline.html
b948fd7bc7b3-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://api.python.langchain.com/en/stable/_modules/langchain/llms/huggingface_pipeline.html
b948fd7bc7b3-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://api.python.langchain.com/en/stable/_modules/langchain/llms/huggingface_pipeline.html
b948fd7bc7b3-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://api.python.langchain.com/en/stable/_modules/langchain/llms/huggingface_pipeline.html
d1627a75897e-0
Source code for langchain.llms.rwkv """Wrapper for the RWKV model. Based on https://github.com/saharNooby/rwkv.cpp/blob/master/rwkv/chat_with_bot.py https://github.com/BlinkDL/ChatRWKV/blob/main/v2/chat.py """ from typing import Any, Dict, List, Mapping, Optional, Set from pydantic import BaseModel, Extra, roo...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/rwkv.html
d1627a75897e-1
"""Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim..""" penalty_alpha_presence: float = 0.4 """Positive values penalize new tokens based on whether they appear in the text so far, increasing ...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/rwkv.html
d1627a75897e-2
"""Validate that the python package exists in the environment.""" try: import tokenizers except ImportError: raise ImportError( "Could not import tokenizers python package. " "Please install it with `pip install tokenizers`." ) ...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/rwkv.html
d1627a75897e-3
AVOID_REPEAT_TOKENS = [] AVOID_REPEAT = ",:?!" for i in AVOID_REPEAT: dd = self.pipeline.encode(i) assert len(dd) == 1 AVOID_REPEAT_TOKENS += dd tokens = [int(x) for x in _tokens] self.model_tokens += tokens out: Any = None while len(to...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/rwkv.html
d1627a75897e-4
occurrence[token] += 1 logits = self.run_rnn([token]) xxx = self.tokenizer.decode(self.model_tokens[out_last:]) if "\ufffd" not in xxx: # avoid utf-8 display issues decoded += xxx out_last = begin + i + 1 if i >= self.max_tokens_per_ge...
https://api.python.langchain.com/en/stable/_modules/langchain/llms/rwkv.html
3adc13d982a8-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://api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html
3adc13d982a8-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://api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html