id stringlengths 14 16 | text stringlengths 31 2.41k | source stringlengths 53 121 |
|---|---|---|
eedabc04c945-10 | client: Optional[chromadb.Client] = None, # Add this line
**kwargs: Any,
) -> Chroma:
"""Create a Chroma vectorstore from a list of documents.
If a persist_directory is specified, the collection will be persisted there.
Otherwise, the data will be ephemeral in-memory.
Args:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
69ea6f4346f3-0 | Source code for langchain.vectorstores.redis
"""Wrapper around Redis vector database."""
from __future__ import annotations
import json
import logging
import uuid
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
Literal,
Mapping,
Optional,
Tuple,
Type,... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
69ea6f4346f3-1 | "Redis cannot be used as a vector database without RediSearch >=2.4"
"Please head to https://redis.io/docs/stack/search/quick_start/"
"to know more about installing the RediSearch module within Redis Stack."
)
logging.error(error_message)
raise ValueError(error_message)
def _check_index_exis... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
69ea6f4346f3-2 | index_name: str,
embedding_function: Callable,
content_key: str = "content",
metadata_key: str = "metadata",
vector_key: str = "content_vector",
relevance_score_fn: Optional[
Callable[[float], float]
] = _default_relevance_score,
**kwargs: Any,
):
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
69ea6f4346f3-3 | if not _check_index_exists(self.client, self.index_name):
# Define schema
schema = (
TextField(name=self.content_key),
TextField(name=self.metadata_key),
VectorField(
self.vector_key,
"FLAT",
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
69ea6f4346f3-4 | prefix = _redis_prefix(self.index_name)
# Get keys or ids from kwargs
# Other vectorstores use ids
keys_or_ids = kwargs.get("keys", kwargs.get("ids"))
# Write data to redis
pipeline = self.client.pipeline(transaction=False)
for i, text in enumerate(texts):
# U... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
69ea6f4346f3-5 | [docs] def similarity_search_limit_score(
self, query: str, k: int = 4, score_threshold: float = 0.2, **kwargs: Any
) -> List[Document]:
"""
Returns the most similar indexed documents to the query text within the
score_threshold range.
Args:
query (str): The qu... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
69ea6f4346f3-6 | return (
Query(base_query)
.return_fields(*return_fields)
.sort_by("vector_score")
.paging(0, k)
.dialect(2)
)
[docs] def similarity_search_with_score(
self, query: str, k: int = 4
) -> List[Tuple[Document, float]]:
"""Return doc... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
69ea6f4346f3-7 | 0 is dissimilar, 1 is most similar.
"""
if self.relevance_score_fn is None:
raise ValueError(
"relevance_score_fn must be provided to"
" Redis constructor to normalize scores"
)
docs_and_scores = self.similarity_search_with_score(query, k=k... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
69ea6f4346f3-8 | )
"""
redis_url = get_from_dict_or_env(kwargs, "redis_url", "REDIS_URL")
if "redis_url" in kwargs:
kwargs.pop("redis_url")
# Name of the search index if not given
if not index_name:
index_name = uuid.uuid4().hex
# Create instance
instance =... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
69ea6f4346f3-9 | Example:
.. code-block:: python
from langchain.vectorstores import Redis
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
redisearch = RediSearch.from_texts(
texts,
embedd... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
69ea6f4346f3-10 | except ValueError as e:
raise ValueError(f"Your redis connected error: {e}")
# Check if index exists
try:
client.delete(*ids)
logger.info("Entries deleted")
return True
except: # noqa: E722
# ids does not exist
return False... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
69ea6f4346f3-11 | [docs] @classmethod
def from_existing_index(
cls,
embedding: Embeddings,
index_name: str,
content_key: str = "content",
metadata_key: str = "metadata",
vector_key: str = "content_vector",
**kwargs: Any,
) -> Redis:
"""Connect to an existing Redi... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
69ea6f4346f3-12 | return RedisVectorStoreRetriever(vectorstore=self, **kwargs)
class RedisVectorStoreRetriever(VectorStoreRetriever, BaseModel):
vectorstore: Redis
search_type: str = "similarity"
k: int = 4
score_threshold: float = 0.4
class Config:
"""Configuration for this pydantic object."""
arbitr... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
69ea6f4346f3-13 | ) -> List[str]:
"""Add documents to vectorstore."""
return await self.vectorstore.aadd_documents(documents, **kwargs) | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
2df5d3448a75-0 | Source code for langchain.vectorstores.docarray.hnsw
"""Wrapper around Hnswlib store."""
from __future__ import annotations
from typing import Any, List, Literal, Optional
from langchain.embeddings.base import Embeddings
from langchain.vectorstores.docarray.base import (
DocArrayIndex,
_check_docarray_import,
)... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html |
2df5d3448a75-1 | "cosine", "ip", and "l2". Defaults to "cosine".
max_elements (int): Maximum number of vectors that can be stored.
Defaults to 1024.
index (bool): Whether an index should be built for this field.
Defaults to True.
ef_construction (int): defines a constr... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html |
2df5d3448a75-2 | work_dir: Optional[str] = None,
n_dim: Optional[int] = None,
**kwargs: Any,
) -> DocArrayHnswSearch:
"""Create an DocArrayHnswSearch store and insert data.
Args:
texts (List[str]): Text data.
embedding (Embeddings): Embedding function.
metadatas (O... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html |
a064d064e258-0 | Source code for langchain.vectorstores.docarray.in_memory
"""Wrapper around in-memory storage."""
from __future__ import annotations
from typing import Any, Dict, List, Literal, Optional
from langchain.embeddings.base import Embeddings
from langchain.vectorstores.docarray.base import (
DocArrayIndex,
_check_doc... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/in_memory.html |
a064d064e258-1 | [docs] @classmethod
def from_texts(
cls,
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[Dict[Any, Any]]] = None,
**kwargs: Any,
) -> DocArrayInMemorySearch:
"""Create an DocArrayInMemorySearch store and insert data.
Args:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/in_memory.html |
98a23b307d98-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://api.python.langchain.com/en/latest/_modules/langchain/retrievers/remote_retriever.html |
88c9f77dcf63-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://api.python.langchain.com/en/latest/_modules/langchain/retrievers/elastic_search_bm25.html |
88c9f77dcf63-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://api.python.langchain.com/en/latest/_modules/langchain/retrievers/elastic_search_bm25.html |
88c9f77dcf63-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://api.python.langchain.com/en/latest/_modules/langchain/retrievers/elastic_search_bm25.html |
9395e9f1be48-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://api.python.langchain.com/en/latest/_modules/langchain/retrievers/contextual_compression.html |
9395e9f1be48-1 | compressed_docs = await self.base_compressor.acompress_documents(
docs, query
)
return list(compressed_docs)
else:
return [] | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/contextual_compression.html |
1d83de5f7b01-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://api.python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html |
1d83de5f7b01-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://api.python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html |
1d83de5f7b01-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"]["... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html |
6be6acadc92c-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://api.python.langchain.com/en/latest/_modules/langchain/retrievers/vespa_retriever.html |
6be6acadc92c-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://api.python.langchain.com/en/latest/_modules/langchain/retrievers/vespa_retriever.html |
6be6acadc92c-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://api.python.langchain.com/en/latest/_modules/langchain/retrievers/vespa_retriever.html |
08e3af67dfa4-0 | Source code for langchain.retrievers.llama_index
from typing import Any, Dict, List, cast
from pydantic import BaseModel, Field
from langchain.schema import BaseRetriever, Document
[docs]class LlamaIndexRetriever(BaseRetriever, BaseModel):
"""Question-answering with sources over an LlamaIndex data structure."""
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/llama_index.html |
08e3af67dfa4-1 | graph: Any
query_configs: List[Dict] = Field(default_factory=list)
[docs] def get_relevant_documents(self, query: str) -> List[Document]:
"""Get documents relevant for a query."""
try:
from llama_index.composability.graph import (
QUERY_CONFIG_TYPE,
Com... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/llama_index.html |
af0f477dcb78-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://api.python.langchain.com/en/latest/_modules/langchain/retrievers/azure_cognitive_search.html |
af0f477dcb78-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://api.python.langchain.com/en/latest/_modules/langchain/retrievers/azure_cognitive_search.html |
af0f477dcb78-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://api.python.langchain.com/en/latest/_modules/langchain/retrievers/azure_cognitive_search.html |
d73dda26bf8a-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()... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/pupmed.html |
ef81497e12f7-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://api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html |
ef81497e12f7-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://api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html |
ef81497e12f7-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://api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html |
ef81497e12f7-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.""... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html |
03ea56542edd-0 | Source code for langchain.retrievers.metal
from typing import Any, List, Optional
from langchain.schema import BaseRetriever, Document
[docs]class MetalRetriever(BaseRetriever):
"""Retriever that uses the Metal API."""
def __init__(self, client: Any, params: Optional[dict] = None):
from metal_sdk.metal ... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/metal.html |
8543eae0b331-0 | Source code for langchain.retrievers.docarray
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import numpy as np
from pydantic import BaseModel
from langchain.embeddings.base import Embeddings
from langchain.schema import BaseRetriever, Document
from langchain.vectorstores.utils import maximal... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/docarray.html |
8543eae0b331-1 | """Configuration for this pydantic object."""
arbitrary_types_allowed = True
[docs] def get_relevant_documents(self, query: str) -> List[Document]:
"""Get documents relevant for a query.
Args:
query: string to find relevant documents for
Returns:
List of releva... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/docarray.html |
8543eae0b331-2 | if self.filters:
query = (
self.index.build_query() # get empty query object
.find(
query=query_emb, search_field=search_field
) # add vector similarity search
.filter(**filter_args) # add filter search
.b... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/docarray.html |
8543eae0b331-3 | else getattr(doc, self.search_field)
for doc in docs
],
k=self.top_k,
)
results = [self._docarray_to_langchain_doc(docs[idx]) for idx in mmr_selected]
return results
def _docarray_to_langchain_doc(self, doc: Union[Dict[str, Any], Any]) -> Document:
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/docarray.html |
691b53995d6b-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://api.python.langchain.com/en/latest/_modules/langchain/retrievers/wikipedia.html |
990796014d06-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://api.python.langchain.com/en/latest/_modules/langchain/retrievers/knn.html |
990796014d06-1 | query_embeds = np.array(self.embeddings.embed_query(query))
# calc L2 norm
index_embeds = self.index / np.sqrt((self.index**2).sum(1, keepdims=True))
query_embeds = query_embeds / np.sqrt((query_embeds**2).sum())
similarities = index_embeds.dot(query_embeds)
sorted_ix = np.argsor... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/knn.html |
ec60f923f49b-0 | Source code for langchain.retrievers.milvus
"""Milvus Retriever"""
import warnings
from typing import Any, Dict, List, Optional
from langchain.embeddings.base import Embeddings
from langchain.schema import BaseRetriever, Document
from langchain.vectorstores.milvus import Milvus
# TODO: Update to MilvusClient + Hybrid S... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/milvus.html |
ec60f923f49b-1 | raise NotImplementedError
def MilvusRetreiver(*args: Any, **kwargs: Any) -> MilvusRetriever:
"""Deprecated MilvusRetreiver. Please use MilvusRetriever ('i' before 'e') instead.
Args:
*args:
**kwargs:
Returns:
MilvusRetriever
"""
warnings.warn(
"MilvusRetreiver will be... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/milvus.html |
f1a23d85538d-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://api.python.langchain.com/en/latest/_modules/langchain/retrievers/chatgpt_plugin_retriever.html |
f1a23d85538d-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... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/chatgpt_plugin_retriever.html |
aeb291d7ee0a-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://api.python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html |
aeb291d7ee0a-1 | for i in _iterator:
# find end of batch
i_end = min(i + batch_size, len(contexts))
# extract batch
context_batch = contexts[i:i_end]
batch_ids = ids[i:i_end]
metadata_batch = (
metadatas[i:i_end] if metadatas else [{} for _ in context_batch]
)
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html |
aeb291d7ee0a-2 | arbitrary_types_allowed = True
[docs] def add_texts(
self,
texts: List[str],
ids: Optional[List[str]] = None,
metadatas: Optional[List[dict]] = None,
) -> None:
create_index(
texts,
self.index,
self.embeddings,
self.sparse_en... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html |
aeb291d7ee0a-3 | top_k=self.top_k,
include_metadata=True,
)
final_result = []
for res in result["matches"]:
context = res["metadata"].pop("context")
final_result.append(
Document(page_content=context, metadata=res["metadata"])
)
# return sea... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html |
ac0a4067d953-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):
"""Retriever that uses the Databerry API."""
datastore_url: str
top_k: Optional[int]
api_key... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/databerry.html |
ac0a4067d953-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://api.python.langchain.com/en/latest/_modules/langchain/retrievers/databerry.html |
014e57f2dece-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... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/zep.html |
014e57f2dece-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... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/zep.html |
1005bee1386f-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://api.python.langchain.com/en/latest/_modules/langchain/retrievers/svm.html |
1005bee1386f-1 | query_embeds = np.array(self.embeddings.embed_query(query))
x = np.concatenate([query_embeds[None, ...], self.index])
y = np.zeros(x.shape[0])
y[0] = 1
clf = svm.LinearSVC(
class_weight="balanced", verbose=False, max_iter=10000, tol=1e-6, C=0.1
)
clf.fit(x, y)... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/svm.html |
abdd6368a0c1-0 | Source code for langchain.retrievers.multi_query
import logging
from typing import List
from pydantic import BaseModel, Field
from langchain.chains.llm import LLMChain
from langchain.llms.base import BaseLLM
from langchain.output_parsers.pydantic import PydanticOutputParser
from langchain.prompts.prompt import PromptTe... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/multi_query.html |
abdd6368a0c1-1 | llm_chain: LLMChain,
verbose: bool = True,
parser_key: str = "lines",
) -> None:
"""Initialize MultiQueryRetriever.
Args:
retriever: retriever to query documents from
llm_chain: llm_chain for query generation
verbose: show the queries that we gener... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/multi_query.html |
abdd6368a0c1-2 | Returns:
Unique union of relevant documents from all generated queries
"""
queries = self.generate_queries(question)
documents = self.retrieve_documents(queries)
unique_documents = self.unique_union(documents)
return unique_documents
[docs] async def aget_relevant_... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/multi_query.html |
abdd6368a0c1-3 | for doc in documents
}
unique_documents = list(unique_documents_dict.values())
return unique_documents | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/multi_query.html |
152f3fb8cfec-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 __... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/merger_retriever.html |
152f3fb8cfec-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... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/merger_retriever.html |
a1402ed09f96-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://api.python.langchain.com/en/latest/_modules/langchain/retrievers/arxiv.html |
2c8a1e4bc351-0 | Source code for langchain.retrievers.kendra
import re
from typing import Any, Dict, List, Literal, Optional
from pydantic import BaseModel, Extra
from langchain.docstore.document import Document
from langchain.schema import BaseRetriever
def clean_excerpt(excerpt: str) -> str:
if not excerpt:
return excerpt... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html |
2c8a1e4bc351-1 | def get_attribute_value(self) -> str:
if not self.AdditionalAttributes:
return ""
if not self.AdditionalAttributes[0]:
return ""
else:
return self.AdditionalAttributes[0].get_value_text()
def get_excerpt(self) -> str:
if (
self.Addition... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html |
2c8a1e4bc351-2 | Key: str
Value: DocumentAttributeValue
class RetrieveResultItem(BaseModel, extra=Extra.allow):
Content: Optional[str]
DocumentAttributes: Optional[List[DocumentAttribute]] = []
DocumentId: Optional[str]
DocumentTitle: Optional[str]
DocumentURI: Optional[str]
Id: Optional[str]
def get_exc... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html |
2c8a1e4bc351-3 | or ~/.aws/config files, which has either access keys or role information
specified. If not specified, the default credential profile or, if on an
EC2 instance, credentials from IMDS will be used.
top_k: No of results to return
attribute_filter: Additional filtering of results bas... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html |
2c8a1e4bc351-4 | "Please install it with `pip install boto3`."
)
except Exception as e:
raise ValueError(
"Could not load credentials to authenticate with AWS client. "
"Please check that credentials in the specified "
"profile name are valid."
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html |
2c8a1e4bc351-5 | """Run search on Kendra index and get top k documents
Example:
.. code-block:: python
docs = retriever.get_relevant_documents('This is my query')
"""
docs = self._kendra_query(query, self.top_k, self.attribute_filter)
return docs
[docs] async def aget_relevant_docu... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html |
c2e92f691419-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://api.python.langchain.com/en/latest/_modules/langchain/retrievers/tfidf.html |
c2e92f691419-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://api.python.langchain.com/en/latest/_modules/langchain/retrievers/tfidf.html |
6a68ffd57cda-0 | Source code for langchain.retrievers.zilliz
"""Zilliz Retriever"""
import warnings
from typing import Any, Dict, List, Optional
from langchain.embeddings.base import Embeddings
from langchain.schema import BaseRetriever, Document
from langchain.vectorstores.zilliz import Zilliz
# TODO: Update to ZillizClient + Hybrid S... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/zilliz.html |
6a68ffd57cda-1 | raise NotImplementedError
def ZillizRetreiver(*args: Any, **kwargs: Any) -> ZillizRetriever:
"""
Deprecated ZillizRetreiver. Please use ZillizRetriever ('i' before 'e') instead.
Args:
*args:
**kwargs:
Returns:
ZillizRetriever
"""
warnings.warn(
"ZillizRetreiver wi... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/zilliz.html |
aa6d8bbbfe79-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://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/cohere_rerank.html |
aa6d8bbbfe79-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]
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/cohere_rerank.html |
dca67d1844c2-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://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_filter.html |
dca67d1844c2-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://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_filter.html |
d715578d933a-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://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/base.html |
d715578d933a-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://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/base.html |
baa8da819db9-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://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html |
baa8da819db9-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://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html |
baa8da819db9-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) | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html |
1cd3aded5f24-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://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/embeddings_filter.html |
1cd3aded5f24-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://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/embeddings_filter.html |
c333be1ed1c6-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://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html |
c333be1ed1c6-1 | if vectorstore_cls not in BUILTIN_TRANSLATORS:
raise ValueError(
f"Self query retriever with Vector Store type {vectorstore_cls}"
f" not supported."
)
if isinstance(vectorstore, Qdrant):
return QdrantTranslator(metadata_key=vectorstore.metadata_payload_key)
elif i... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html |
c333be1ed1c6-2 | values["vectorstore"]
)
return values
[docs] def get_relevant_documents(
self, query: str, callbacks: Callbacks = None
) -> List[Document]:
"""Get documents relevant for a query.
Args:
query: string to find relevant documents for
Returns:
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html |
c333be1ed1c6-3 | if structured_query_translator is None:
structured_query_translator = _get_builtin_translator(vectorstore)
chain_kwargs = chain_kwargs or {}
if "allowed_comparators" not in chain_kwargs:
chain_kwargs[
"allowed_comparators"
] = structured_query_translat... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html |
d8867cdfc156-0 | Source code for langchain.chains.loading
"""Functionality for loading chains."""
import json
from pathlib import Path
from typing import Any, Union
import yaml
from langchain.chains.api.base import APIChain
from langchain.chains.base import Chain
from langchain.chains.combine_documents.map_reduce import MapReduceDocume... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
d8867cdfc156-1 | def _load_llm_chain(config: dict, **kwargs: Any) -> LLMChain:
"""Load LLM chain from config dict."""
if "llm" in config:
llm_config = config.pop("llm")
llm = load_llm_from_config(llm_config)
elif "llm_path" in config:
llm = load_llm(config.pop("llm_path"))
else:
raise Val... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
d8867cdfc156-2 | return HypotheticalDocumentEmbedder(
llm_chain=llm_chain, base_embeddings=embeddings, **config
)
def _load_stuff_documents_chain(config: dict, **kwargs: Any) -> StuffDocumentsChain:
if "llm_chain" in config:
llm_chain_config = config.pop("llm_chain")
llm_chain = load_chain_from_config(ll... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
d8867cdfc156-3 | llm_chain = load_chain(config.pop("llm_chain_path"))
else:
raise ValueError("One of `llm_chain` or `llm_chain_config` must be present.")
if not isinstance(llm_chain, LLMChain):
raise ValueError(f"Expected LLMChain, got {llm_chain}")
if "combine_document_chain" in config:
combine_docu... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.