id
stringlengths
14
16
text
stringlengths
36
2.73k
source
stringlengths
49
117
1f828b262a30-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
1f828b262a30-1
try: import predictionguard as pg values["client"] = pg.Client(token=token) except ImportError: raise ImportError( "Could not import predictionguard python package. " "Please install it with `pip install predictionguard`." ) ...
https://python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html
1f828b262a30-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
ee0f4a51dc79-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
ee0f4a51dc79-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
ee0f4a51dc79-2
if stop is None: stop = [] # Never want model to invent new turns of Human / Assistant dialog. stop.extend([self.HUMAN_PROMPT]) return stop [docs]class Anthropic(LLM, _AnthropicCommon): r"""Wrapper around Anthropic's large language models. To use, you should have the ``anthro...
https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
ee0f4a51dc79-3
extra = Extra.forbid @property def _llm_type(self) -> str: """Return type of llm.""" return "anthropic-llm" def _wrap_prompt(self, prompt: str) -> str: if not self.HUMAN_PROMPT or not self.AI_PROMPT: raise NameError("Please ensure the anthropic package is loaded") ...
https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
ee0f4a51dc79-4
if self.streaming: stream_resp = self.client.completion_stream( prompt=self._wrap_prompt(prompt), stop_sequences=stop, **self._default_params, ) current_completion = "" for data in stream_resp: delta = data["...
https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
ee0f4a51dc79-5
**self._default_params, ) return response["completion"] [docs] def stream(self, prompt: str, stop: Optional[List[str]] = None) -> Generator: r"""Call Anthropic completion_stream and return the resulting generator. BETA: this is a beta feature while we figure out the right abstraction....
https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
12a0fe55ee4f-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
12a0fe55ee4f-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
12a0fe55ee4f-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
3f57e7edfc5d-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
3f57e7edfc5d-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_hub.html
3f57e7edfc5d-2
self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, ) -> str: """Call out to HuggingFace Hub's inference endpoint. Args: prompt: The prompt to pass into the model. stop: Optional list of stop wor...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html
f7dd85d05b55-0
Source code for langchain.llms.aleph_alpha """Wrapper around Aleph Alpha APIs.""" from typing import Any, Dict, List, Optional, Sequence from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enforc...
https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
f7dd85d05b55-1
"""Total probability mass of tokens to consider at each step.""" presence_penalty: float = 0.0 """Penalizes repeated tokens.""" frequency_penalty: float = 0.0 """Penalizes repeated tokens according to frequency.""" repetition_penalties_include_prompt: Optional[bool] = False """Flag deciding whet...
https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
f7dd85d05b55-2
"""Echo the prompt in the completion.""" use_multiplicative_frequency_penalty: bool = False sequence_penalty: float = 0.0 sequence_penalty_min_length: int = 2 use_multiplicative_sequence_penalty: bool = False completion_bias_inclusion: Optional[Sequence[str]] = None completion_bias_inclusion_fir...
https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
f7dd85d05b55-3
"""Validate that api key and python package exists in environment.""" aleph_alpha_api_key = get_from_dict_or_env( values, "aleph_alpha_api_key", "ALEPH_ALPHA_API_KEY" ) try: import aleph_alpha_client values["client"] = aleph_alpha_client.Client(token=aleph_alp...
https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
f7dd85d05b55-4
"minimum_tokens": self.minimum_tokens, "echo": self.echo, "use_multiplicative_frequency_penalty": self.use_multiplicative_frequency_penalty, # noqa: E501 "sequence_penalty": self.sequence_penalty, "sequence_penalty_min_length": self.sequence_penalty_min_length, ...
https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
f7dd85d05b55-5
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 response = alpeh_alpha("Tell me a joke.") """ ...
https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
467240d2ea80-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
467240d2ea80-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
467240d2ea80-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
467240d2ea80-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 # to support explicit proxy for OpenAI ...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
467240d2ea80-4
"no longer supported. Instead, please use: " "`from langchain.chat_models import ChatOpenAI`" ) return OpenAIChat(**data) return super().__new__(cls) class Config: """Configuration for this pydantic object.""" extra = Extra.ignore allow_populat...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
467240d2ea80-5
values, "openai_api_key", "OPENAI_API_KEY" ) openai_api_base = get_from_dict_or_env( values, "openai_api_base", "OPENAI_API_BASE", default="", ) openai_proxy = get_from_dict_or_env( values, "openai_proxy", ...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
467240d2ea80-6
normal_params = { "temperature": self.temperature, "max_tokens": self.max_tokens, "top_p": self.top_p, "frequency_penalty": self.frequency_penalty, "presence_penalty": self.presence_penalty, "n": self.n, "request_timeout": self.request_...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
467240d2ea80-7
for _prompts in sub_prompts: if self.streaming: if len(_prompts) > 1: raise ValueError("Cannot stream results with multiple prompts.") params["stream"] = True response = _streaming_response_template() for stream_resp in comp...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
467240d2ea80-8
for _prompts in sub_prompts: if self.streaming: if len(_prompts) > 1: raise ValueError("Cannot stream results with multiple prompts.") params["stream"] = True response = _streaming_response_template() async for stream_resp i...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
467240d2ea80-9
) params["max_tokens"] = self.max_tokens_for_prompt(prompts[0]) sub_prompts = [ prompts[i : i + self.batch_size] for i in range(0, len(prompts), self.batch_size) ] return sub_prompts def create_llm_result( self, choices: Any, prompts: List[str], to...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
467240d2ea80-10
.. code-block:: python generator = openai.stream("Tell me a joke.") for token in generator: yield token """ params = self.prep_streaming_params(stop) generator = self.client.create(prompt=prompt, **params) return generator def prep_...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
467240d2ea80-11
try: import tiktoken except ImportError: raise ImportError( "Could not import tiktoken python package. " "This is needed in order to calculate get_num_tokens. " "Please install it with `pip install tiktoken`." ) enc = ti...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
467240d2ea80-12
"curie": 2049, "davinci": 2049, "text-davinci-003": 4097, "text-davinci-002": 4097, "code-davinci-002": 8001, "code-davinci-001": 8001, "code-cushman-002": 2048, "code-cushman-001": 2048, } # handling finetuned models ...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
467240d2ea80-13
To use, you should have the ``openai`` python package installed, and the environment variable ``OPENAI_API_KEY`` set with your API key. 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:: pyth...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
467240d2ea80-14
@property def _llm_type(self) -> str: """Return type of llm.""" return "azure" [docs]class OpenAIChat(BaseLLM): """Wrapper around OpenAI Chat large language models. To use, you should have the ``openai`` python package installed, and the environment variable ``OPENAI_API_KEY`` set with y...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
467240d2ea80-15
disallowed_special: Union[Literal["all"], Collection[str]] = "all" """Set of special tokens that are not allowed。""" 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]: ...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
467240d2ea80-16
openai.api_key = openai_api_key if openai_api_base: openai.api_base = openai_api_base if openai_organization: openai.organization = openai_organization if openai_proxy: openai.proxy = {"http": openai_proxy, "https": openai_proxy} # typ...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
467240d2ea80-17
params: Dict[str, Any] = {**{"model": self.model_name}, **self._default_params} if stop is not None: if "stop" in params: raise ValueError("`stop` found in both the input and default params.") params["stop"] = stop if params.get("max_tokens") == -1: # ...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
467240d2ea80-18
async def _agenerate( self, prompts: List[str], stop: Optional[List[str]] = None, run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, ) -> LLMResult: messages, params = self._get_chat_params(prompts, stop) if self.streaming: response = "" ...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
467240d2ea80-19
"""Get the token IDs using the tiktoken package.""" # tiktoken NOT supported for Python < 3.8 if sys.version_info[1] < 8: return super().get_token_ids(text) try: import tiktoken except ImportError: raise ImportError( "Could not import t...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
dbc9e83ffc74-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://python.langchain.com/en/latest/_modules/langchain/llms/openlm.html
267916669df0-0
Source code for langchain.retrievers.azure_cognitive_search """Retriever wrapper for Azure Cognitive Search.""" from __future__ import annotations import json from typing import Dict, List, Optional import aiohttp import requests from pydantic import BaseModel, Extra, root_validator from langchain.schema import BaseRet...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/azure_cognitive_search.html
267916669df0-1
) values["api_key"] = get_from_dict_or_env( values, "api_key", "AZURE_COGNITIVE_SEARCH_API_KEY" ) return values def _build_search_url(self, query: str) -> str: base_url = f"https://{self.service_name}.search.windows.net/" endpoint_path = f"indexes/{self.index_name...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/azure_cognitive_search.html
267916669df0-2
search_results = self._search(query) return [ Document(page_content=result.pop(self.content_key), metadata=result) for result in search_results ] [docs] async def aget_relevant_documents(self, query: str) -> List[Document]: search_results = await self._asearch(query) ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/azure_cognitive_search.html
ca1d5fd99f82-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, Any, Dict, List, Literal, Optional, Sequence, Union from langchain.schema import BaseRetriever, Document if TYPE_CHECKING: from ves...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/vespa_retriever.html
ca1d5fd99f82-1
docs.append(Document(page_content=page_content, metadata=metadata)) return docs [docs] def get_relevant_documents(self, query: str) -> List[Document]: body = self._query_body.copy() body["query"] = query return self._query(body) [docs] async def aget_relevant_documents(self, query:...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/vespa_retriever.html
ca1d5fd99f82-2
document metadata. Defaults to empty tuple (). sources (Sequence[str] or "*" or None): Sources to retrieve from. Defaults to None. _filter (Optional[str]): Document filter condition expressed in YQL. Defaults to None. yql (Optional[str]): Full YQL quer...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/vespa_retriever.html
53e6b0d70056-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
53e6b0d70056-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
53e6b0d70056-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
aa471c1ab85c-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
aa471c1ab85c-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
5d51e2cd2e1e-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
aa426705ff29-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
aa426705ff29-1
return list(compressed_docs) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/retrievers/contextual_compression.html
ed3d4dc55df7-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 __future__ import annotations from typing import Any, Dict, Iterable, List, Optional from pydantic import BaseModel from langchai...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/tfidf.html
ed3d4dc55df7-1
return cls(vectorizer=vectorizer, docs=docs, tfidf_array=tfidf_array, **kwargs) [docs] @classmethod def from_documents( cls, documents: Iterable[Document], *, tfidf_params: Optional[Dict[str, Any]] = None, **kwargs: Any, ) -> TFIDFRetriever: texts, metadatas = ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/tfidf.html
55e9c5e23ae9-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
55e9c5e23ae9-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
7d47f4147fcc-0
Source code for langchain.retrievers.knn """KNN 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/knn.html
7d47f4147fcc-1
similarities = index_embeds.dot(query_embeds) sorted_ix = np.argsort(-similarities) denominator = np.max(similarities) - np.min(similarities) + 1e-6 normalized_similarities = (similarities - np.min(similarities)) / denominator top_k_results = [] for row in sorted_ix[0 : self.k]: ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/knn.html
e326b7e808b9-0
Source code for langchain.retrievers.zep from __future__ import annotations from typing import TYPE_CHECKING, List, Optional from langchain.schema import BaseRetriever, Document if TYPE_CHECKING: from zep_python import SearchResult [docs]class ZepRetriever(BaseRetriever): """A Retriever implementation for the Z...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/zep.html
e326b7e808b9-1
) for r in results if r.message ] [docs] def get_relevant_documents(self, query: str) -> List[Document]: from zep_python import SearchPayload payload: SearchPayload = SearchPayload(text=query) results: List[SearchResult] = self.zep_client.search_memory( ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/zep.html
caa9bf26f326-0
Source code for langchain.retrievers.time_weighted_retriever """Retriever that combines embedding similarity with recency in retrieving values.""" import datetime from copy import deepcopy from typing import Any, Dict, List, Optional, Tuple from pydantic import BaseModel, Field from langchain.schema import BaseRetrieve...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html
caa9bf26f326-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.datetime, ) -> float: """Return the combined sco...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html
caa9bf26f326-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
caa9bf26f326-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") if cu...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html
022adf2e22b0-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
022adf2e22b0-1
] # create dense vectors dense_embeds = embeddings.embed_documents(context_batch) # create sparse vectors sparse_embeds = sparse_encoder.encode_documents(context_batch) for s in sparse_embeds: s["values"] = [float(s1) for s1 in s["values"]] vectors = [] ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html
022adf2e22b0-2
"""Validate that api key and python package exists in environment.""" try: from pinecone_text.hybrid import hybrid_convex_scale # noqa:F401 from pinecone_text.sparse.base_sparse_encoder import ( BaseSparseEncoder, # noqa:F401 ) except ImportError: ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html
c9894c39ed70-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
f57eee6d2d55-0
Source code for langchain.retrievers.arxiv from typing import List from langchain.schema import BaseRetriever, Document from langchain.utilities.arxiv import ArxivAPIWrapper [docs]class ArxivRetriever(BaseRetriever, ArxivAPIWrapper): """ It is effectively a wrapper for ArxivAPIWrapper. It wraps load() to ge...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/arxiv.html
cc39c5de96bf-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
cc39c5de96bf-1
"properties": [{"name": self._text_key, "dataType": ["text"]}], "vectorizer": "text2vec-openai", } if not self._client.schema.exists(self._index_name): self._client.schema.create_class(class_obj) [docs] class Config: """Configuration for this pydantic object.""" ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html
cc39c5de96bf-2
if "errors" in result: raise ValueError(f"Error during query: {result['errors']}") docs = [] for res in result["data"]["Get"][self._index_name]: text = res.pop(self._text_key) docs.append(Document(page_content=text, metadata=res)) return docs [docs] async d...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html
f6f07db85412-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
f6f07db85412-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
d290ba509b07-0
Source code for langchain.retrievers.wikipedia from typing import List from langchain.schema import BaseRetriever, Document from langchain.utilities.wikipedia import WikipediaAPIWrapper [docs]class WikipediaRetriever(BaseRetriever, WikipediaAPIWrapper): """ It is effectively a wrapper for WikipediaAPIWrapper. ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/wikipedia.html
16f78f9687d4-0
Source code for langchain.retrievers.self_query.base """Retriever that generates and executes structured queries over its own data source.""" from typing import Any, Dict, List, Optional, Type, cast from pydantic import BaseModel, Field, root_validator from langchain import LLMChain from langchain.base_language import ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html
16f78f9687d4-1
vectorstore: VectorStore """The underlying vector store from which documents will be retrieved.""" llm_chain: LLMChain """The LLMChain for generating the vector store queries.""" search_type: str = "similarity" """The search type to perform on the vector store.""" search_kwargs: dict = Field(def...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html
16f78f9687d4-2
if structured_query.limit is not None: new_kwargs["k"] = structured_query.limit search_kwargs = {**self.search_kwargs, **new_kwargs} docs = self.vectorstore.search(new_query, self.search_type, **search_kwargs) return docs [docs] async def aget_relevant_documents(self, query: str) ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html
16f78f9687d4-3
**kwargs, ) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html
030a52dcd8fc-0
Source code for langchain.retrievers.document_compressors.chain_extract """DocumentFilter that uses an LLM chain to extract the relevant parts of documents.""" from __future__ import annotations import asyncio from typing import Any, Callable, Dict, Optional, Sequence from langchain import LLMChain, PromptTemplate from...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html
030a52dcd8fc-1
[docs] def compress_documents( self, documents: Sequence[Document], query: str ) -> Sequence[Document]: """Compress page content of raw documents.""" compressed_docs = [] for doc in documents: _input = self.get_input(query, doc) output = self.llm_chain.pred...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html
030a52dcd8fc-2
_get_input = get_input if get_input is not None else default_get_input llm_chain = LLMChain(llm=llm, prompt=_prompt, **(llm_chain_kwargs or {})) return cls(llm_chain=llm_chain, get_input=_get_input) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html
37833527eded-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
37833527eded-1
return values [docs] def compress_documents( self, documents: Sequence[Document], query: str ) -> Sequence[Document]: """Filter documents based on similarity of their embeddings to the query.""" stateful_documents = get_stateful_documents(documents) embedded_documents = _get_embed...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/embeddings_filter.html
da029b1fd958-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
da029b1fd958-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
613add0e537b-0
Source code for langchain.retrievers.document_compressors.base """Interface for retrieved document compressors.""" from abc import ABC, abstractmethod from typing import List, Sequence, Union from pydantic import BaseModel from langchain.schema import BaseDocumentTransformer, Document class BaseDocumentCompressor(BaseM...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/base.html
613add0e537b-1
self, documents: Sequence[Document], query: str ) -> Sequence[Document]: """Compress retrieved documents given the query context.""" for _transformer in self.transformers: if isinstance(_transformer, BaseDocumentCompressor): documents = await _transformer.acompress_docume...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/base.html
a31639f45e75-0
Source code for langchain.retrievers.document_compressors.cohere_rerank from __future__ import annotations from typing import TYPE_CHECKING, Dict, Sequence from pydantic import Extra, root_validator from langchain.retrievers.document_compressors.base import BaseDocumentCompressor from langchain.schema import Document f...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/cohere_rerank.html
a31639f45e75-1
) -> Sequence[Document]: doc_list = list(documents) _docs = [d.page_content for d in doc_list] results = self.client.rerank( model=self.model, query=query, documents=_docs, top_n=self.top_n ) final_results = [] for r in results: doc = doc_list[r.in...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/cohere_rerank.html
e5df7c6ca095-0
Source code for langchain.embeddings.huggingface """Wrapper around HuggingFace embedding models.""" from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, Field from langchain.embeddings.base import Embeddings DEFAULT_MODEL_NAME = "sentence-transformers/all-mpnet-base-v2" DEFAULT_INSTRUCT_M...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html
e5df7c6ca095-1
super().__init__(**kwargs) try: import sentence_transformers except ImportError as exc: raise ImportError( "Could not import sentence_transformers python package. " "Please install it with `pip install sentence_transformers`." ) from ex...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html
e5df7c6ca095-2
from langchain.embeddings import HuggingFaceInstructEmbeddings model_name = "hkunlp/instructor-large" model_kwargs = {'device': 'cpu'} hf = HuggingFaceInstructEmbeddings( model_name=model_name, model_kwargs=model_kwargs ) """ client: Any #: :meta ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html
e5df7c6ca095-3
Returns: List of embeddings, one for each text. """ instruction_pairs = [[self.embed_instruction, text] for text in texts] embeddings = self.client.encode(instruction_pairs) return embeddings.tolist() [docs] def embed_query(self, text: str) -> List[float]: """Compu...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html
66d93fdb2934-0
Source code for langchain.embeddings.elasticsearch from __future__ import annotations from typing import TYPE_CHECKING, List, Optional from langchain.utils import get_from_env if TYPE_CHECKING: from elasticsearch.client import MlClient from langchain.embeddings.base import Embeddings [docs]class ElasticsearchEmbedd...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html
66d93fdb2934-1
es_user: Optional[str] = None, es_password: Optional[str] = None, input_field: str = "text_field", ) -> ElasticsearchEmbeddings: """Instantiate embeddings from Elasticsearch credentials. Args: model_id (str): The model_id of the model deployed in the Elasticsearch ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html