id
stringlengths
14
16
text
stringlengths
29
2.73k
source
stringlengths
49
115
11a099a1d2b8-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://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html
11a099a1d2b8-1
@root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" huggingfacehub_api_token = get_from_dict_or_env( values, "huggingfacehub_api_token", "HUGGINGFACEHUB_API_TOKEN" ) try: ...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html
11a099a1d2b8-2
) -> str: """Call out to HuggingFace Hub's inference endpoint. Args: prompt: The prompt to pass into the model. stop: Optional list of stop words to use when generating. Returns: The string generated by the model. Example: .. code-block:: p...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html
295197187008-0
Source code for langchain.llms.cerebriumai """Wrapper around CerebriumAI API.""" import logging from typing import Any, Dict, List, Mapping, Optional from pydantic import Extra, Field, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms...
https://python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html
295197187008-1
all_required_field_names = {field.alias for field in cls.__fields__.values()} extra = values.get("model_kwargs", {}) for field_name in list(values): if field_name not in all_required_field_names: if field_name in extra: raise ValueError(f"Found {field_name...
https://python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html
295197187008-2
try: from cerebrium import model_api_request except ImportError: raise ValueError( "Could not import cerebrium python package. " "Please install it with `pip install cerebrium`." ) params = self.model_kwargs or {} response = mod...
https://python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html
22c3f03df076-0
Source code for langchain.llms.huggingface_pipeline """Wrapper around HuggingFace Pipeline APIs.""" import importlib.util import logging from typing import Any, List, Mapping, Optional from pydantic import Extra from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from la...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html
22c3f03df076-1
"""Model name to use.""" model_kwargs: Optional[dict] = None """Key word arguments to pass to the model.""" class Config: """Configuration for this pydantic object.""" extra = Extra.forbid [docs] @classmethod def from_model_id( cls, model_id: str, task: str, ...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html
22c3f03df076-2
if importlib.util.find_spec("torch") is not None: import torch cuda_device_count = torch.cuda.device_count() if device < -1 or (device >= cuda_device_count): raise ValueError( f"Got device=={device}, " f"device is required to be...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html
22c3f03df076-3
self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, ) -> str: response = self.pipeline(prompt) if self.pipeline.task == "text-generation": # Text generation return includes the starter text. text...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html
4fdfcb070dbd-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://python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html
4fdfcb070dbd-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://python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html
4fdfcb070dbd-2
text = enforce_stop_tokens(text, stop) return text By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 02, 2023.
https://python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html
85171bbf8502-0
Source code for langchain.llms.openai """Wrapper around OpenAI APIs.""" from __future__ import annotations import logging import sys import warnings from typing import ( AbstractSet, Any, Callable, Collection, Dict, Generator, List, Literal, Mapping, Optional, Set, Tuple,...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
85171bbf8502-1
"finish_reason" ] response["choices"][0]["logprobs"] = stream_response["choices"][0]["logprobs"] def _streaming_response_template() -> Dict[str, Any]: return { "choices": [ { "text": "", "finish_reason": None, "logprobs": None, ...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
85171bbf8502-2
return llm.client.create(**kwargs) return _completion_with_retry(**kwargs) async def acompletion_with_retry( llm: Union[BaseOpenAI, OpenAIChat], **kwargs: Any ) -> Any: """Use tenacity to retry the async completion call.""" retry_decorator = _create_retry_decorator(llm) @retry_decorator async de...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
85171bbf8502-3
model_kwargs: Dict[str, Any] = Field(default_factory=dict) """Holds any model parameters valid for `create` call not explicitly specified.""" openai_api_key: Optional[str] = None openai_api_base: Optional[str] = None openai_organization: Optional[str] = None batch_size: int = 20 """Batch size to...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
85171bbf8502-4
) return OpenAIChat(**data) return super().__new__(cls) class Config: """Configuration for this pydantic object.""" extra = Extra.ignore @root_validator(pre=True) def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]: """Build extra kwargs from additional...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
85171bbf8502-5
try: import openai openai.api_key = openai_api_key if openai_api_base: openai.api_base = openai_api_base if openai_organization: openai.organization = openai_organization values["client"] = openai.Completion except Impor...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
85171bbf8502-6
run_manager: Optional[CallbackManagerForLLMRun] = None, ) -> LLMResult: """Call out to OpenAI's endpoint with k unique prompts. Args: prompts: The prompts to pass into the model. stop: Optional list of stop words to use when generating. Returns: The full L...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
85171bbf8502-7
choices.extend(response["choices"]) if not self.streaming: # Can't update token usage if streaming update_token_usage(_keys, response, token_usage) return self.create_llm_result(choices, prompts, token_usage) async def _agenerate( self, prompts: Li...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
85171bbf8502-8
choices.extend(response["choices"]) if not self.streaming: # Can't update token usage if streaming update_token_usage(_keys, response, token_usage) return self.create_llm_result(choices, prompts, token_usage) def get_sub_prompts( self, params: Dict...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
85171bbf8502-9
logprobs=choice.get("logprobs"), ), ) for choice in sub_choices ] ) llm_output = {"token_usage": token_usage, "model_name": self.model_name} return LLMResult(generations=generations, llm_output=llm_output) de...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
85171bbf8502-10
@property def _invocation_params(self) -> Dict[str, Any]: """Get the parameters used to invoke the model.""" return self._default_params @property def _identifying_params(self) -> Mapping[str, Any]: """Get the identifying parameters.""" return {**{"model_name": self.model_nam...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
85171bbf8502-11
Returns: The maximum context size Example: .. code-block:: python max_tokens = openai.modelname_to_contextsize("text-davinci-003") """ model_token_mapping = { "gpt-4": 8192, "gpt-4-0314": 8192, "gpt-4-32k": 32768, ...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
85171bbf8502-12
return context_size def max_tokens_for_prompt(self, prompt: str) -> int: """Calculate the maximum number of tokens possible to generate for a prompt. Args: prompt: The prompt to pass into the model. Returns: The maximum number of tokens to generate for a prompt. ...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
85171bbf8502-13
Any parameters that are valid to be passed to the openai.create call can be passed in, even if not explicitly saved on this class. Example: .. code-block:: python from langchain.llms import AzureOpenAI openai = AzureOpenAI(model_name="text-davinci-003") """ deployment_nam...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
85171bbf8502-14
model_kwargs: Dict[str, Any] = Field(default_factory=dict) """Holds any model parameters valid for `create` call not explicitly specified.""" openai_api_key: Optional[str] = None openai_api_base: Optional[str] = None max_retries: int = 6 """Maximum number of retries to make when generating.""" p...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
85171bbf8502-15
openai_api_key = get_from_dict_or_env( values, "openai_api_key", "OPENAI_API_KEY" ) openai_api_base = get_from_dict_or_env( values, "openai_api_base", "OPENAI_API_BASE", default="", ) openai_organization = get_from_dict_or_env( ...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
85171bbf8502-16
self, prompts: List[str], stop: Optional[List[str]] = None ) -> Tuple: if len(prompts) > 1: raise ValueError( f"OpenAIChat currently only supports single prompt, got {prompts}" ) messages = self.prefix_messages + [{"role": "user", "content": prompts[0]}] ...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
85171bbf8502-17
llm_output = { "token_usage": full_response["usage"], "model_name": self.model_name, } return LLMResult( generations=[ [Generation(text=full_response["choices"][0]["message"]["content"])] ], llm_o...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
85171bbf8502-18
"""Get the identifying parameters.""" return {**{"model_name": self.model_name}, **self._default_params} @property def _llm_type(self) -> str: """Return type of llm.""" return "openai-chat" [docs] def get_num_tokens(self, text: str) -> int: """Calculate num tokens with tiktoke...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
ac6354339f5f-0
Source code for langchain.llms.ai21 """Wrapper around AI21 APIs.""" from typing import Any, Dict, List, Optional import requests from pydantic import BaseModel, Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.utils import get_from...
https://python.langchain.com/en/latest/_modules/langchain/llms/ai21.html
ac6354339f5f-1
countPenalty: AI21PenaltyData = AI21PenaltyData() """Penalizes repeated tokens according to count.""" frequencyPenalty: AI21PenaltyData = AI21PenaltyData() """Penalizes repeated tokens according to frequency.""" numResults: int = 1 """How many completions to generate for each prompt.""" logitBia...
https://python.langchain.com/en/latest/_modules/langchain/llms/ai21.html
ac6354339f5f-2
"logitBias": self.logitBias, } @property def _identifying_params(self) -> Dict[str, Any]: """Get the identifying parameters.""" return {**{"model": self.model}, **self._default_params} @property def _llm_type(self) -> str: """Return type of llm.""" return "ai21" ...
https://python.langchain.com/en/latest/_modules/langchain/llms/ai21.html
ac6354339f5f-3
headers={"Authorization": f"Bearer {self.ai21_api_key}"}, json={"prompt": prompt, "stopSequences": stop, **self._default_params}, ) if response.status_code != 200: optional_detail = response.json().get("error") raise ValueError( f"AI21 /complete call f...
https://python.langchain.com/en/latest/_modules/langchain/llms/ai21.html
d6865ec99ad9-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://python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html
d6865ec99ad9-1
try: import predictionguard as pg values["client"] = pg.Client(token=token) except ImportError: raise ValueError( "Could not import predictionguard python package. " "Please install it with `pip install predictionguard`." ) ...
https://python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html
d6865ec99ad9-2
response = self.client.predict( name=self.name, data={ "prompt": prompt, "max_tokens": params["max_tokens"], "temperature": params["temperature"], }, ) text = response["text"] # If stop tokens are provided, Predi...
https://python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html
b31314cd89bf-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://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
b31314cd89bf-1
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 transformers import AutoModelForCausa...
https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
b31314cd89bf-2
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 associated with CUDA device id.", cuda_device_coun...
https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
b31314cd89bf-3
hardware=gpu ) 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...
https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
b31314cd89bf-4
"""Inference function to send to the remote hardware.""" class Config: """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...
https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
da0bed5ba727-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, Extra, root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMR...
https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
da0bed5ba727-1
anthropic_api_key = get_from_dict_or_env( 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"]...
https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
da0bed5ba727-2
if stop is None: stop = [] # Never want model to invent new turns of Human / Assistant dialog. stop.extend([self.HUMAN_PROMPT]) return stop def get_num_tokens(self, text: str) -> int: """Calculate number of tokens.""" if not self.count_tokens: raise Na...
https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
da0bed5ba727-3
warnings.warn( "This Anthropic LLM is deprecated. " "Please use `from langchain.chat_models import ChatAnthropic` instead" ) return values class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @property def _llm_type(self) ->...
https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
da0bed5ba727-4
.. code-block:: python prompt = "What are the biggest risks facing humanity?" prompt = f"\n\nHuman: {prompt}\n\nAssistant:" response = model(prompt) """ stop = self._get_anthropic_stop(stop) if self.streaming: stream_resp = self.client....
https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
da0bed5ba727-5
await run_manager.on_llm_new_token(delta, **data) return current_completion response = await self.client.acompletion( prompt=self._wrap_prompt(prompt), stop_sequences=stop, **self._default_params, ) return response["completion"] [docs] def strea...
https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
dfdf8572e1d8-0
Source code for langchain.llms.huggingface_endpoint """Wrapper around HuggingFace APIs.""" from typing import Any, Dict, List, Mapping, Optional import requests from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain....
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html
dfdf8572e1d8-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://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html
dfdf8572e1d8-2
) -> str: """Call out to HuggingFace Hub's inference endpoint. Args: prompt: The prompt to pass into the model. stop: Optional list of stop words to use when generating. Returns: The string generated by the model. Example: .. code-block:: p...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html
dfdf8572e1d8-3
# This is a bit hacky, but I can't figure out a better way to enforce # stop tokens when making calls to huggingface_hub. text = enforce_stop_tokens(text, stop) return text By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 02, 2023.
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html
a683e5e0bd86-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://python.langchain.com/en/latest/_modules/langchain/llms/pipelineai.html
a683e5e0bd86-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://python.langchain.com/en/latest/_modules/langchain/llms/pipelineai.html
a683e5e0bd86-2
"Please install it with `pip install pipeline-ai`." ) client = PipelineCloud(token=self.pipeline_api_key) params = self.pipeline_kwargs or {} run = client.run_pipeline(self.pipeline_key, [prompt, params]) try: text = run.result_preview[0][0] except Attribu...
https://python.langchain.com/en/latest/_modules/langchain/llms/pipelineai.html
878d4408d8b5-0
Source code for langchain.llms.gpt4all """Wrapper for the GPT4All model.""" from functools import partial from typing import Any, Dict, List, Mapping, Optional, Set from pydantic import Extra, Field, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from...
https://python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html
878d4408d8b5-1
"""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_mlock") """Force system to keep model in RAM.""" embedding: bool = Field(False, alias="embedding") ...
https://python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html
878d4408d8b5-2
@property def _default_params(self) -> Dict[str, Any]: """Get the identifying parameters.""" return { "seed": self.seed, "n_predict": self.n_predict, "n_threads": self.n_threads, "n_batch": self.n_batch, "repeat_last_n": self.repeat_last_n,...
https://python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html
878d4408d8b5-3
@property def _identifying_params(self) -> Mapping[str, Any]: """Get the identifying parameters.""" return { "model": self.model, **self._default_params, **{ k: v for k, v in self.__dict__.items() if k in GPT4All._ll...
https://python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html
67e66e4831b0-0
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...
https://python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html
67e66e4831b0-1
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[field_name] = values.pop(field_name) ...
https://python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html
67e66e4831b0-2
""" params = self.model_kwargs or {} response_post = requests.post( url=self.api_url, json={"prompt": prompt, "params": params}, headers={ "apiKey": f"{self.stochasticai_api_key}", "Accept": "application/json", "Content-...
https://python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html
63dab3a22b26-0
Source code for langchain.llms.self_hosted """Run model inference on self-hosted remote hardware.""" import importlib.util import logging import pickle from typing import Any, Callable, List, Mapping, Optional from pydantic import Extra from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llm...
https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
63dab3a22b26-1
) 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://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
63dab3a22b26-2
llm = SelfHostedPipeline( model_load_fn=load_pipeline, hardware=gpu, model_reqs=model_reqs, inference_fn=inference_fn ) Example for <2GB model (can be serialized and sent directly to the server): .. code-block:: python from langchain.ll...
https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
63dab3a22b26-3
load_fn_kwargs: Optional[dict] = None """Key word arguments to pass to the model load function.""" model_reqs: List[str] = ["./", "torch"] """Requirements to install on hardware to inference the model.""" class Config: """Configuration for this pydantic object.""" extra = Extra.forbid ...
https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
63dab3a22b26-4
if not isinstance(pipeline, str): logger.warning( "Serializing pipeline to send to remote hardware. " "Note, it can be quite slow" "to serialize and send large models with each execution. " "Consider sending the pipeline" "to th...
https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
39c485bb8585-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://python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html
39c485bb8585-1
for field_name in list(values): if field_name not in all_required_field_names: if field_name in extra: raise ValueError(f"Found {field_name} supplied twice.") logger.warning( f"""{field_name} was transfered to model_kwargs. ...
https://python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html
39c485bb8585-2
params = self.model_kwargs or {} 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_key, model_key, model_inputs) try: ...
https://python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html
eafa063cf164-0
Source code for langchain.retrievers.remote_retriever from typing import List, Optional import aiohttp import requests from pydantic import BaseModel from langchain.schema import BaseRetriever, Document [docs]class RemoteLangChainRetriever(BaseRetriever, BaseModel): url: str headers: Optional[dict] = None i...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/remote_retriever.html
5d6063155eff-0
Source code for langchain.retrievers.metal from typing import Any, List, Optional from langchain.schema import BaseRetriever, Document [docs]class MetalRetriever(BaseRetriever): def __init__(self, client: Any, params: Optional[dict] = None): from metal_sdk.metal import Metal if not isinstance(client...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/metal.html
5c87aac05891-0
Source code for langchain.retrievers.svm """SMV Retriever. Largely based on https://github.com/karpathy/randomfun/blob/master/knn_vs_svm.ipynb""" from __future__ import annotations import concurrent.futures from typing import Any, List, Optional import numpy as np from pydantic import BaseModel from langchain.embedding...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/svm.html
5c87aac05891-1
y[0] = 1 clf = svm.LinearSVC( class_weight="balanced", verbose=False, max_iter=10000, tol=1e-6, C=0.1 ) clf.fit(x, y) similarities = clf.decision_function(x) sorted_ix = np.argsort(-similarities) # svm.LinearSVC in scikit-learn is non-deterministic. # ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/svm.html
2d1a87a5f892-0
Source code for langchain.retrievers.pinecone_hybrid_search """Taken from: https://docs.pinecone.io/docs/hybrid-search""" import hashlib from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, root_validator from langchain.embeddings.base import Embeddings from langchain.schema import BaseRe...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html
2d1a87a5f892-1
vectors = [] # loop through the data and create dictionaries for upserts for doc_id, sparse, dense, metadata in zip( batch_ids, sparse_embeds, dense_embeds, meta ): vectors.append( { "id": doc_id, "sparse_values": sp...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html
2d1a87a5f892-2
[docs] def get_relevant_documents(self, query: str) -> List[Document]: from pinecone_text.hybrid import hybrid_convex_scale sparse_vec = self.sparse_encoder.encode_queries(query) # convert the question into a dense vector dense_vec = self.embeddings.embed_query(query) # scale ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html
1a235c4f2743-0
Source code for langchain.retrievers.tfidf """TF-IDF Retriever. Largely based on https://github.com/asvskartheek/Text-Retrieval/blob/master/TF-IDF%20Search%20Engine%20(SKLEARN).ipynb""" from typing import Any, Dict, List, Optional from pydantic import BaseModel from langchain.schema import BaseRetriever, Document [docs...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/tfidf.html
1a235c4f2743-1
results = cosine_similarity(self.tfidf_array, query_vec).reshape( (-1,) ) # Op -- (n_docs,1) -- Cosine Sim with each doc return_docs = [] for i in results.argsort()[-self.k :][::-1]: return_docs.append(self.docs[i]) return return_docs [docs] async def aget_rel...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/tfidf.html
bce16898a563-0
Source code for langchain.retrievers.time_weighted_retriever """Retriever that combines embedding similarity with recency in retrieving values.""" from copy import deepcopy from datetime import datetime from typing import Any, Dict, List, Optional, Tuple from pydantic import BaseModel, Field from langchain.schema impor...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html
bce16898a563-1
""" class Config: """Configuration for this pydantic object.""" arbitrary_types_allowed = True def _get_combined_score( self, document: Document, vector_relevance: Optional[float], current_time: datetime, ) -> float: """Return the combined score for a ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html
bce16898a563-2
for doc in self.memory_stream[-self.k :] } # If a doc is considered salient, update the salience score docs_and_scores.update(self.get_salient_docs(query)) rescored_docs = [ (doc, self._get_combined_score(doc, relevance, current_time)) for doc, relevance in docs_a...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html
bce16898a563-3
self.memory_stream.extend(dup_docs) return self.vectorstore.add_documents(dup_docs, **kwargs) [docs] async def aadd_documents( self, documents: List[Document], **kwargs: Any ) -> List[str]: """Add documents to vectorstore.""" current_time = kwargs.get("current_time", datetime.now(...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html
69ad630066de-0
Source code for langchain.retrievers.elastic_search_bm25 """Wrapper around Elasticsearch vector database.""" from __future__ import annotations import uuid from typing import Any, Iterable, List from langchain.docstore.document import Document from langchain.schema import BaseRetriever [docs]class ElasticSearchBM25Retr...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/elastic_search_bm25.html
69ad630066de-1
self.index_name = index_name [docs] @classmethod def create( cls, elasticsearch_url: str, index_name: str, k1: float = 2.0, b: float = 0.75 ) -> ElasticSearchBM25Retriever: from elasticsearch import Elasticsearch # Create an Elasticsearch client instance es = Elasticsearch(ela...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/elastic_search_bm25.html
69ad630066de-2
raise ValueError( "Could not import elasticsearch python package. " "Please install it with `pip install elasticsearch`." ) requests = [] ids = [] for i, text in enumerate(texts): _id = str(uuid.uuid4()) request = { ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/elastic_search_bm25.html
f008216c936b-0
Source code for langchain.retrievers.chatgpt_plugin_retriever from __future__ import annotations from typing import List, Optional import aiohttp import requests from pydantic import BaseModel from langchain.schema import BaseRetriever, Document [docs]class ChatGPTPluginRetriever(BaseRetriever, BaseModel): url: str...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/chatgpt_plugin_retriever.html
f008216c936b-1
docs = [] for d in results: content = d.pop("text") docs.append(Document(page_content=content, metadata=d)) return docs def _create_request(self, query: str) -> tuple[str, dict, dict]: url = f"{self.url}/query" json = { "queries": [ ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/chatgpt_plugin_retriever.html
d11737faeb71-0
Source code for langchain.retrievers.vespa_retriever """Wrapper for retrieving documents from Vespa.""" from __future__ import annotations import json from typing import TYPE_CHECKING, List from langchain.schema import BaseRetriever, Document if TYPE_CHECKING: from vespa.application import Vespa [docs]class VespaRe...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/vespa_retriever.html
9de60c5bd9dd-0
Source code for langchain.retrievers.contextual_compression """Retriever that wraps a base retriever and filters the results.""" from typing import List from pydantic import BaseModel, Extra from langchain.retrievers.document_compressors.base import ( BaseDocumentCompressor, ) from langchain.schema import BaseRetri...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/contextual_compression.html
9de60c5bd9dd-1
return list(compressed_docs) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 02, 2023.
https://python.langchain.com/en/latest/_modules/langchain/retrievers/contextual_compression.html
6145d8c1895c-0
Source code for langchain.retrievers.weaviate_hybrid_search """Wrapper around weaviate vector database.""" from __future__ import annotations from typing import Any, Dict, List, Optional from uuid import uuid4 from pydantic import Extra from langchain.docstore.document import Document from langchain.schema import BaseR...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html
6145d8c1895c-1
"""Upload documents to Weaviate.""" from weaviate.util import get_valid_uuid with self._client.batch as batch: ids = [] for i, doc in enumerate(docs): metadata = doc.metadata or {} data_properties = {self._text_key: doc.page_content, **metadata} ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html
7d8d124217d5-0
Source code for langchain.retrievers.databerry from typing import List, Optional import aiohttp import requests from langchain.schema import BaseRetriever, Document [docs]class DataberryRetriever(BaseRetriever): datastore_url: str top_k: Optional[int] api_key: Optional[str] def __init__( self, ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/databerry.html
7d8d124217d5-1
self.datastore_url, json={ "query": query, **({"topK": self.top_k} if self.top_k is not None else {}), }, headers={ "Content-Type": "application/json", **( {"Authorizat...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/databerry.html
74b2e2cf3d69-0
Source code for langchain.retrievers.document_compressors.chain_filter """Filter that uses an LLM to drop documents that aren't relevant to the query.""" from typing import Any, Callable, Dict, Optional, Sequence from langchain import BasePromptTemplate, LLMChain, PromptTemplate from langchain.base_language import Base...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_filter.html
74b2e2cf3d69-1
include_doc = self.llm_chain.predict_and_parse(**_input) if include_doc: filtered_docs.append(doc) return filtered_docs [docs] async def acompress_documents( self, documents: Sequence[Document], query: str ) -> Sequence[Document]: """Filter down documents.""" ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_filter.html
df52c41c6f0c-0
Source code for langchain.retrievers.document_compressors.embeddings_filter """Document compressor that uses embeddings to drop documents unrelated to the query.""" from typing import Callable, Dict, Optional, Sequence import numpy as np from pydantic import root_validator from langchain.document_transformers import ( ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/embeddings_filter.html