id
stringlengths
14
16
text
stringlengths
31
2.41k
source
stringlengths
54
121
aa28b4b5edff-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/latest/_modules/langchain/llms/openllm.html
aa28b4b5edff-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/latest/_modules/langchain/llms/openllm.html
aa28b4b5edff-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/latest/_modules/langchain/llms/openllm.html
aa28b4b5edff-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/latest/_modules/langchain/llms/openllm.html
9ad2e0a02605-0
Source code for langchain.llms.huggingface_hub """Wrapper around HuggingFace APIs.""" from typing import Any, Dict, List, Mapping, Optional from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enf...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html
9ad2e0a02605-1
"""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.""" huggingfacehub_api_token = get_from_dict_or_env( values, "huggingfac...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html
9ad2e0a02605-2
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: The prompt to pass into the model. stop: Optional list of...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html
aeaeafa6f0b8-0
Source code for langchain.llms.forefrontai """Wrapper around ForefrontAI APIs.""" from typing import Any, Dict, List, Mapping, Optional import requests from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.util...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/forefrontai.html
aeaeafa6f0b8-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/latest/_modules/langchain/llms/forefrontai.html
aeaeafa6f0b8-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/latest/_modules/langchain/llms/forefrontai.html
b05c516b7cf6-0
Source code for langchain.llms.bananadev """Wrapper around Banana API.""" import logging from typing import Any, Dict, List, Mapping, Optional from pydantic import Extra, Field, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html
b05c516b7cf6-1
if field_name not in all_required_field_names: if field_name in extra: raise ValueError(f"Found {field_name} supplied twice.") logger.warning( f"""{field_name} was transfered to model_kwargs. Please confirm that {field_name} is ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html
b05c516b7cf6-2
) params = self.model_kwargs or {} params = {**params, **kwargs} api_key = self.banana_api_key model_key = self.model_key model_inputs = { # a json specific to your model. "prompt": prompt, **params, } response = banana.run(api_...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html
91a9c2c0e066-0
Source code for langchain.llms.anthropic """Wrapper around Anthropic APIs.""" import re import warnings from typing import Any, Callable, Dict, Generator, List, Mapping, Optional, Tuple, Union from pydantic import BaseModel, root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
91a9c2c0e066-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/latest/_modules/langchain/llms/anthropic.html
91a9c2c0e066-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/latest/_modules/langchain/llms/anthropic.html
91a9c2c0e066-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/latest/_modules/langchain/llms/anthropic.html
91a9c2c0e066-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/latest/_modules/langchain/llms/anthropic.html
91a9c2c0e066-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/latest/_modules/langchain/llms/anthropic.html
7393076f3330-0
Source code for langchain.llms.google_palm """Wrapper arround Google's PaLM Text APIs.""" from __future__ import annotations import logging from typing import Any, Callable, Dict, List, Optional from pydantic import BaseModel, root_validator from tenacity import ( before_sleep_log, retry, retry_if_exception...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html
7393076f3330-1
), before_sleep=before_sleep_log(logger, logging.WARNING), ) def generate_with_retry(llm: GooglePalm, **kwargs: Any) -> Any: """Use tenacity to retry the completion call.""" retry_decorator = _create_retry_decorator() @retry_decorator def _generate_with_retry(**kwargs: Any) -> Any: r...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html
7393076f3330-2
Must be positive.""" max_output_tokens: Optional[int] = None """Maximum number of tokens to include in a candidate. Must be greater than zero. If unset, will default to 64.""" n: int = 1 """Number of chat completions to generate for each prompt. Note that the API may not return the full n ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html
7393076f3330-3
return values def _generate( self, prompts: List[str], stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> LLMResult: generations = [] for prompt in prompts: completion = generate_with_r...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html
7bc0b3b6d851-0
Source code for langchain.llms.deepinfra """Wrapper around DeepInfra APIs.""" from typing import Any, Dict, List, Mapping, Optional import requests from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils im...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html
7bc0b3b6d851-1
return values @property def _identifying_params(self) -> Mapping[str, Any]: """Get the identifying parameters.""" return { **{"model_id": self.model_id}, **{"model_kwargs": self.model_kwargs}, } @property def _llm_type(self) -> str: """Return type ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html
7bc0b3b6d851-2
if res.status_code != 200: raise ValueError( "Error raised by inference API HTTP code: %s, %s" % (res.status_code, res.text) ) try: t = res.json() text = t["results"][0]["generated_text"] except requests.exceptions.JSONDecod...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html
466233e04674-0
Source code for langchain.llms.predictionguard """Wrapper around Prediction Guard APIs.""" import logging from typing import Any, Dict, List, Optional from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html
466233e04674-1
"""Your Prediction Guard access token.""" stop: Optional[List[str]] = None class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that the access token and python package ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html
466233e04674-2
Returns: The string generated by the model. Example: .. code-block:: python response = pgllm("Tell me a joke.") """ import predictionguard as pg params = self._default_params if self.stop is not None and stop is not None: raise ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html
7f185d3d5063-0
Source code for langchain.llms.openlm from typing import Any, Dict from pydantic import root_validator from langchain.llms.openai import BaseOpenAI [docs]class OpenLM(BaseOpenAI): @property def _invocation_params(self) -> Dict[str, Any]: return {**{"model": self.model_name}, **super()._invocation_params...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openlm.html
c5eee539fba7-0
Source code for langchain.llms.nlpcloud """Wrapper around NLPCloud APIs.""" from typing import Any, Dict, List, Mapping, Optional from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.utils import get_from_dict_or_e...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
c5eee539fba7-1
"""Total probability mass of tokens to consider at each step.""" top_k: int = 50 """The number of highest probability tokens to keep for top-k filtering.""" repetition_penalty: float = 1.0 """Penalizes repeated tokens. 1.0 means no penalty.""" length_penalty: float = 1.0 """Exponential penalty t...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
c5eee539fba7-2
@property def _default_params(self) -> Mapping[str, Any]: """Get the default parameters for calling NLPCloud API.""" return { "temperature": self.temperature, "min_length": self.min_length, "max_length": self.max_length, "length_no_input": self.length_...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
c5eee539fba7-3
Returns: The string generated by the model. Example: .. code-block:: python response = nlpcloud("Tell me a joke.") """ if stop and len(stop) > 1: raise ValueError( "NLPCloud only supports a single stop sequence per generation." ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
b24ad666a9e0-0
Source code for langchain.llms.cohere """Wrapper around Cohere APIs.""" from __future__ import annotations import logging from typing import Any, Callable, Dict, List, Optional from pydantic import Extra, root_validator from tenacity import ( before_sleep_log, retry, retry_if_exception_type, stop_after_...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/cohere.html
b24ad666a9e0-1
"""Wrapper around Cohere large language models. To use, you should have the ``cohere`` python package installed, and the environment variable ``COHERE_API_KEY`` set with your API key, or pass it as a named parameter to the constructor. Example: .. code-block:: python from langchain.l...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/cohere.html
b24ad666a9e0-2
extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" cohere_api_key = get_from_dict_or_env( values, "cohere_api_key", "COHERE_API_KEY" ) try: impor...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/cohere.html
b24ad666a9e0-3
"""Call out to Cohere's generate endpoint. Args: prompt: The prompt to pass into the model. stop: Optional list of stop words to use when generating. Returns: The string generated by the model. Example: .. code-block:: python respon...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/cohere.html
bc94350dcf5b-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
bc94350dcf5b-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/latest/_modules/langchain/llms/promptlayer_openai.html
bc94350dcf5b-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/latest/_modules/langchain/llms/promptlayer_openai.html
bc94350dcf5b-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/latest/_modules/langchain/llms/promptlayer_openai.html
bc94350dcf5b-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/latest/_modules/langchain/llms/promptlayer_openai.html
bc94350dcf5b-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/latest/_modules/langchain/llms/promptlayer_openai.html
68ae42b97792-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
68ae42b97792-1
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
68ae42b97792-2
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 around Google Vertex...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html
68ae42b97792-3
**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 Callbackmanager for LLM run, optional. Returns: The str...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html
52495bd4bb90-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
52495bd4bb90-1
) """ endpoint_url: str = ( "https://models.hosted-on.mosaicml.hosting/mpt-7b-instruct/v1/predict" ) """Endpoint URL to use.""" inject_instruction_format: bool = False """Whether to inject the instruction format into the prompt.""" model_kwargs: Optional[dict] = None """Key word ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html
52495bd4bb90-2
instruction=prompt, ) 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 i...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html
52495bd4bb90-3
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
3185287c4654-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
3185287c4654-1
logger.warning( f"""{field_name} was transfered to model_kwargs. Please confirm that {field_name} is what you intended.""" ) extra[field_name] = values.pop(field_name) values["model_kwargs"] = extra return values @property d...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/modal.html
b2f20384c6b5-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
b2f20384c6b5-1
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 huggingface model_id and retur...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
b2f20384c6b5-2
) if device < 0 and cuda_device_count > 0: logger.warning( "Device has %d GPUs available. " "Provide device={deviceId} to `from_model_id` to use available" "GPUs for execution. deviceId is -1 for CPU and " "can be a positive integer ass...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
b2f20384c6b5-3
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
b2f20384c6b5-4
"""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
3fb41742b28b-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
3fb41742b28b-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/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
3fb41742b28b-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/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
3fb41742b28b-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/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
3fb41742b28b-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/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
3fb41742b28b-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/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
f8cd799a2197-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
f8cd799a2197-1
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
ae490ba62939-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
ae490ba62939-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/latest/_modules/langchain/llms/pipelineai.html
ae490ba62939-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/latest/_modules/langchain/llms/pipelineai.html
f38ca04ac557-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
f38ca04ac557-1
"""The MIME type of the response data returned from endpoint""" @abstractmethod def transform_input(self, prompt: INPUT_TYPE, model_kwargs: Dict) -> bytes: """Transforms the input to a format that model can accept as the request Body. Should return bytes or seekable file like object in t...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
f38ca04ac557-2
) credentials_profile_name = ( "default" ) se = SagemakerEndpoint( endpoint_name=endpoint_name, region_name=region_name, credentials_profile_name=credentials_profile_name ) """ client: Any #: :meta p...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
f38ca04ac557-3
def transform_output(self, output: bytes) -> str: response_json = json.loads(output.read().decode("utf-8")) return response_json[0]["generated_text"] """ model_kwargs: Optional[Dict] = None """Key word arguments to pass to the model.""" endpoint_kwargs: Optional[D...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
f38ca04ac557-4
@property def _identifying_params(self) -> Mapping[str, Any]: """Get the identifying parameters.""" _model_kwargs = self.model_kwargs or {} return { **{"endpoint_name": self.endpoint_name}, **{"model_kwargs": _model_kwargs}, } @property def _llm_type(s...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
f38ca04ac557-5
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 making calls to the sagemaker endpoint. text = enforce_stop_tokens(text, stop) return text
https://api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
e2037d2aa88a-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
e2037d2aa88a-1
f16_kv: bool = Field(True, alias="f16_kv") """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.""" ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
e2037d2aa88a-2
"""Whether to echo the prompt.""" stop: Optional[List[str]] = [] """A list of strings to stop generation when encountered.""" 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_token...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
e2037d2aa88a-3
except ImportError: raise ModuleNotFoundError( "Could not import llama-cpp-python library. " "Please install the llama-cpp-python library to " "use this embedding model: pip install llama-cpp-python" ) except Exception as e: rai...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
e2037d2aa88a-4
Returns: Dictionary containing the combined parameters. """ # Raise error if stop sequences are in both input and default params if self.stop and stop is not None: raise ValueError("`stop` found in both the input and default params.") params = self._default_params...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
e2037d2aa88a-5
return combined_text_output else: params = self._get_parameters(stop) params = {**params, **kwargs} result = self.client(prompt=prompt, **params) return result["choices"][0]["text"] [docs] def stream( self, prompt: str, stop: Optional[Li...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
e2037d2aa88a-6
""" params = self._get_parameters(stop) result = self.client(prompt=prompt, stream=True, **params) for chunk in result: token = chunk["choices"][0]["text"] log_probs = chunk["choices"][0].get("logprobs", None) if run_manager: run_manager.on_llm...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
d1f654c4abbb-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
d1f654c4abbb-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/latest/_modules/langchain/llms/azureml_endpoint.html
d1f654c4abbb-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/latest/_modules/langchain/llms/azureml_endpoint.html
d1f654c4abbb-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/latest/_modules/langchain/llms/azureml_endpoint.html
d1f654c4abbb-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/latest/_modules/langchain/llms/azureml_endpoint.html
28d1eb6acef6-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
28d1eb6acef6-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/latest/_modules/langchain/llms/amazon_api_gateway.html
a7214af167b7-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
a7214af167b7-1
max_length=50) llm._deploy() call_result = llm._call(input) """ model_name: str = "" name: str = "" cpu: str = "" memory: str = "" gpu: str = "" python_version: str = "" python_packages: List[str] = [] max_length: str = "" url: str = "" """model endpoi...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/beam.html
a7214af167b7-2
@root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" beam_client_id = get_from_dict_or_env( values, "beam_client_id", "BEAM_CLIENT_ID" ) beam_client_secret = get_from_dict_or_env( ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/beam.html
a7214af167b7-3
python_packages={python_packages}, ) app.Trigger.RestAPI( inputs={{"prompt": beam.Types.String(), "max_length": beam.Types.String()}}, outputs={{"text": beam.Types.String()}}, handler="run.py:beam_langchain", ) """ ) script_name = "app....
https://api.python.langchain.com/en/latest/_modules/langchain/llms/beam.html
a7214af167b7-4
file.write(script.format(model_name=self.model_name)) def _deploy(self) -> str: """Call to Beam.""" try: import beam # type: ignore if beam.__path__ == "": raise ImportError except ImportError: raise ImportError( "Could not...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/beam.html
a7214af167b7-5
self, prompt: str, stop: Optional[list] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Call to Beam.""" url = "https://apps.beam.cloud/" + self.app_id if self.app_id else self.url payload = {"prompt": prompt, "max_l...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/beam.html
5fe6e6d8f65c-0
Source code for langchain.callbacks.clearml_callback import tempfile from copy import deepcopy from pathlib import Path from typing import Any, Dict, List, Optional, Sequence, Union from langchain.callbacks.base import BaseCallbackHandler from langchain.callbacks.utils import ( BaseMetadataCallbackHandler, flat...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html
5fe6e6d8f65c-1
and adds the response to the list of records for both the {method}_records and action. It then logs the response to the ClearML console. """ def __init__( self, task_type: Optional[str] = "inference", project_name: Optional[str] = "langchain_callback_demo", tags: Optional[Seq...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html
5fe6e6d8f65c-2
) self.logger.report_text(warning, level=30, print_console=True) self.callback_columns: list = [] self.action_records: list = [] self.complexity_metrics = complexity_metrics self.visualize = visualize self.nlp = spacy.load("en_core_web_sm") def _init_resp(self) -> Dic...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html
5fe6e6d8f65c-3
if self.stream_logs: self.logger.report_text(resp) [docs] def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None: """Run when LLM ends running.""" self.step += 1 self.llm_ends += 1 self.ends += 1 resp = self._init_resp() resp.update({"action": "on...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html