id
stringlengths
14
16
text
stringlengths
31
2.73k
metadata
dict
1e9de6ff3e6a-3
values, "aleph_alpha_api_key", "ALEPH_ALPHA_API_KEY" ) try: import aleph_alpha_client values["client"] = aleph_alpha_client.Client(token=aleph_alpha_api_key) except ImportError: raise ValueError( "Could not import aleph_alpha_client python pack...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html" }
1e9de6ff3e6a-4
"sequence_penalty": self.sequence_penalty, "sequence_penalty_min_length": self.sequence_penalty_min_length, "use_multiplicative_sequence_penalty": self.use_multiplicative_sequence_penalty, # noqa: E501 "completion_bias_inclusion": self.completion_bias_inclusion, "complet...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html" }
1e9de6ff3e6a-5
from aleph_alpha_client import CompletionRequest, Prompt params = self._default_params if self.stop_sequences is not None and stop is not None: raise ValueError( "stop sequences found in both the input and default params." ) elif self.stop_sequences is not...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html" }
d93016bc1749-0
Source code for langchain.llms.gooseai """Wrapper around GooseAI API.""" import logging from typing import Any, Dict, List, Mapping, Optional from pydantic import Extra, Field, root_validator from langchain.llms.base import LLM from langchain.utils import get_from_dict_or_env logger = logging.getLogger(__name__) [docs]...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html" }
d93016bc1749-1
"""Penalizes repeated tokens.""" n: int = 1 """How many completions to generate for each prompt.""" model_kwargs: Dict[str, Any] = Field(default_factory=dict) """Holds any model parameters valid for `create` call not explicitly specified.""" logit_bias: Optional[Dict[str, float]] = Field(default_fac...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html" }
d93016bc1749-2
) try: import openai openai.api_key = gooseai_api_key openai.api_base = "https://api.goose.ai/v1" values["client"] = openai.Completion except ImportError: raise ValueError( "Could not import openai python package. " ...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html" }
d93016bc1749-3
params["stop"] = stop response = self.client.create(engine=self.model_name, prompt=prompt, **params) text = response.choices[0].text return text By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 08, 2023.
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html" }
4b8cedc88add-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.llms.base import LLM from langchain.llms.utils import enforce_stop_t...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html" }
4b8cedc88add-1
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...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html" }
4b8cedc88add-2
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.llms import SelfHostedPipeline import runhouse as rh gpu = rh.clu...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html" }
4b8cedc88add-3
"""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 def __init__(self, **kwargs: Any): ...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html" }
4b8cedc88add-4
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 the cluster and passing the path to the pipeline...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html" }
9589c8461e20-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.llms.self_hosted import SelfHostedPipeline...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html" }
9589c8461e20-1
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 AutoModelForCausalLM, AutoModelForSeq2SeqLM, AutoTokeni...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html" }
9589c8461e20-2
"Provide device={deviceId} to `from_model_id` to use available" "GPUs for execution. deviceId is -1 for CPU and " "can be a positive integer associated with CUDA device id.", cuda_device_count, ) pipeline = hf_pipeline( task=task, model=mod...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html" }
9589c8461e20-3
.. code-block:: python from langchain.llms import SelfHostedHuggingFaceLLM from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline import runhouse as rh def get_pipeline(): model_id = "gpt2" tokenizer = AutoTokenizer.from_pre...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html" }
9589c8461e20-4
extra = Extra.forbid def __init__(self, **kwargs: Any): """Construct the pipeline remotely using an auxiliary function. The load function needs to be importable to be imported and run on the server, i.e. in a module and not a REPL or closure. Then, initialize the remote inference fun...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html" }
a07c77ed0734-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.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens DEFAULT_MODEL_ID = ...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html" }
a07c77ed0734-1
"""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, device: int = -1, model_kwargs: Optional[dict] = None, ...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html" }
a07c77ed0734-2
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 within [-1, {cuda_device_count})" ) ...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html" }
a07c77ed0734-3
response = self.pipeline(prompt) if self.pipeline.task == "text-generation": # Text generation return includes the starter text. text = response[0]["generated_text"][len(prompt) :] elif self.pipeline.task == "text2text-generation": text = response[0]["generated_text"]...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html" }
1b9a225a109c-0
Source code for langchain.llms.rwkv """Wrapper for the RWKV model. Based on https://github.com/saharNooby/rwkv.cpp/blob/master/rwkv/chat_with_bot.py https://github.com/BlinkDL/ChatRWKV/blob/main/v2/chat.py """ from typing import Any, Dict, List, Mapping, Optional, Set, SupportsIndex from pydantic import BaseMo...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html" }
1b9a225a109c-1
in the text so far, decreasing the model's likelihood to repeat the same line verbatim..""" penalty_alpha_presence: float = 0.4 """Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics..""" CHUNK_LEN: int =...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html" }
1b9a225a109c-2
try: import tokenizers except ImportError: raise ValueError( "Could not import tokenizers python package. " "Please install it with `pip install tokenizers`." ) try: from rwkv.model import RWKV as RWKVMODEL from ...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html" }
1b9a225a109c-3
logits = None state = self.model_state occurrence = {} # Feed in the input string while len(tokens) > 0: logits, state = self.client.forward(tokens[: self.CHUNK_LEN], state) tokens = tokens[self.CHUNK_LEN :] decoded = "" for i in range(self.max_tok...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html" }
1b9a225a109c-4
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 08, 2023.
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html" }
fe3fb455bb79-0
Source code for langchain.llms.gpt4all """Wrapper for the GPT4All model.""" from typing import Any, Dict, List, Mapping, Optional, Set from pydantic import Extra, Field, root_validator from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens [docs]class GPT4All(LLM): r"""Wrapper arou...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html" }
fe3fb455bb79-1
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") """Use embedding mode only.""" n_threads: Optional[int] = F...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html" }
fe3fb455bb79-2
"""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, "repeat_penalty": self.repeat_penalty, "to...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html" }
fe3fb455bb79-3
return { "model": self.model, **self._default_params, **{ k: v for k, v in self.__dict__.items() if k in GPT4All._llama_param_names() }, } @property def _llm_type(self) -> str: """Return the type of l...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html" }
9dec2608e770-0
Source code for langchain.llms.anthropic """Wrapper around Anthropic APIs.""" import re from typing import Any, Dict, Generator, List, Mapping, Optional from pydantic import Extra, root_validator from langchain.llms.base import LLM from langchain.utils import get_from_dict_or_env [docs]class Anthropic(LLM): r"""Wra...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html" }
9dec2608e770-1
"""A non-negative float that tunes the degree of randomness in generation.""" top_k: int = 0 """Number of most likely tokens to consider at each step.""" top_p: float = 1 """Total probability mass of tokens to consider at each step.""" streaming: bool = False """Whether to stream the results."""...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html" }
9dec2608e770-2
"top_p": self.top_p, } @property def _identifying_params(self) -> Mapping[str, Any]: """Get the identifying parameters.""" return {**{"model": self.model}, **self._default_params} @property def _llm_type(self) -> str: """Return type of llm.""" return "anthropic" ...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html" }
9dec2608e770-3
r"""Call out to Anthropic's completion 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 ...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html" }
9dec2608e770-4
stream=True, **self._default_params, ) current_completion = "" async for data in stream_resp: delta = data["completion"][len(current_completion) :] current_completion = data["completion"] if self.callback_manager.is_asyn...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html" }
9dec2608e770-5
prompt=self._wrap_prompt(prompt), stop_sequences=stop, **self._default_params, ) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 08, 2023.
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html" }
d14b63ed7d4f-0
Source code for langchain.embeddings.cohere """Wrapper around Cohere embedding models.""" from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, root_validator from langchain.embeddings.base import Embeddings from langchain.utils import get_from_dict_or_env [docs]class CohereEmbeddings(Base...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/cohere.html" }
d14b63ed7d4f-1
raise ValueError( "Could not import cohere python package. " "Please it install it with `pip install cohere`." ) return values [docs] def embed_documents(self, texts: List[str]) -> List[List[float]]: """Call out to Cohere's embedding endpoint. Args:...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/cohere.html" }
ebbcb153052f-0
Source code for langchain.embeddings.fake from typing import List import numpy as np from pydantic import BaseModel from langchain.embeddings.base import Embeddings [docs]class FakeEmbeddings(Embeddings, BaseModel): size: int def _get_embedding(self) -> List[float]: return list(np.random.normal(size=sel...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/fake.html" }
73eaf1cc12d2-0
Source code for langchain.embeddings.huggingface_hub """Wrapper around HuggingFace Hub embedding models.""" from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, root_validator from langchain.embeddings.base import Embeddings from langchain.utils import get_from_dict_or_env DEFAULT_REPO_ID...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html" }
73eaf1cc12d2-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: ...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html" }
73eaf1cc12d2-2
texts = [text.replace("\n", " ") for text in texts] _model_kwargs = self.model_kwargs or {} responses = self.client(inputs=texts, params=_model_kwargs) return responses [docs] def embed_query(self, text: str) -> List[float]: """Call out to HuggingFaceHub's embedding endpoint for embed...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html" }
3b65e3f56c7c-0
Source code for langchain.embeddings.sagemaker_endpoint """Wrapper around Sagemaker InvokeEndpoint API.""" from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, root_validator from langchain.embeddings.base import Embeddings from langchain.llms.sagemaker_endpoint import ContentHandlerBase ...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html" }
3b65e3f56c7c-1
"""The name of the endpoint from the deployed Sagemaker model. Must be unique within an AWS Region.""" region_name: str = "" """The aws region where the Sagemaker model is deployed, eg. `us-west-2`.""" credentials_profile_name: Optional[str] = None """The name of the profile in the ~/.aws/credential...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html" }
3b65e3f56c7c-2
endpoint_kwargs: Optional[Dict] = None """Optional attributes passed to the invoke_endpoint function. See `boto3`_. docs for more info. .. _boto3: <https://boto3.amazonaws.com/v1/documentation/api/latest/index.html> """ class Config: """Configuration for this pydantic object.""" extr...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html" }
3b65e3f56c7c-3
_endpoint_kwargs = self.endpoint_kwargs or {} body = self.content_handler.transform_input(texts, _model_kwargs) content_type = self.content_handler.content_type accepts = self.content_handler.accepts # send request try: response = self.client.invoke_endpoint( ...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html" }
3b65e3f56c7c-4
""" return self._embedding_func([text]) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 08, 2023.
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html" }
2d2425fa4352-0
Source code for langchain.embeddings.tensorflow_hub """Wrapper around TensorflowHub embedding models.""" from typing import Any, List from pydantic import BaseModel, Extra from langchain.embeddings.base import Embeddings DEFAULT_MODEL_URL = "https://tfhub.dev/google/universal-sentence-encoder-multilingual/3" [docs]clas...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/tensorflow_hub.html" }
2d2425fa4352-1
Returns: List of embeddings, one for each text. """ texts = list(map(lambda x: x.replace("\n", " "), texts)) embeddings = self.embed(texts).numpy() return embeddings.tolist() [docs] def embed_query(self, text: str) -> List[float]: """Compute query embeddings using ...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/tensorflow_hub.html" }
98e292a3aef9-0
Source code for langchain.embeddings.openai """Wrapper around OpenAI embedding models.""" from __future__ import annotations import logging from typing import Any, Callable, Dict, List, Optional import numpy as np from pydantic import BaseModel, Extra, root_validator from tenacity import ( before_sleep_log, ret...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html" }
98e292a3aef9-1
retry_decorator = _create_retry_decorator(embeddings) @retry_decorator def _completion_with_retry(**kwargs: Any) -> Any: return embeddings.client.create(**kwargs) return _completion_with_retry(**kwargs) [docs]class OpenAIEmbeddings(BaseModel, Embeddings): """Wrapper around OpenAI embedding model...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html" }
98e292a3aef9-2
model: str = "text-embedding-ada-002" # TODO: deprecate these two in favor of model # https://community.openai.com/t/api-update-engines-models/18597 # https://github.com/openai/openai-python/issues/132 document_model_name: str = "text-embedding-ada-002" query_model_name: str = "text-embedding-ada-...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html" }
98e292a3aef9-3
) if "query_model_name" in values: raise ValueError( "Both `model_name` and `query_model_name` were provided, " "but only one should be." ) model_name = values.pop("model_name") values["document_model_name"] = f"...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html" }
98e292a3aef9-4
values["client"] = openai.Embedding except ImportError: raise ValueError( "Could not import openai python package. " "Please it install it with `pip install openai`." ) return values # please refer to # https://github.com/openai/openai-cook...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html" }
98e292a3aef9-5
for i in range(len(indices)): results[indices[i]].append(batched_embeddings[i]) lens[indices[i]].append(len(batched_embeddings[i])) for i in range(len(texts)): average = np.average(results[i], axis=0, weights=lens[i]) embeddings[i] = (average /...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html" }
98e292a3aef9-6
# handle large batches of texts if self.embedding_ctx_length > 0: return self._get_len_safe_embeddings(texts, engine=self.document_model_name) else: results = [] _chunk_size = chunk_size or self.chunk_size for i in range(0, len(texts), _chunk_size): ...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html" }
f8d56027ab0e-0
Source code for langchain.embeddings.huggingface """Wrapper around HuggingFace embedding models.""" from typing import Any, List from pydantic import BaseModel, Extra from langchain.embeddings.base import Embeddings DEFAULT_MODEL_NAME = "sentence-transformers/all-mpnet-base-v2" DEFAULT_INSTRUCT_MODEL = "hkunlp/instruct...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html" }
f8d56027ab0e-1
"""Compute doc embeddings using a HuggingFace transformer model. Args: texts: The list of texts to embed. Returns: List of embeddings, one for each text. """ texts = list(map(lambda x: x.replace("\n", " "), texts)) embeddings = self.client.encode(texts) ...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html" }
f8d56027ab0e-2
try: from InstructorEmbedding import INSTRUCTOR self.client = INSTRUCTOR(self.model_name) except ImportError as e: raise ValueError("Dependencies for InstructorEmbedding not found.") from e class Config: """Configuration for this pydantic object.""" extra ...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html" }
a65ba2bdb9ef-0
Source code for langchain.embeddings.llamacpp """Wrapper around llama.cpp embedding models.""" from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, Field, root_validator from langchain.embeddings.base import Embeddings [docs]class LlamaCppEmbeddings(BaseModel, Embeddings): """Wrapper ...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html" }
a65ba2bdb9ef-1
use_mlock: bool = Field(False, alias="use_mlock") """Force system to keep model in RAM.""" n_threads: Optional[int] = Field(None, alias="n_threads") """Number of threads to use. If None, the number of threads is automatically determined.""" n_batch: Optional[int] = Field(8, alias="n_batch") """...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html" }
a65ba2bdb9ef-2
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: raise NameError(f"Could not load Llama m...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html" }
185d134c3a3d-0
Source code for langchain.embeddings.aleph_alpha from typing import Any, Dict, List, Optional from pydantic import BaseModel, root_validator from langchain.embeddings.base import Embeddings from langchain.utils import get_from_dict_or_env [docs]class AlephAlphaAsymmetricSemanticEmbedding(BaseModel, Embeddings): """...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html" }
185d134c3a3d-1
"""Attention control parameters only apply to those tokens that have explicitly been set in the request.""" control_log_additive: Optional[bool] = True """Apply controls on prompt items by adding the log(control_factor) to attention scores.""" @root_validator() def validate_environment(cls, va...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html" }
185d134c3a3d-2
"representation": SemanticRepresentation.Document, "compress_to_size": self.compress_to_size, "normalize": self.normalize, "contextual_control_threshold": self.contextual_control_threshold, "control_log_additive": self.control_log_additive, } ...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html" }
185d134c3a3d-3
"""The symmetric version of the Aleph Alpha's semantic embeddings. The main difference is that here, both the documents and queries are embedded with a SemanticRepresentation.Symmetric Example: .. code-block:: python from aleph_alpha import AlephAlphaSymmetricSemanticEmbedding ...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html" }
185d134c3a3d-4
List of embeddings, one for each text. """ document_embeddings = [] for text in texts: document_embeddings.append(self._embed(text)) return document_embeddings [docs] def embed_query(self, text: str) -> List[float]: """Call out to Aleph Alpha's asymmetric, query em...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html" }
dad036d46ad1-0
Source code for langchain.embeddings.self_hosted """Running custom embedding models on self-hosted remote hardware.""" from typing import Any, Callable, List from pydantic import Extra from langchain.embeddings.base import Embeddings from langchain.llms import SelfHostedPipeline def _embed_documents(pipeline: Any, *arg...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html" }
dad036d46ad1-1
model_load_fn=get_pipeline, hardware=gpu model_reqs=["./", "torch", "transformers"], ) Example passing in a pipeline path: .. code-block:: python from langchain.embeddings import SelfHostedHFEmbeddings import runhouse as rh from...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html" }
dad036d46ad1-2
[docs] def embed_query(self, text: str) -> List[float]: """Compute query embeddings using a HuggingFace transformer model. Args: text: The text to embed. Returns: Embeddings for the text. """ text = text.replace("\n", " ") embeddings = self.clie...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html" }
6afc09438080-0
Source code for langchain.embeddings.self_hosted_hugging_face """Wrapper around HuggingFace embedding models for self-hosted remote hardware.""" import importlib import logging from typing import Any, Callable, List, Optional from langchain.embeddings.self_hosted import SelfHostedEmbeddings DEFAULT_MODEL_NAME = "senten...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html" }
6afc09438080-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 associated wi...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html" }
6afc09438080-2
model_load_fn: Callable = load_embedding_model """Function to load the model remotely on the server.""" load_fn_kwargs: Optional[dict] = None """Key word arguments to pass to the model load function.""" inference_fn: Callable = _embed_documents """Inference function to extract the embeddings.""" ...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html" }
6afc09438080-3
model_name=model_name, hardware=gpu) """ model_id: str = DEFAULT_INSTRUCT_MODEL """Model name to use.""" embed_instruction: str = DEFAULT_EMBED_INSTRUCTION """Instruction to use for embedding documents.""" query_instruction: str = DEFAULT_QUERY_INSTRUCTION """Instruction to use for embedding...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html" }
6afc09438080-4
text: The text to embed. Returns: Embeddings for the text. """ instruction_pair = [self.query_instruction, text] embedding = self.client(self.pipeline_ref, [instruction_pair])[0] return embedding.tolist() By Harrison Chase © Copyright 2023, Harrison Chase. ...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html" }
367e515ed808-0
Source code for langchain.agents.tools """Interface for tools.""" from inspect import signature from typing import Any, Awaitable, Callable, Optional, Union from langchain.tools.base import BaseTool [docs]class Tool(BaseTool): """Tool that takes in function or coroutine directly.""" description: str = "" fu...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/agents/tools.html" }
367e515ed808-1
return f"{tool_name} is not a valid tool, try another one." [docs]def tool(*args: Union[str, Callable], return_direct: bool = False) -> Callable: """Make tools out of functions, can be used with or without arguments. Requires: - Function must be of type (str) -> str - Function must have a docstr...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/agents/tools.html" }
367e515ed808-2
# if the argument is a function, then we use the function name as the tool name # Example usage: @tool return _make_with_name(args[0].__name__)(args[0]) elif len(args) == 0: # if there are no arguments, then we use the function name as the tool name # Example usage: @tool(return_dire...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/agents/tools.html" }
7fb9e07bc9ed-0
Source code for langchain.agents.initialize """Load agent.""" from typing import Any, Optional, Sequence from langchain.agents.agent import AgentExecutor from langchain.agents.agent_types import AgentType from langchain.agents.loading import AGENT_TO_CLASS, load_agent from langchain.callbacks.base import BaseCallbackMa...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/agents/initialize.html" }
7fb9e07bc9ed-1
"but at most only one should be." ) if agent is not None: if agent not in AGENT_TO_CLASS: raise ValueError( f"Got unknown agent type: {agent}. " f"Valid types are: {AGENT_TO_CLASS.keys()}." ) agent_cls = AGENT_TO_CLASS[agent] ag...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/agents/initialize.html" }
71e9f3b9d989-0
Source code for langchain.agents.agent_types from enum import Enum [docs]class AgentType(str, Enum): ZERO_SHOT_REACT_DESCRIPTION = "zero-shot-react-description" REACT_DOCSTORE = "react-docstore" SELF_ASK_WITH_SEARCH = "self-ask-with-search" CONVERSATIONAL_REACT_DESCRIPTION = "conversational-react-descri...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/agents/agent_types.html" }
a52b9bd0a17e-0
Source code for langchain.agents.loading """Functionality for loading agents.""" import json from pathlib import Path from typing import Any, List, Optional, Union import yaml from langchain.agents.agent import Agent from langchain.agents.agent_types import AgentType from langchain.agents.chat.base import ChatAgent fro...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/agents/loading.html" }
a52b9bd0a17e-1
raise ValueError(f"Loading {config_type} agent not supported") if config_type not in AGENT_TO_CLASS: raise ValueError(f"Loading {config_type} agent not supported") agent_cls = AGENT_TO_CLASS[config_type] combined_config = {**config, **kwargs} return agent_cls.from_llm_and_tools(llm, tools, **com...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/agents/loading.html" }
a52b9bd0a17e-2
elif "llm_chain_path" in config: config["llm_chain"] = load_chain(config.pop("llm_chain_path")) else: raise ValueError("One of `llm_chain` and `llm_chain_path` should be specified.") combined_config = {**config, **kwargs} return agent_cls(**combined_config) # type: ignore [docs]def load_age...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/agents/loading.html" }
eb070272db6e-0
Source code for langchain.agents.load_tools # flake8: noqa """Load tools.""" import warnings from typing import Any, List, Optional from langchain.agents.tools import Tool from langchain.callbacks.base import BaseCallbackManager from langchain.chains.api import news_docs, open_meteo_docs, podcast_docs, tmdb_docs from l...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html" }
eb070272db6e-1
from langchain.utilities.wolfram_alpha import WolframAlphaAPIWrapper def _get_python_repl() -> BaseTool: return PythonREPLTool() def _get_tools_requests_get() -> BaseTool: return RequestsGetTool(requests_wrapper=TextRequestsWrapper()) def _get_tools_requests_post() -> BaseTool: return RequestsPostTool(reque...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html" }
eb070272db6e-2
func=PALChain.from_math_prompt(llm).run, ) def _get_pal_colored_objects(llm: BaseLLM) -> BaseTool: return Tool( name="PAL-COLOR-OBJ", description="A language model that is really good at reasoning about position and the color attributes of objects. Input should be a fully worded hard reasoning p...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html" }
eb070272db6e-3
"open-meteo-api": _get_open_meteo_api, } def _get_news_api(llm: BaseLLM, **kwargs: Any) -> BaseTool: news_api_key = kwargs["news_api_key"] chain = APIChain.from_llm_and_api_docs( llm, news_docs.NEWS_DOCS, headers={"X-Api-Key": news_api_key} ) return Tool( name="News API", descrip...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html" }
eb070272db6e-4
) return Tool( name="Podcast API", description="Use the Listen Notes Podcast API to search all podcasts or episodes. The input should be a question in natural language that this API can answer.", func=chain.run, ) def _get_wolfram_alpha(**kwargs: Any) -> BaseTool: return WolframAlpha...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html" }
eb070272db6e-5
def _get_searx_search_results_json(**kwargs: Any) -> BaseTool: wrapper_kwargs = {k: v for k, v in kwargs.items() if k != "num_results"} return SearxSearchResults(wrapper=SearxSearchWrapper(**wrapper_kwargs), **kwargs) def _get_bing_search(**kwargs: Any) -> BaseTool: return BingSearchRun(api_wrapper=BingSear...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html" }
eb070272db6e-6
"searx-search": (_get_searx_search, ["searx_host", "engines", "aiosession"]), "wikipedia": (_get_wikipedia, ["top_k_results"]), "human": (_get_human_tool, ["prompt_func", "input_func"]), } [docs]def load_tools( tool_names: List[str], llm: Optional[BaseLLM] = None, callback_manager: Optional[BaseCall...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html" }
eb070272db6e-7
if callback_manager is not None: tool.callback_manager = callback_manager tools.append(tool) elif name in _EXTRA_LLM_TOOLS: if llm is None: raise ValueError(f"Tool {name} requires an LLM to be provided") _get_llm_tool_func, extra_keys = _EXTRA_...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html" }
eb070272db6e-8
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 08, 2023.
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html" }
48d642a15044-0
Source code for langchain.agents.agent """Chain that takes in an input and produces an action and action input.""" from __future__ import annotations import asyncio import json import logging import time from abc import abstractmethod from pathlib import Path from typing import Any, Dict, List, Optional, Sequence, Tupl...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html" }
48d642a15044-1
**kwargs: User inputs. Returns: Action specifying what tool to use. """ [docs] @abstractmethod async def aplan( self, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any ) -> Union[AgentAction, AgentFinish]: """Given input, decided what to do. ...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html" }
48d642a15044-2
_dict["_type"] = self._agent_type return _dict [docs] def save(self, file_path: Union[Path, str]) -> None: """Save the agent. Args: file_path: Path to file to save the agent to. Example: .. code-block:: python # If working with agent executor ...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html" }
48d642a15044-3
) -> Union[List[AgentAction], AgentFinish]: """Given input, decided what to do. Args: intermediate_steps: Steps the LLM has taken to date, along with observations **kwargs: User inputs. Returns: Actions specifying what tool to use. """ ...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html" }
48d642a15044-4
raise NotImplementedError [docs] def dict(self, **kwargs: Any) -> Dict: """Return dictionary representation of agent.""" _dict = super().dict() _dict["_type"] = self._agent_type return _dict [docs] def save(self, file_path: Union[Path, str]) -> None: """Save the agent. ...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html" }
48d642a15044-5
llm_chain: LLMChain output_parser: AgentOutputParser stop: List[str] @property def input_keys(self) -> List[str]: return list(set(self.llm_chain.input_keys) - {"intermediate_steps"}) [docs] def plan( self, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any ) -> Union...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html" }
48d642a15044-6
} [docs]class Agent(BaseSingleActionAgent): """Class responsible for calling the language model and deciding the action. This is driven by an LLMChain. The prompt in the LLMChain MUST include a variable called "agent_scratchpad" where the agent can put its intermediary work. """ llm_chain: LLMCh...
{ "url": "https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html" }