id
stringlengths
14
16
text
stringlengths
4
1.28k
source
stringlengths
54
121
e803b998817f-7
) text = response.generations[0].text # If stop tokens are provided, Cohere's endpoint returns them. # 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"]...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/cohere.html
c642d54e6b0f-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/latest/_modules/langchain/llms/promptlayer_openai.html
c642d54e6b0f-1
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/latest/_modules/langchain/llms/promptlayer_openai.html
c642d54e6b0f-2
) -> LLMResult: """Call OpenAI generate and then call PromptLayer API to log the request.""" from promptlayer.utils import get_api_key, promptlayer_api_request request_start_time = datetime.datetime.now().timestamp() generated_responses = super()._generate(prompts, stop, run_manager) ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html
c642d54e6b0f-3
params, self.pl_tags, resp, request_start_time, request_end_time, get_api_key(), return_pl_id=self.return_pl_id, ) if self.return_pl_id: if generation.generation_info is None or not is...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html
c642d54e6b0f-4
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/latest/_modules/langchain/llms/promptlayer_openai.html
c642d54e6b0f-5
if self.return_pl_id: if generation.generation_info is None or not isinstance( generation.generation_info, dict ): generation.generation_info = {} generation.generation_info["pl_request_id"] = pl_request_id return generated_...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html
c642d54e6b0f-6
``return_pl_id``: If True, the PromptLayer request ID will be returned in the ``generation_info`` field of the ``Generation`` object. Example: .. code-block:: python from langchain.llms import PromptLayerOpenAIChat openaichat = PromptLayerOpenAIChat(model_name...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html
c642d54e6b0f-7
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)): ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html
c642d54e6b0f-8
get_api_key(), return_pl_id=self.return_pl_id, ) if self.return_pl_id: if generation.generation_info is None or not isinstance( generation.generation_info, dict ): generation.generation_info = {} ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html
c642d54e6b0f-9
for i in range(len(prompts)): prompt = prompts[i] generation = generated_responses.generations[i][0] resp = { "text": generation.text, "llm_output": generated_responses.llm_output, } params = {**self._identifying_params, **kwarg...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html
c642d54e6b0f-10
generation.generation_info = {} generation.generation_info["pl_request_id"] = pl_request_id return generated_responses
https://api.python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html
53999eb5b92f-0
Source code for langchain.llms.vertexai """Wrapper around Google VertexAI models.""" from typing import TYPE_CHECKING, Any, Dict, List, Optional from pydantic import BaseModel, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils i...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html
53999eb5b92f-1
temperature: float = 0.0 "Sampling temperature, it controls the degree of randomness in token selection." max_output_tokens: int = 128 "Token limit determines the maximum amount of text output from one prompt." top_p: float = 0.95 "Tokens are selected from most probable to least until the sum of the...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html
53999eb5b92f-2
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 calls. If not provided, credentials will be ascertained from " "the environment." @property ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html
53999eb5b92f-3
"top_k": self.top_k, "top_p": self.top_p, } def _predict( self, prompt: str, stop: Optional[List[str]] = None, **kwargs: Any ) -> str: params = {**self._default_params, **kwargs} res = self.client.predict(prompt, **params) return self._enforce_stop_wor...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html
53999eb5b92f-4
@classmethod def _try_init_vertexai(cls, values: Dict) -> None: allowed_params = ["project", "location", "credentials"] params = {k: v for k, v in values.items() if k in allowed_params} init_vertexai(**params) return None [docs]class VertexAI(_VertexAICommon, LLM): """Wrapper aro...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html
53999eb5b92f-5
cls._try_init_vertexai(values) tuned_model_name = values.get("tuned_model_name") model_name = values["model_name"] try: if tuned_model_name or not is_codey_model(model_name): from vertexai.preview.language_models import TextGenerationModel if tuned_mod...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html
53999eb5b92f-6
run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Call Vertex model to get predictions based on the prompt. Args: prompt: The prompt to pass into the model. stop: A list of stop words (optional). run_manager: A Callbackman...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html
8487674cfd4c-0
Source code for langchain.llms.mosaicml """Wrapper around MosaicML APIs.""" from typing import Any, Dict, List, Mapping, Optional import requests from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils impo...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html
8487674cfd4c-1
instruction="{instruction}", response_key=RESPONSE_KEY, ) [docs]class MosaicML(LLM): """Wrapper around MosaicML's LLM inference service. To use, you should have the environment variable ``MOSAICML_API_TOKEN`` set with your API token, or pass it as a named parameter to the constructor. Example: ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html
8487674cfd4c-2
endpoint_url: str = ( "https://models.hosted-on.mosaicml.hosting/mpt-7b-instruct/v1/predict" ) """Endpoint URL to use.""" inject_instruction_format: bool = False """Whether to inject the instruction format into the prompt.""" model_kwargs: Optional[dict] = None """Key word arguments to p...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html
8487674cfd4c-3
values, "mosaicml_api_token", "MOSAICML_API_TOKEN" ) values["mosaicml_api_token"] = mosaicml_api_token return values @property def _identifying_params(self) -> Mapping[str, Any]: """Get the identifying parameters.""" _model_kwargs = self.model_kwargs or {} return ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html
8487674cfd4c-4
) return prompt def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, is_retry: bool = False, **kwargs: Any, ) -> str: """Call out to a MosaicML LLM inference endpoint. Args:...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html
8487674cfd4c-5
payload.update(_model_kwargs) payload.update(kwargs) # HTTP headers for authorization headers = { "Authorization": f"{self.mosaicml_api_token}", "Content-Type": "application/json", } # send request try: response = requests.post(self.end...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html
8487674cfd4c-6
raise ValueError( f"Error raised by inference API: {parsed_response['error']}" ) # The inference API has changed a couple of times, so we add some handling # to be robust to multiple response formats. if isinstance(parsed_response, dict): ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html
8487674cfd4c-7
text = first_item elif isinstance(first_item, dict): if "output" in parsed_response: text = first_item["output"] else: raise ValueError( f"No key data or output in response: {parsed_respon...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html
c9884fe36a46-0
Source code for langchain.llms.modal """Wrapper around Modal API.""" import logging from typing import Any, Dict, List, Mapping, Optional import requests from pydantic import Extra, Field, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain....
https://api.python.langchain.com/en/latest/_modules/langchain/llms/modal.html
c9884fe36a46-1
endpoint_url: str = "" """model endpoint to use""" model_kwargs: Dict[str, Any] = Field(default_factory=dict) """Holds any model parameters valid for `create` call not explicitly specified.""" class Config: """Configuration for this pydantic config.""" extra = Extra.forbid @root_...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/modal.html
c9884fe36a46-2
logger.warning( f"""{field_name} was transfered to model_kwargs. Please confirm that {field_name} is what you intended.""" ) extra[field_name] = values.pop(field_name) values["model_kwargs"] = extra return values @property d...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/modal.html
c9884fe36a46-3
**kwargs: Any, ) -> str: """Call to Modal endpoint.""" params = self.model_kwargs or {} params = {**params, **kwargs} response = requests.post( url=self.endpoint_url, headers={ "Content-Type": "application/json", }, json...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/modal.html
217222ca0682-0
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...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
217222ca0682-1
) -> str: """Inference function to send to the remote hardware. Accepts a Hugging Face pipeline (or more likely, a key pointing to such a pipeline on the cluster's object store) and returns generated text. """ response = pipeline(prompt, *args, **kwargs) if pipeline.task == "text-generation"...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
217222ca0682-2
if stop is not None: text = enforce_stop_tokens(text, stop) return text 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 h...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
217222ca0682-3
if task == "text-generation": model = AutoModelForCausalLM.from_pretrained(model_id, **_model_kwargs) elif task in ("text2text-generation", "summarization"): model = AutoModelForSeq2SeqLM.from_pretrained(model_id, **_model_kwargs) else: raise ValueError( ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
217222ca0682-4
f"device is required to be within [-1, {cuda_device_count})" ) if device < 0 and cuda_device_count > 0: logger.warning( "Device has %d GPUs available. " "Provide device={deviceId} to `from_model_id` to use available" "GPUs for execution. de...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
217222ca0682-5
) return pipeline [docs]class SelfHostedHuggingFaceLLM(SelfHostedPipeline): """Wrapper around HuggingFace Pipeline API to run on self-hosted remote hardware. Supported hardware includes auto-launched instances on AWS, GCP, Azure, and Lambda, as well as servers specified by IP address and SSH credent...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
217222ca0682-6
hf = SelfHostedHuggingFaceLLM( model_id="google/flan-t5-large", task="text2text-generation", hardware=gpu ) Example passing fn that generates a pipeline (bc the pipeline is not serializable): .. code-block:: python from langchain.llms import SelfHosted...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
217222ca0682-7
model_load_fn=get_pipeline, model_id="gpt2", hardware=gpu) """ model_id: str = DEFAULT_MODEL_ID """Hugging Face model_id to load the model.""" task: str = DEFAULT_TASK """Hugging Face task ("text-generation", "text2text-generation" or "summarization").""" device: int = 0 """Device to use...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
217222ca0682-8
"""Function to load the model remotely on the server.""" inference_fn: Callable = _generate_text #: :meta private: """Inference function to send to the remote hardware.""" class Config: """Configuration for this pydantic object.""" extra = Extra.forbid def __init__(self, **kwargs: Any):...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
217222ca0682-9
} super().__init__(load_fn_kwargs=load_fn_kwargs, **kwargs) @property def _identifying_params(self) -> Mapping[str, Any]: """Get the identifying parameters.""" return { **{"model_id": self.model_id}, **{"model_kwargs": self.model_kwargs}, } @property ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
62b970dc7958-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/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
62b970dc7958-1
- top_p: The cumulative probability threshold for generating text. - typical_p: The typical probability threshold for generating text. - temperature: The temperature to use when generating text. - repetition_penalty: The repetition penalty to use when generating text. - stop_sequences: A list of stop se...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
62b970dc7958-2
- _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/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
62b970dc7958-3
llm = HuggingFaceTextGenInference( inference_server_url = "http://localhost:8010/", max_new_tokens = 512, top_k = 10, top_p = 0.95, typical_p = 0.95, temperature = 0.01, repetition_penalty = 1.03, ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
62b970dc7958-4
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/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
62b970dc7958-5
**values["server_kwargs"], ) except ImportError: raise ImportError( "Could not import text_generation python package. " "Please install it with `pip install text_generation`." ) return values @property def _llm_type(self) -> str...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
62b970dc7958-6
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, repetition_penalty=self.repetition_penalty, seed=self.seed,...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
62b970dc7958-7
"top_k": self.top_k, "top_p": self.top_p, "typical_p": self.typical_p, "temperature": self.temperature, "repetition_penalty": self.repetition_penalty, "seed": self.seed, } text = "" for res in self.client...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
62b970dc7958-8
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: res = await self.async_client.generate( prompt, ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
62b970dc7958-9
: res.generated_text.index(stop_seq) ] text: str = res.generated_text else: text_callback = None if run_manager: text_callback = partial( run_manager.on_llm_new_token, verbose=self.verbose ) p...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
62b970dc7958-10
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 text_callback: ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
c176425d0aad-0
Source code for langchain.llms.manifest """Wrapper around HazyResearch's Manifest library.""" 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 [docs]class ManifestWrapper(...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/manifest.html
c176425d0aad-1
except ImportError: raise ValueError( "Could not import manifest python package. " "Please install it with `pip install manifest-ml`." ) return values @property def _identifying_params(self) -> Mapping[str, Any]: kwargs = self.llm_kwargs or...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/manifest.html
c176425d0aad-2
if stop is not None and len(stop) != 1: raise NotImplementedError( f"Manifest currently only supports a single stop token, got {stop}" ) params = self.llm_kwargs or {} params = {**params, **kwargs} if stop is not None: params["stop_token"] = st...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/manifest.html
f1307184d796-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/latest/_modules/langchain/llms/pipelineai.html
f1307184d796-1
.. code-block:: python from langchain import PipelineAI pipeline = PipelineAI(pipeline_key="") """ pipeline_key: str = "" """The id or tag of the target pipeline""" pipeline_kwargs: Dict[str, Any] = Field(default_factory=dict) """Holds any pipeline parameters valid for `creat...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/pipelineai.html
f1307184d796-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 pipeline_kwargs. ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/pipelineai.html
f1307184d796-3
return values @property def _identifying_params(self) -> Mapping[str, Any]: """Get the identifying parameters.""" return { **{"pipeline_key": self.pipeline_key}, **{"pipeline_kwargs": self.pipeline_kwargs}, } @property def _llm_type(self) -> str: "...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/pipelineai.html
f1307184d796-4
"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/latest/_modules/langchain/llms/pipelineai.html
c2e58a656166-0
Source code for langchain.llms.sagemaker_endpoint """Wrapper around Sagemaker InvokeEndpoint API.""" from abc import abstractmethod from typing import Any, Dict, Generic, List, Mapping, Optional, TypeVar, Union from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun f...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
c2e58a656166-1
""" """ Example: .. code-block:: python class ContentHandler(ContentHandlerBase): content_type = "application/json" accepts = "application/json" def transform_input(self, prompt: str, model_kwargs: Dict) -> bytes: input_str ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
c2e58a656166-2
@abstractmethod def transform_input(self, prompt: INPUT_TYPE, model_kwargs: Dict) -> bytes: """Transforms the input to a format that model can accept as the request Body. Should return bytes or seekable file like object in the format specified in the content_type request header. ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
c2e58a656166-3
To authenticate, the AWS client uses the following methods to automatically load credentials: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html If a specific credential profile should be used, you must pass the name of the profile from the ~/.aws/credentials file that is to ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
c2e58a656166-4
se = SagemakerEndpoint( endpoint_name=endpoint_name, 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...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
c2e58a656166-5
credentials from IMDS will be used. See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html """ content_handler: LLMContentHandler """The content handler class that provides an input and output transform functions to handle formats between LLM and the endpoint. ""...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
c2e58a656166-6
response_json = json.loads(output.read().decode("utf-8")) return response_json[0]["generated_text"] """ model_kwargs: Optional[Dict] = None """Key word arguments to pass to the model.""" endpoint_kwargs: Optional[Dict] = None """Optional attributes passed to the invoke_endpoint ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
c2e58a656166-7
import boto3 try: if values["credentials_profile_name"] is not None: session = boto3.Session( profile_name=values["credentials_profile_name"] ) else: # use default credentials ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
c2e58a656166-8
return values @property def _identifying_params(self) -> Mapping[str, Any]: """Get the identifying parameters.""" _model_kwargs = self.model_kwargs or {} return { **{"endpoint_name": self.endpoint_name}, **{"model_kwargs": _model_kwargs}, } @property ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
c2e58a656166-9
stop: Optional list of stop words to use when generating. Returns: The string generated by the model. Example: .. code-block:: python response = se("Tell me a joke.") """ _model_kwargs = self.model_kwargs or {} _model_kwargs = {**_model_kwa...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
c2e58a656166-10
) except Exception as e: raise ValueError(f"Error raised by inference endpoint: {e}") text = self.content_handler.transform_output(response["Body"]) if stop is not None: # This is a bit hacky, but I can't figure out a better way to enforce # stop tokens when m...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
bf1f7cccb064-0
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...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
bf1f7cccb064-1
""" client: Any #: :meta private: model_path: str """The path to the Llama model file.""" lora_base: Optional[str] = None """The path to the Llama LoRA base model.""" lora_path: Optional[str] = None """The path to the Llama LoRA. If None, no LoRa is loaded.""" n_ctx: int = Field(512, al...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
bf1f7cccb064-2
"""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...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
bf1f7cccb064-3
"""Number of layers to be loaded into gpu memory. Default None.""" suffix: Optional[str] = Field(None) """A suffix to append to the generated text. If None, no suffix is appended.""" max_tokens: Optional[int] = 256 """The maximum number of tokens to generate.""" temperature: Optional[float] = 0.8 ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
bf1f7cccb064-4
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...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
bf1f7cccb064-5
"n_parts", "seed", "f16_kv", "logits_all", "vocab_only", "use_mlock", "n_threads", "n_batch", "use_mmap", "last_n_tokens_size", ] model_params = {k: values[k] for k in model_param_names} #...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
bf1f7cccb064-6
"use this embedding model: pip install llama-cpp-python" ) 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...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
bf1f7cccb064-7
} @property def _identifying_params(self) -> Dict[str, Any]: """Get the identifying parameters.""" return {**{"model_path": self.model_path}, **self._default_params} @property def _llm_type(self) -> str: """Return type of llm.""" return "llamacpp" def _get_parameters(...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
bf1f7cccb064-8
raise ValueError("`stop` found in both the input and default params.") params = self._default_params # 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...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
bf1f7cccb064-9
The generated text. Example: .. code-block:: python from langchain.llms import LlamaCpp llm = LlamaCpp(model_path="/path/to/local/llama/model.bin") llm("This is a prompt.") """ if self.streaming: # If streaming is enabled, w...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
bf1f7cccb064-10
return result["choices"][0]["text"] [docs] def stream( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, ) -> Generator[Dict, None, None]: """Yields results objects as they are generated in real time. BETA:...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
bf1f7cccb064-11
Yields: A dictionary like objects containing a string token and metadata. See llama-cpp-python docs and below for more. Example: .. code-block:: python from langchain.llms import LlamaCpp llm = LlamaCpp( model_path="/path/to...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
bf1f7cccb064-12
log_probs = chunk["choices"][0].get("logprobs", None) if run_manager: run_manager.on_llm_new_token( token=token, verbose=self.verbose, log_probs=log_probs ) yield chunk [docs] def get_num_tokens(self, text: str) -> int: tokenized_tex...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
ef1aef0ca793-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/latest/_modules/langchain/llms/azureml_endpoint.html
ef1aef0ca793-1
self.deployment_name = deployment_name def call(self, body: bytes) -> bytes: """call.""" # The azureml-model-deployment header will force the request to go to a # specific deployment. Remove this header to have the request observe the # endpoint traffic rules. headers = { ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html
ef1aef0ca793-2
.. 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/latest/_modules/langchain/llms/azureml_endpoint.html
ef1aef0ca793-3
"""The MIME type of the response data returned form the endpoint""" @abstractmethod def format_request_payload(self, prompt: str, model_kwargs: Dict) -> bytes: """Formats the request body according to the input schema of the model. Returns bytes or seekable file like object in the format...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html
ef1aef0ca793-4
input_str = json.dumps( {"inputs": {"input_string": [prompt]}, "parameters": model_kwargs} ) 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(Cont...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html
ef1aef0ca793-5
class DollyContentFormatter(ContentFormatterBase): """Content handler for the Dolly-v2-12b model""" def format_request_payload(self, prompt: str, model_kwargs: Dict) -> bytes: input_str = json.dumps( {"input_data": {"input_string": [prompt]}, "parameters": model_kwargs} ) ret...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html
ef1aef0ca793-6
endpoint_api_key="my-api-key", deployment_name="my-deployment-name", content_formatter=content_formatter, ) """ # noqa: E501 endpoint_url: str = "" """URL of pre-existing Endpoint. Should be passed to constructor or specified as env var `AZUREML_ENDPOINT...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html
ef1aef0ca793-7
the endpoint""" model_kwargs: Optional[dict] = None """Key word arguments to pass to the model.""" @validator("http_client", always=True, allow_reuse=True) @classmethod def validate_client(cls, field_value: Any, values: Dict) -> AzureMLEndpointClient: """Validate that api key and python pack...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html
ef1aef0ca793-8
return http_client @property def _identifying_params(self) -> Mapping[str, Any]: """Get the identifying parameters.""" _model_kwargs = self.model_kwargs or {} return { **{"deployment_name": self.deployment_name}, **{"model_kwargs": _model_kwargs}, } @p...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html
ef1aef0ca793-9
stop: Optional list of stop words to use when generating. Returns: The string generated by the model. Example: .. code-block:: python response = azureml_model("Tell me a joke.") """ _model_kwargs = self.model_kwargs or {} body = self.conten...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html
a841f27d31a3-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/latest/_modules/langchain/llms/amazon_api_gateway.html
a841f27d31a3-1
[docs]class AmazonAPIGateway(LLM): """Wrapper around custom Amazon API Gateway""" api_url: str """API Gateway URL""" model_kwargs: Optional[Dict] = None """Key word arguments to pass to the model.""" content_handler: ContentHandlerAmazonAPIGateway = ContentHandlerAmazonAPIGateway() """The co...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/amazon_api_gateway.html
a841f27d31a3-2
} @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, **kwargs: Any, ) -> str: "...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/amazon_api_gateway.html
a841f27d31a3-3
try: response = requests.post( self.api_url, json=payload, ) text = self.content_handler.transform_output(response) except Exception as error: raise ValueError(f"Error raised by the service: {error}") if stop is not None: ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/amazon_api_gateway.html
705eaf3c22a2-0
Source code for langchain.llms.beam """Wrapper around Beam API.""" import base64 import json import logging import subprocess import textwrap import time from typing import Any, Dict, List, Mapping, Optional import requests from pydantic import Extra, Field, root_validator from langchain.callbacks.manager import Callba...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/beam.html
705eaf3c22a2-1
to get these is available here: https://docs.beam.cloud/account/api-keys. The wrapper can then be called as follows, where the name, cpu, memory, gpu, python version, and python packages can be updated accordingly. Once deployed, the instance can be called. Example: .. code-block:: python ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/beam.html