id
stringlengths
14
16
text
stringlengths
36
2.73k
source
stringlengths
59
127
d791178e0d57-1
verbose=verbose, ), LLMChain( llm=llm, prompt=check_assertions_prompt, output_key="checked_assertions", verbose=verbose, ), LLMChain( llm=llm, prompt=revised_summary_prompt, ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/llm_summarization_checker/base.html
d791178e0d57-2
input_key: str = "query" #: :meta private: output_key: str = "result" #: :meta private: max_checks: int = 2 """Maximum number of times to check the assertions. Default to double-checking.""" class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitr...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/llm_summarization_checker/base.html
d791178e0d57-3
def _call( self, inputs: Dict[str, Any], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, str]: _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() all_true = False count = 0 output = None original_input ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/llm_summarization_checker/base.html
d791178e0d57-4
create_assertions_prompt, check_assertions_prompt, revised_summary_prompt, are_all_true_prompt, verbose=verbose, ) return cls(sequential_chain=chain, verbose=verbose, **kwargs) By Harrison Chase © Copyright 2023, Harrison Chase. Last up...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/llm_summarization_checker/base.html
f54b57b10006-0
Source code for langchain.chains.combine_documents.base """Base interface for chains combining documents.""" from abc import ABC, abstractmethod from typing import Any, Dict, List, Optional, Tuple from pydantic import Field from langchain.callbacks.manager import ( AsyncCallbackManagerForChainRun, CallbackManag...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/combine_documents/base.html
f54b57b10006-1
""" return [self.input_key] @property def output_keys(self) -> List[str]: """Return output key. :meta private: """ return [self.output_key] def prompt_length(self, docs: List[Document], **kwargs: Any) -> Optional[int]: """Return the prompt length given the doc...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/combine_documents/base.html
f54b57b10006-2
) -> Dict[str, str]: _run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_manager() docs = inputs[self.input_key] # Other keys are assumed to be needed for LLM prediction other_keys = {k: v for k, v in inputs.items() if k != self.input_key} output, extra_return_...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/combine_documents/base.html
f54b57b10006-3
other_keys[self.combine_docs_chain.input_key] = docs return self.combine_docs_chain( other_keys, return_only_outputs=True, callbacks=_run_manager.get_child() ) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/combine_documents/base.html
cf5e270ef9d0-0
Source code for langchain.chains.sql_database.base """Chain for interacting with SQL Database.""" from __future__ import annotations import warnings from typing import Any, Dict, List, Optional from pydantic import Extra, Field, root_validator from langchain.base_language import BaseLanguageModel from langchain.callbac...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/sql_database/base.html
cf5e270ef9d0-1
return_intermediate_steps: bool = False """Whether or not to return the intermediate steps along with the final answer.""" return_direct: bool = False """Whether or not to return the result of querying the SQL table directly.""" use_query_checker: bool = False """Whether or not the query checker too...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/sql_database/base.html
cf5e270ef9d0-2
:meta private: """ if not self.return_intermediate_steps: return [self.output_key] else: return [self.output_key, INTERMEDIATE_STEPS_KEY] def _call( self, inputs: Dict[str, Any], run_manager: Optional[CallbackManagerForChainRun] = None, ) -...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/sql_database/base.html
cf5e270ef9d0-3
result = self.database.run(sql_cmd) intermediate_steps.append(str(result)) # output: sql exec else: query_checker_prompt = self.query_checker_prompt or PromptTemplate( template=QUERY_CHECKER, input_variables=["query", "dialect"] ) ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/sql_database/base.html
cf5e270ef9d0-4
llm_inputs["input"] = input_text intermediate_steps.append(llm_inputs) # input: final answer final_result = self.llm_chain.predict( callbacks=_run_manager.get_child(), **llm_inputs, ).strip() intermediate_steps.appe...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/sql_database/base.html
cf5e270ef9d0-5
2. Based on those tables, call the normal SQL database chain. This is useful in cases where the number of tables in the database is large. """ decider_chain: LLMChain sql_chain: SQLDatabaseChain input_key: str = "query" #: :meta private: output_key: str = "result" #: :meta private: return_...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/sql_database/base.html
cf5e270ef9d0-6
def _call( self, inputs: Dict[str, Any], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, Any]: _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() _table_names = self.sql_chain.database.get_usable_table_names() table_na...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/sql_database/base.html
f043fac22094-0
Source code for langchain.chains.hyde.base """Hypothetical Document Embeddings. https://arxiv.org/abs/2212.10496 """ from __future__ import annotations from typing import Any, Dict, List, Optional import numpy as np from pydantic import Extra from langchain.base_language import BaseLanguageModel from langchain.callback...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/hyde/base.html
f043fac22094-1
return list(np.array(embeddings).mean(axis=0)) [docs] def embed_query(self, text: str) -> List[float]: """Generate a hypothetical document and embedded it.""" var_name = self.llm_chain.input_keys[0] result = self.llm_chain.generate([{var_name: text}]) documents = [generation.text for ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/hyde/base.html
c758ad599ce9-0
Source code for langchain.chains.qa_with_sources.base """Question answering with sources over documents.""" from __future__ import annotations import re from abc import ABC, abstractmethod from typing import Any, Dict, List, Optional from pydantic import Extra, root_validator from langchain.base_language import BaseLan...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/qa_with_sources/base.html
c758ad599ce9-1
document_prompt: BasePromptTemplate = EXAMPLE_PROMPT, question_prompt: BasePromptTemplate = QUESTION_PROMPT, combine_prompt: BasePromptTemplate = COMBINE_PROMPT, **kwargs: Any, ) -> BaseQAWithSourcesChain: """Construct the chain from an LLM.""" llm_question_chain = LLMChain(l...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/qa_with_sources/base.html
c758ad599ce9-2
def input_keys(self) -> List[str]: """Expect input key. :meta private: """ return [self.question_key] @property def output_keys(self) -> List[str]: """Return output key. :meta private: """ _output_keys = [self.answer_key, self.sources_answer_key] ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/qa_with_sources/base.html
c758ad599ce9-3
} if self.return_source_documents: result["source_documents"] = docs return result @abstractmethod async def _aget_docs(self, inputs: Dict[str, Any]) -> List[Document]: """Get docs to run questioning over.""" async def _acall( self, inputs: Dict[str, Any],...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/qa_with_sources/base.html
c758ad599ce9-4
return inputs.pop(self.input_docs_key) @property def _chain_type(self) -> str: return "qa_with_sources_chain" By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/qa_with_sources/base.html
92de44e5f839-0
Source code for langchain.chains.qa_with_sources.vector_db """Question-answering with sources over a vector database.""" import warnings from typing import Any, Dict, List from pydantic import Field, root_validator from langchain.chains.combine_documents.stuff import StuffDocumentsChain from langchain.chains.qa_with_so...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/qa_with_sources/vector_db.html
92de44e5f839-1
num_docs -= 1 token_count -= tokens[num_docs] return docs[:num_docs] def _get_docs(self, inputs: Dict[str, Any]) -> List[Document]: question = inputs[self.question_key] docs = self.vectorstore.similarity_search( question, k=self.k, **self.search_kwargs ) ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/qa_with_sources/vector_db.html
022fb0123bab-0
Source code for langchain.chains.qa_with_sources.retrieval """Question-answering with sources over an index.""" from typing import Any, Dict, List from pydantic import Field from langchain.chains.combine_documents.stuff import StuffDocumentsChain from langchain.chains.qa_with_sources.base import BaseQAWithSourcesChain ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/qa_with_sources/retrieval.html
022fb0123bab-1
docs = self.retriever.get_relevant_documents(question) return self._reduce_tokens_below_limit(docs) async def _aget_docs(self, inputs: Dict[str, Any]) -> List[Document]: question = inputs[self.question_key] docs = await self.retriever.aget_relevant_documents(question) return self._re...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/qa_with_sources/retrieval.html
947118fa9f6e-0
Source code for langchain.chains.llm_math.base """Chain that interprets a prompt and executes python code to do math.""" from __future__ import annotations import math import re import warnings from typing import Any, Dict, List, Optional import numexpr from pydantic import Extra, root_validator from langchain.base_lan...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/llm_math/base.html
947118fa9f6e-1
if "llm" in values: warnings.warn( "Directly instantiating an LLMMathChain with an llm is deprecated. " "Please instantiate with llm_chain argument or using the from_llm " "class method." ) if "llm_chain" not in values and values["llm"]...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/llm_math/base.html
947118fa9f6e-2
) -> Dict[str, str]: run_manager.on_text(llm_output, color="green", verbose=self.verbose) llm_output = llm_output.strip() text_match = re.search(r"^```text(.*?)```", llm_output, re.DOTALL) if text_match: expression = text_match.group(1) output = self._evaluate_exp...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/llm_math/base.html
947118fa9f6e-3
elif llm_output.startswith("Answer:"): answer = llm_output elif "Answer:" in llm_output: answer = "Answer: " + llm_output.split("Answer:")[-1] else: raise ValueError(f"unknown format from LLM: {llm_output}") return {self.output_key: answer} def _call( ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/llm_math/base.html
947118fa9f6e-4
[docs] @classmethod def from_llm( cls, llm: BaseLanguageModel, prompt: BasePromptTemplate = PROMPT, **kwargs: Any, ) -> LLMMathChain: llm_chain = LLMChain(llm=llm, prompt=prompt) return cls(llm_chain=llm_chain, **kwargs) By Harrison Chase © Copyright...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/llm_math/base.html
a3093a112b78-0
Source code for langchain.chains.retrieval_qa.base """Chain for question-answering against a vector database.""" from __future__ import annotations import warnings from abc import abstractmethod from typing import Any, Dict, List, Optional from pydantic import Extra, Field, root_validator from langchain.base_language i...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/retrieval_qa/base.html
a3093a112b78-1
def output_keys(self) -> List[str]: """Return the output keys. :meta private: """ _output_keys = [self.output_key] if self.return_source_documents: _output_keys = _output_keys + ["source_documents"] return _output_keys @classmethod def from_llm( ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/retrieval_qa/base.html
a3093a112b78-2
def _get_docs(self, question: str) -> List[Document]: """Get documents to do question answering over.""" def _call( self, inputs: Dict[str, Any], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, Any]: """Run get_relevant_text and llm on input query...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/retrieval_qa/base.html
a3093a112b78-3
the retrieved documents as well under the key 'source_documents'. Example: .. code-block:: python res = indexqa({'query': 'This is my query'}) answer, docs = res['result'], res['source_documents'] """ _run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/retrieval_qa/base.html
a3093a112b78-4
def _chain_type(self) -> str: """Return the chain type.""" return "retrieval_qa" [docs]class VectorDBQA(BaseRetrievalQA): """Chain for question-answering against a vector database.""" vectorstore: VectorStore = Field(exclude=True, alias="vectorstore") """Vector Database to connect to.""" ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/retrieval_qa/base.html
a3093a112b78-5
question, k=self.k, **self.search_kwargs ) else: raise ValueError(f"search_type of {self.search_type} not allowed.") return docs async def _aget_docs(self, question: str) -> List[Document]: raise NotImplementedError("VectorDBQA does not support async") @property ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/retrieval_qa/base.html
24db6450623b-0
Source code for langchain.chains.conversation.base """Chain that carries on a conversation and calls an LLM.""" from typing import Dict, List from pydantic import Extra, Field, root_validator from langchain.chains.conversation.prompt import PROMPT from langchain.chains.llm import LLMChain from langchain.memory.buffer i...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/conversation/base.html
24db6450623b-1
f"The input key {input_key} was also found in the memory keys " f"({memory_keys}) - please provide keys that don't overlap." ) prompt_variables = values["prompt"].input_variables expected_keys = memory_keys + [input_key] if set(expected_keys) != set(prompt_variables):...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/conversation/base.html
df77e24cd9d0-0
Source code for langchain.chains.api.base """Chain that makes API calls and summarizes the responses to answer a question.""" from __future__ import annotations from typing import Any, Dict, List, Optional from pydantic import Field, root_validator from langchain.base_language import BaseLanguageModel from langchain.ca...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/api/base.html
df77e24cd9d0-1
if set(input_vars) != expected_vars: raise ValueError( f"Input variables should be {expected_vars}, got {input_vars}" ) return values @root_validator(pre=True) def validate_api_answer_prompt(cls, values: Dict) -> Dict: """Check that api answer prompt expec...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/api/base.html
df77e24cd9d0-2
return {self.output_key: answer} async def _acall( self, inputs: Dict[str, Any], run_manager: Optional[AsyncCallbackManagerForChainRun] = None, ) -> Dict[str, str]: _run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_manager() question = inputs[self.que...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/api/base.html
df77e24cd9d0-3
requests_wrapper = TextRequestsWrapper(headers=headers) get_answer_chain = LLMChain(llm=llm, prompt=api_response_prompt) return cls( api_request_chain=get_request_chain, api_answer_chain=get_answer_chain, requests_wrapper=requests_wrapper, api_docs=api_doc...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/api/base.html
8f0fcfc20bfb-0
Source code for langchain.chains.api.openapi.chain """Chain that makes API calls and summarizes the responses to answer a question.""" from __future__ import annotations import json from typing import Any, Dict, List, NamedTuple, Optional, cast from pydantic import BaseModel, Field from requests import Response from la...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/api/openapi/chain.html
8f0fcfc20bfb-1
""" return [self.instructions_key] @property def output_keys(self) -> List[str]: """Expect output key. :meta private: """ if not self.return_intermediate_steps: return [self.output_key] else: return [self.output_key, "intermediate_steps"] ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/api/openapi/chain.html
8f0fcfc20bfb-2
path = self._construct_path(args) body_params = self._extract_body_params(args) query_params = self._extract_query_params(args) return { "url": path, "data": body_params, "params": query_params, } def _get_output(self, output: str, intermediate_ste...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/api/openapi/chain.html
8f0fcfc20bfb-3
method = getattr(self.requests, self.api_operation.method.value) api_response: Response = method(**request_args) if api_response.status_code != 200: method_str = str(self.api_operation.method.value) response_text = ( f"{api_response.status_code...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/api/openapi/chain.html
8f0fcfc20bfb-4
# TODO: Handle async ) -> "OpenAPIEndpointChain": """Create an OpenAPIEndpoint from a spec at the specified url.""" operation = APIOperation.from_openapi_url(spec_url, path, method) return cls.from_api_operation( operation, requests=requests, llm=llm, ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/api/openapi/chain.html
8f0fcfc20bfb-5
requests=_requests, param_mapping=param_mapping, verbose=verbose, return_intermediate_steps=return_intermediate_steps, callbacks=callbacks, **kwargs, ) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 16, 2023...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chains/api/openapi/chain.html
a4536c037b83-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/chatgpt_plugin_retriever.html
a4536c037b83-1
) as response: res = await response.json() results = res["results"][0]["results"] docs = [] for d in results: content = d.pop("text") metadata = d.pop("metadata", d) if metadata.get("source_id"): metadata["source"] = metadata.po...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/chatgpt_plugin_retriever.html
e739168c01d9-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/elastic_search_bm25.html
e739168c01d9-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/elastic_search_bm25.html
e739168c01d9-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 = { ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/elastic_search_bm25.html
19f6955e3979-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/tfidf.html
19f6955e3979-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 = ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/tfidf.html
f7819b69d7e5-0
Source code for langchain.retrievers.zep from __future__ import annotations from typing import TYPE_CHECKING, Dict, List, Optional from langchain.schema import BaseRetriever, Document if TYPE_CHECKING: from zep_python import MemorySearchResult [docs]class ZepRetriever(BaseRetriever): """A Retriever implementati...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/zep.html
f7819b69d7e5-1
) for r in results if r.message ] [docs] def get_relevant_documents( self, query: str, metadata: Optional[Dict] = None ) -> List[Document]: from zep_python import MemorySearchPayload payload: MemorySearchPayload = MemorySearchPayload( text=query...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/zep.html
ba158238f972-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/remote_retriever.html
5ab5b5df176e-0
Source code for langchain.retrievers.aws_kendra_index_retriever """Retriever wrapper for AWS Kendra.""" import re from typing import Any, Dict, List from langchain.schema import BaseRetriever, Document [docs]class AwsKendraIndexRetriever(BaseRetriever): """Wrapper around AWS Kendra.""" kendraindex: str """K...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/aws_kendra_index_retriever.html
5ab5b5df176e-1
doc_excerpt = self._clean_result(res_text) combined_text = f"""Document Title: {doc_title} Document Excerpt: {doc_excerpt} """ return Document( page_content=combined_text, metadata={ "source": doc_uri, "title": doc_title, "excerpt":...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/aws_kendra_index_retriever.html
67cb7bb02754-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/svm.html
67cb7bb02754-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. # ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/svm.html
dfb467d7ec76-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/contextual_compression.html
dfb467d7ec76-1
return list(compressed_docs) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/contextual_compression.html
bb8e89143840-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/time_weighted_retriever.html
bb8e89143840-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/time_weighted_retriever.html
bb8e89143840-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/time_weighted_retriever.html
bb8e89143840-3
doc.metadata["buffer_idx"] = len(self.memory_stream) + i 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.""...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/time_weighted_retriever.html
f33751026e13-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/knn.html
f33751026e13-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 = [ Document(page_content=self.text...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/knn.html
a9c0445e574d-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/azure_cognitive_search.html
a9c0445e574d-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/azure_cognitive_search.html
a9c0445e574d-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) ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/azure_cognitive_search.html
c7671d075d44-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/weaviate_hybrid_search.html
c7671d075d44-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.""" ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/weaviate_hybrid_search.html
c7671d075d44-2
if where_filter: query_obj = query_obj.with_where(where_filter) result = query_obj.with_hybrid(query, alpha=self.alpha).with_limit(self.k).do() if "errors" in result: raise ValueError(f"Error during query: {result['errors']}") docs = [] for res in result["data"]["...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/weaviate_hybrid_search.html
daed6da266ed-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/pinecone_hybrid_search.html
daed6da266ed-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 = [] # loop t...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/pinecone_hybrid_search.html
daed6da266ed-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: ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/pinecone_hybrid_search.html
cdf5c77bf365-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/vespa_retriever.html
cdf5c77bf365-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:...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/vespa_retriever.html
cdf5c77bf365-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/vespa_retriever.html
d05d3131bd44-0
Source code for langchain.retrievers.pupmed from typing import List from langchain.schema import BaseRetriever, Document from langchain.utilities.pupmed import PubMedAPIWrapper [docs]class PubMedRetriever(BaseRetriever, PubMedAPIWrapper): """ It is effectively a wrapper for PubMedAPIWrapper. It wraps load()...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/pupmed.html
d336c3d5ecde-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/arxiv.html
2448275fad5e-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, ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/databerry.html
2448275fad5e-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/databerry.html
655fad512421-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. ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/wikipedia.html
0910faed59a3-0
Source code for langchain.retrievers.merger_retriever from typing import List from langchain.schema import BaseRetriever, Document [docs]class MergerRetriever(BaseRetriever): """ This class merges the results of multiple retrievers. Args: retrievers: A list of retrievers to merge. """ def __...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/merger_retriever.html
0910faed59a3-1
Returns: A list of merged documents. """ # Get the results of all retrievers. retriever_docs = [ retriever.get_relevant_documents(query) for retriever in self.retrievers ] # Merge the results of the retrievers. merged_documents = [] max_doc...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/merger_retriever.html
60d44a6814ff-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/metal.html
10f467bd2847-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 ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/self_query/base.html
10f467bd2847-1
return QdrantTranslator(metadata_key=vectorstore.metadata_payload_key) return BUILTIN_TRANSLATORS[vectorstore_cls]() [docs]class SelfQueryRetriever(BaseRetriever, BaseModel): """Retriever that wraps around a vector store and uses an LLM to generate the vector store queries.""" vectorstore: VectorStore ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/self_query/base.html
10f467bd2847-2
) if self.verbose: print(structured_query) new_query, new_kwargs = self.structured_query_translator.visit_structured_query( structured_query ) if structured_query.limit is not None: new_kwargs["k"] = structured_query.limit search_kwargs = {**se...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/self_query/base.html
10f467bd2847-3
**chain_kwargs, ) return cls( llm_chain=llm_chain, vectorstore=vectorstore, structured_query_translator=structured_query_translator, **kwargs, ) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/self_query/base.html
d29c02dfb229-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/document_compressors/base.html
d29c02dfb229-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/document_compressors/base.html
f11df7c5b63e-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/document_compressors/cohere_rerank.html
f11df7c5b63e-1
return [] 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.index] ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/document_compressors/cohere_rerank.html
e81835ae1e31-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/document_compressors/chain_extract.html