id
stringlengths
14
16
source
stringlengths
49
117
text
stringlengths
16
2.73k
f93c35a5f1e3-0
https://python.langchain.com/en/latest/_modules/langchain/llms/forefrontai.html
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...
f93c35a5f1e3-1
https://python.langchain.com/en/latest/_modules/langchain/llms/forefrontai.html
"""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 return values @property def _default_params(self) -> Mapping[str, ...
f93c35a5f1e3-2
https://python.langchain.com/en/latest/_modules/langchain/llms/forefrontai.html
"Content-Type": "application/json", }, json={"text": prompt, **self._default_params}, ) response_json = response.json() text = response_json["result"][0]["completion"] if stop is not None: # I believe this is required since the stop tokens ...
ec91f497f3e0-0
https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
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...
ec91f497f3e0-1
https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
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 the format specified in the content_type request header. """ @abstrac...
ec91f497f3e0-2
https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
region_name=region_name, credentials_profile_name=credentials_profile_name ) """ client: Any #: :meta private: endpoint_name: str = "" """The name of the endpoint from the deployed Sagemaker model. Must be unique within an AWS Region.""" region_name: str = "" """...
ec91f497f3e0-3
https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
"""Key word arguments to pass to the model.""" endpoint_kwargs: Optional[Dict] = None """Optional attributes passed to the invoke_endpoint function. See `boto3`_. docs for more info. .. _boto3: <https://boto3.amazonaws.com/v1/documentation/api/latest/index.html> """ class Config: """Conf...
ec91f497f3e0-4
https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
def _llm_type(self) -> str: """Return type of llm.""" return "sagemaker_endpoint" def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, ) -> str: """Call out to Sagemaker inference endpoint....
3c5853f73c86-0
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html
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...
3c5853f73c86-1
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html
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: """Configuration for this pydantic object.""" ...
3c5853f73c86-2
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html
except ImportError as e: raise ValueError( f"Could not load the {task} model due to missing dependencies." ) from e if importlib.util.find_spec("torch") is not None: import torch cuda_device_count = torch.cuda.device_count() if device <...
3c5853f73c86-3
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html
@property def _identifying_params(self) -> Mapping[str, Any]: """Get the identifying parameters.""" return { "model_id": self.model_id, "model_kwargs": self.model_kwargs, "pipeline_kwargs": self.pipeline_kwargs, } @property def _llm_type(self) -> s...
63b4321e5e67-0
https://python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html
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...
63b4321e5e67-1
https://python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html
"""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_from_dict_or_env( values, "anyscale_service_route", "ANYSCALE_SERVICE_R...
63b4321e5e67-2
https://python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html
stop: Optional list of stop words to use when generating. Returns: The string generated by the model. Example: .. code-block:: python response = anyscale("Tell me a joke.") """ anyscale_service_endpoint = ( f"{self.anyscale_service_url}...
9941fefb6b0a-0
https://python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html
Source code for langchain.llms.stochasticai """Wrapper around StochasticAI APIs.""" import logging import time 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...
9941fefb6b0a-1
https://python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html
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 @root_validator...
9941fefb6b0a-2
https://python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html
json={"prompt": prompt, "params": params}, headers={ "apiKey": f"{self.stochasticai_api_key}", "Accept": "application/json", "Content-Type": "application/json", }, ) response_post.raise_for_status() response_post_json = resp...
573cab5d56f3-0
https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
Source code for langchain.llms.self_hosted_hugging_face """Wrapper around HuggingFace Pipeline API to run on self-hosted remote hardware.""" import importlib.util import logging from typing import Any, Callable, List, Mapping, Optional from pydantic import Extra from langchain.callbacks.manager import CallbackManagerFo...
573cab5d56f3-1
https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
def _load_transformer( model_id: str = DEFAULT_MODEL_ID, task: str = DEFAULT_TASK, device: int = 0, model_kwargs: Optional[dict] = None, ) -> Any: """Inference function to send to the remote hardware. Accepts a huggingface model_id and returns a pipeline for the task. """ from transforme...
573cab5d56f3-2
https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
"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 associated with CUDA device id.", cuda_device_count, ) pipeline = ...
573cab5d56f3-3
https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
Example passing fn that generates a pipeline (bc the pipeline is not serializable): .. code-block:: python from langchain.llms import SelfHostedHuggingFaceLLM from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline import runhouse as rh def get_pipe...
573cab5d56f3-4
https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
"""Configuration for this pydantic object.""" extra = Extra.forbid def __init__(self, **kwargs: Any): """Construct the pipeline remotely using an auxiliary function. The load function needs to be importable to be imported and run on the server, i.e. in a module and not a REPL or clos...
8375355f167f-0
https://python.langchain.com/en/latest/_modules/langchain/llms/cohere.html
Source code for langchain.llms.cohere """Wrapper around Cohere 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 enforce_sto...
8375355f167f-1
https://python.langchain.com/en/latest/_modules/langchain/llms/cohere.html
truncate: Optional[str] = None """Specify how the client handles inputs longer than the maximum token length: Truncate from START, END or NONE""" cohere_api_key: Optional[str] = None stop: Optional[List[str]] = None class Config: """Configuration for this pydantic object.""" extra = ...
8375355f167f-2
https://python.langchain.com/en/latest/_modules/langchain/llms/cohere.html
self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, ) -> 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 ...
d194b5d081f7-0
https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
Source code for langchain.llms.aleph_alpha """Wrapper around Aleph Alpha APIs.""" from typing import Any, Dict, List, Optional, Sequence from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enforc...
d194b5d081f7-1
https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
presence_penalty: float = 0.0 """Penalizes repeated tokens.""" frequency_penalty: float = 0.0 """Penalizes repeated tokens according to frequency.""" repetition_penalties_include_prompt: Optional[bool] = False """Flag deciding whether presence penalty or frequency penalty are updated from the pr...
d194b5d081f7-2
https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
sequence_penalty_min_length: int = 2 use_multiplicative_sequence_penalty: bool = False completion_bias_inclusion: Optional[Sequence[str]] = None completion_bias_inclusion_first_token_only: bool = False completion_bias_exclusion: Optional[Sequence[str]] = None completion_bias_exclusion_first_token_on...
d194b5d081f7-3
https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
import aleph_alpha_client values["client"] = aleph_alpha_client.Client(token=aleph_alpha_api_key) except ImportError: raise ImportError( "Could not import aleph_alpha_client python package. " "Please install it with `pip install aleph_alpha_client`." ...
d194b5d081f7-4
https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
"use_multiplicative_sequence_penalty": self.use_multiplicative_sequence_penalty, # noqa: E501 "completion_bias_inclusion": self.completion_bias_inclusion, "completion_bias_inclusion_first_token_only": self.completion_bias_inclusion_first_token_only, # noqa: E501 "completion_bias_ex...
d194b5d081f7-5
https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
params = self._default_params if self.stop_sequences is not None and stop is not None: raise ValueError( "stop sequences found in both the input and default params." ) elif self.stop_sequences is not None: params["stop_sequences"] = self.stop_sequences...
2e471f84d25f-0
https://python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html
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...
2e471f84d25f-1
https://python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html
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 of llm.""" return "deepi...
2e471f84d25f-2
https://python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html
© Copyright 2023, Harrison Chase. Last updated on Jun 04, 2023.
db54ad32ef3c-0
https://python.langchain.com/en/latest/_modules/langchain/llms/ai21.html
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...
db54ad32ef3c-1
https://python.langchain.com/en/latest/_modules/langchain/llms/ai21.html
"""Penalizes repeated tokens according to count.""" frequencyPenalty: AI21PenaltyData = AI21PenaltyData() """Penalizes repeated tokens according to frequency.""" numResults: int = 1 """How many completions to generate for each prompt.""" logitBias: Optional[Dict[str, float]] = None """Adjust the...
db54ad32ef3c-2
https://python.langchain.com/en/latest/_modules/langchain/llms/ai21.html
"""Get the identifying parameters.""" return {**{"model": self.model}, **self._default_params} @property def _llm_type(self) -> str: """Return type of llm.""" return "ai21" def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Op...
db54ad32ef3c-3
https://python.langchain.com/en/latest/_modules/langchain/llms/ai21.html
optional_detail = response.json().get("error") raise ValueError( f"AI21 /complete call failed with status code {response.status_code}." f" Details: {optional_detail}" ) response_json = response.json() return response_json["completions"][0]["data"][...
76651b012e37-0
https://python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
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...
76651b012e37-1
https://python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
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 """Exponential penalty to the length.""" do_sample: bool = True """Whether to use sam...
76651b012e37-2
https://python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
"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, "remove_end_sequence": self.remove_end_sequence, "bad_words": self.bad_words,...
76651b012e37-3
https://python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
"NLPCloud only supports a single stop sequence per generation." "Pass in a list of length 1." ) elif stop and len(stop) == 1: end_sequence = stop[0] else: end_sequence = None response = self.client.generation( prompt, end_sequence=e...
982debb03433-0
https://python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html
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 ...
982debb03433-1
https://python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html
if field_name in extra: raise ValueError(f"Found {field_name} supplied twice.") logger.warning( f"""{field_name} was transfered to model_kwargs. Please confirm that {field_name} is what you intended.""" ) extra[f...
982debb03433-2
https://python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html
# a json specific to your model. "prompt": prompt, **params, } response = banana.run(api_key, model_key, model_inputs) try: text = response["modelOutputs"][0]["output"] except (KeyError, TypeError): returned = response["modelOutputs"][0] ...
7e7f232a3a80-0
https://python.langchain.com/en/latest/_modules/langchain/llms/human.html
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: ...
7e7f232a3a80-1
https://python.langchain.com/en/latest/_modules/langchain/llms/human.html
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. Args: prompt (str): The prompt to be displa...
25a88548a67f-0
https://python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html
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...
25a88548a67f-1
https://python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html
extra = values.get("model_kwargs", {}) for field_name in list(values): if field_name not in all_required_field_names: if field_name in extra: raise ValueError(f"Found {field_name} supplied twice.") logger.warning( f"""{field_nam...
25a88548a67f-2
https://python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html
"Could not import cerebrium python package. " "Please install it with `pip install cerebrium`." ) params = self.model_kwargs or {} response = model_api_request( self.endpoint_url, {"prompt": prompt, **params}, self.cerebriumai_api_key ) text = resp...
26919889f763-0
https://python.langchain.com/en/latest/_modules/langchain/llms/petals.html
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...
26919889f763-1
https://python.langchain.com/en/latest/_modules/langchain/llms/petals.html
max_length: Optional[int] = None """The maximum length of the sequence to be generated.""" model_kwargs: Dict[str, Any] = Field(default_factory=dict) """Holds any model parameters valid for `create` call not explicitly specified.""" huggingface_api_key: Optional[str] = None class Config: ...
26919889f763-2
https://python.langchain.com/en/latest/_modules/langchain/llms/petals.html
values["tokenizer"] = BloomTokenizerFast.from_pretrained(model_name) values["client"] = DistributedBloomForCausalLM.from_pretrained(model_name) values["huggingface_api_key"] = huggingface_api_key except ImportError: raise ValueError( "Could not import transfor...
26919889f763-3
https://python.langchain.com/en/latest/_modules/langchain/llms/petals.html
if stop is not None: # I believe this is required since the stop tokens # are not enforced by the model parameters text = enforce_stop_tokens(text, stop) return text By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 04, 2023.
acbe60dc84cd-0
https://python.langchain.com/en/latest/_modules/langchain/llms/fake.html
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 ...
b89d61c50d5c-0
https://python.langchain.com/en/latest/_modules/langchain/llms/pipelineai.html
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...
b89d61c50d5c-1
https://python.langchain.com/en/latest/_modules/langchain/llms/pipelineai.html
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 pipeline_kwargs. Please confirm that {field_name} ...
b89d61c50d5c-2
https://python.langchain.com/en/latest/_modules/langchain/llms/pipelineai.html
run = client.run_pipeline(self.pipeline_key, [prompt, params]) try: text = run.result_preview[0][0] except AttributeError: raise AttributeError( f"A pipeline run should have a `result_preview` attribute." f"Run was: {run}" ) if ...
48f3f05c617f-0
https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
Source code for langchain.llms.llamacpp """Wrapper around llama.cpp.""" import logging from typing import Any, Dict, Generator, List, Optional from pydantic import Field, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM logger = logging.getLogger(__name...
48f3f05c617f-1
https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
"""Use half-precision for key/value cache.""" logits_all: bool = Field(False, alias="logits_all") """Return logits for all tokens, not just the last token.""" vocab_only: bool = Field(False, alias="vocab_only") """Only load the vocabulary, no weights.""" use_mlock: bool = Field(False, alias="use_mlo...
48f3f05c617f-2
https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
repeat_penalty: Optional[float] = 1.1 """The penalty to apply to repeated tokens.""" top_k: Optional[int] = 40 """The top-k value to use for sampling.""" last_n_tokens_size: Optional[int] = 64 """The number of tokens to look back when applying the repeat_penalty.""" use_mmap: Optional[bool] = Tr...
48f3f05c617f-3
https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
) except Exception as e: raise ValueError( f"Could not load Llama model from path: {model_path}. " f"Received error {e}" ) return values @property def _default_params(self) -> Dict[str, Any]: """Get the default parameters for callin...
48f3f05c617f-4
https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
# llama_cpp expects the "stop" key not this, so we remove it: params.pop("stop_sequences") # then sets it as configured, or default to an empty list: params["stop"] = self.stop or stop or [] return params def _call( self, prompt: str, stop: Optional[List[str]]...
48f3f05c617f-5
https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
) -> Generator[Dict, None, None]: """Yields results objects as they are generated in real time. BETA: this is a beta feature while we figure out the right abstraction. Once that happens, this interface could change. It also calls the callback manager's on_llm_new_token event with ...
48f3f05c617f-6
https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
tokenized_text = self.client.tokenize(text.encode("utf-8")) return len(tokenized_text) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 04, 2023.
9548bb8296e9-0
https://python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html
Source code for langchain.llms.gooseai """Wrapper around GooseAI 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 import...
9548bb8296e9-1
https://python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html
n: int = 1 """How many completions to generate for each prompt.""" model_kwargs: Dict[str, Any] = Field(default_factory=dict) """Holds any model parameters valid for `create` call not explicitly specified.""" logit_bias: Optional[Dict[str, float]] = Field(default_factory=dict) """Adjust the probabil...
9548bb8296e9-2
https://python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html
openai.api_base = "https://api.goose.ai/v1" values["client"] = openai.Completion except ImportError: raise ImportError( "Could not import openai python package. " "Please install it with `pip install openai`." ) return values @prope...
9548bb8296e9-3
https://python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html
response = self.client.create(engine=self.model_name, prompt=prompt, **params) text = response.choices[0].text return text By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 04, 2023.
ec170480f731-0
https://python.langchain.com/en/latest/_modules/langchain/llms/modal.html
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....
ec170480f731-1
https://python.langchain.com/en/latest/_modules/langchain/llms/modal.html
Please confirm that {field_name} is what you intended.""" ) extra[field_name] = values.pop(field_name) values["model_kwargs"] = extra return values @property def _identifying_params(self) -> Mapping[str, Any]: """Get the identifying parameters.""" ...
2064188564fd-0
https://python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html
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...
2064188564fd-1
https://python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html
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_retry(...
2064188564fd-2
https://python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html
"""Maximum number of tokens to include in a candidate. Must be greater than zero. If unset, will default to 64.""" n: int = 1 """Number of chat completions to generate for each prompt. Note that the API may not return the full n completions if duplicates are generated.""" @root_validator() ...
2064188564fd-3
https://python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html
stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, ) -> LLMResult: generations = [] for prompt in prompts: completion = generate_with_retry( self, model=self.model_name, prompt=prompt, ...
35a92242ca9c-0
https://python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html
Source code for langchain.llms.promptlayer_openai """PromptLayer wrapper.""" import datetime from typing import List, Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun, ) from langchain.llms import OpenAI, OpenAIChat from langchain.schema import LLMResult...
35a92242ca9c-1
https://python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html
from promptlayer.utils import get_api_key, promptlayer_api_request request_start_time = datetime.datetime.now().timestamp() generated_responses = super()._generate(prompts, stop, run_manager) request_end_time = datetime.datetime.now().timestamp() for i in range(len(prompts)): ...
35a92242ca9c-2
https://python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html
resp = { "text": generation.text, "llm_output": generated_responses.llm_output, } pl_request_id = await promptlayer_api_request_async( "langchain.PromptLayerOpenAI.async", "langchain", [prompt], self....
35a92242ca9c-3
https://python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html
""" pl_tags: Optional[List[str]] return_pl_id: Optional[bool] = False def _generate( self, prompts: List[str], stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, ) -> LLMResult: """Call OpenAI generate and then call PromptLay...
35a92242ca9c-4
https://python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html
) -> LLMResult: from promptlayer.utils import get_api_key, promptlayer_api_request_async request_start_time = datetime.datetime.now().timestamp() generated_responses = await super()._agenerate(prompts, stop, run_manager) request_end_time = datetime.datetime.now().timestamp() for ...
e26dd70f1a34-0
https://python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html
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...
e26dd70f1a34-1
https://python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html
def _default_params(self) -> Dict[str, Any]: base_params = { "temperature": self.temperature, "max_output_tokens": self.max_output_tokens, "top_k": self.top_p, "top_p": self.top_k, } return {**base_params} def _predict(self, prompt: str, stop: ...
e26dd70f1a34-2
https://python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html
tuned_model_name = values.get("tuned_model_name") if tuned_model_name: values["client"] = TextGenerationModel.get_tuned_model(tuned_model_name) else: values["client"] = TextGenerationModel.from_pretrained(values["model_name"]) return values def _call( self, ...
e298183c4283-0
https://python.langchain.com/en/latest/_modules/langchain/llms/ctransformers.html
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...
e298183c4283-1
https://python.langchain.com/en/latest/_modules/langchain/llms/ctransformers.html
def _llm_type(self) -> str: """Return type of llm.""" return "ctransformers" @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that ``ctransformers`` package is installed.""" try: from ctransformers import AutoModelForCausalLM ...
e298183c4283-2
https://python.langchain.com/en/latest/_modules/langchain/llms/ctransformers.html
© Copyright 2023, Harrison Chase. Last updated on Jun 04, 2023.
d3225a388a6f-0
https://python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html
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...
d3225a388a6f-1
https://python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html
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 exists in environment.""" token = get_from_dict_or_env(values, "token", "PR...
d3225a388a6f-2
https://python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html
import predictionguard as pg params = self._default_params if self.stop is not None and stop is not None: raise ValueError("`stop` found in both the input and default params.") elif self.stop is not None: params["stop_sequences"] = self.stop else: para...
ca578177f6ef-0
https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
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, Extra, root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMR...
ca578177f6ef-1
https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
values, "anthropic_api_key", "ANTHROPIC_API_KEY" ) try: import anthropic values["client"] = anthropic.Client( api_key=anthropic_api_key, default_request_timeout=values["default_request_timeout"], ) values["HUMAN_PROMPT"] = a...
ca578177f6ef-2
https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
stop.extend([self.HUMAN_PROMPT]) return stop [docs]class Anthropic(LLM, _AnthropicCommon): r"""Wrapper around Anthropic's large language models. To use, you should have the ``anthropic`` python package installed, and the environment variable ``ANTHROPIC_API_KEY`` set with your API key, or pass i...
ca578177f6ef-3
https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
def _wrap_prompt(self, prompt: str) -> str: if not self.HUMAN_PROMPT or not self.AI_PROMPT: raise NameError("Please ensure the anthropic package is loaded") if prompt.startswith(self.HUMAN_PROMPT): return prompt # Already wrapped. # Guard against common errors in specify...
ca578177f6ef-4
https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
delta = data["completion"][len(current_completion) :] current_completion = data["completion"] if run_manager: run_manager.on_llm_new_token(delta, **data) return current_completion response = self.client.completion( prompt=self._wrap_pro...
ca578177f6ef-5
https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
prompt: The prompt to pass into the model. stop: Optional list of stop words to use when generating. Returns: A generator representing the stream of tokens from Anthropic. Example: .. code-block:: python prompt = "Write a poem about a stream." ...
6070efcd4f4f-0
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
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,...
6070efcd4f4f-1
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
response["choices"][0]["logprobs"] = stream_response["choices"][0]["logprobs"] def _streaming_response_template() -> Dict[str, Any]: return { "choices": [ { "text": "", "finish_reason": None, "logprobs": None, } ] } def _cre...
6070efcd4f4f-2
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
llm: Union[BaseOpenAI, OpenAIChat], **kwargs: Any ) -> Any: """Use tenacity to retry the async completion call.""" retry_decorator = _create_retry_decorator(llm) @retry_decorator async def _completion_with_retry(**kwargs: Any) -> Any: # Use OpenAI's async api https://github.com/openai/openai-pyt...
6070efcd4f4f-3
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
openai_api_base: Optional[str] = None openai_organization: Optional[str] = None # to support explicit proxy for OpenAI openai_proxy: Optional[str] = None batch_size: int = 20 """Batch size to use when passing multiple documents to generate.""" request_timeout: Optional[Union[float, Tuple[float, ...