id stringlengths 14 16 | text stringlengths 36 2.73k | source stringlengths 49 117 |
|---|---|---|
36481f540ad3-2 | self, topic: str, now: Optional[datetime] = None
) -> List[str]:
"""Generate 'insights' on a topic of reflection, based on pertinent memories."""
prompt = PromptTemplate.from_template(
"Statements relevant to: '{topic}'\n"
"---\n"
"{related_statements}\n"
... | https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html |
36481f540ad3-3 | insights = self._get_insights_on_topic(topic, now=now)
for insight in insights:
self.add_memory(insight, now=now)
new_insights.extend(insights)
return new_insights
def _score_memory_importance(self, memory_content: str) -> float:
"""Score the absolute importan... | https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html |
36481f540ad3-4 | + " acceptance), rate the likely poignancy of the"
+ " following piece of memory. Always answer with only a list of numbers."
+ " If just given one memory still respond in a list."
+ " Memories are separated by semi colans (;)"
+ "\Memories: {memory_content}"
... | https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html |
36481f540ad3-5 | and not self.reflecting
):
self.reflecting = True
self.pause_to_reflect(now=now)
# Hack to clear the importance from reflection
self.aggregate_importance = 0.0
self.reflecting = False
return result
[docs] def add_memory(
self, memory... | https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html |
36481f540ad3-6 | else:
return self.memory_retriever.get_relevant_documents(observation)
def format_memories_detail(self, relevant_memories: List[Document]) -> str:
content = []
for mem in relevant_memories:
content.append(self._format_memory_detail(mem, prefix="- "))
return "\n".join(... | https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html |
36481f540ad3-7 | now = inputs.get(self.now_key)
if queries is not None:
relevant_memories = [
mem for query in queries for mem in self.fetch_memories(query, now=now)
]
return {
self.relevant_memories_key: self.format_memories_detail(
relevan... | https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html |
5164b97cae39-0 | Source code for langchain.experimental.generative_agents.generative_agent
import re
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple
from pydantic import BaseModel, Field
from langchain import LLMChain
from langchain.base_language import BaseLanguageModel
from langchain.experimental.gen... | https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html |
5164b97cae39-1 | arbitrary_types_allowed = True
# LLM-related methods
@staticmethod
def _parse_list(text: str) -> List[str]:
"""Parse a newline-separated string into a list of strings."""
lines = re.split(r"\n", text.strip())
return [re.sub(r"^\s*\d+\.\s*", "", line).strip() for line in lines]
de... | https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html |
5164b97cae39-2 | entity_action = self._get_entity_action(observation, entity_name)
q1 = f"What is the relationship between {self.name} and {entity_name}"
q2 = f"{entity_name} is {entity_action}"
return self.chain(prompt=prompt).run(q1=q1, queries=[q1, q2]).strip()
def _generate_reaction(
self, observ... | https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html |
5164b97cae39-3 | )
consumed_tokens = self.llm.get_num_tokens(
prompt.format(most_recent_memories="", **kwargs)
)
kwargs[self.memory.most_recent_memories_token_key] = consumed_tokens
return self.chain(prompt=prompt).run(**kwargs).strip()
def _clean_response(self, text: str) -> str:
... | https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html |
5164b97cae39-4 | if "SAY:" in result:
said_value = self._clean_response(result.split("SAY:")[-1])
return True, f"{self.name} said {said_value}"
else:
return False, result
[docs] def generate_dialogue_response(
self, observation: str, now: Optional[datetime] = None
) -> Tuple[bo... | https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html |
5164b97cae39-5 | )
return True, f"{self.name} said {response_text}"
else:
return False, result
######################################################
# Agent stateful' summary methods. #
# Each dialog or response prompt includes a header #
# summarizing the agent's sel... | https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html |
5164b97cae39-6 | + f"\nInnate traits: {self.traits}"
+ f"\n{self.summary}"
)
[docs] def get_full_header(
self, force_refresh: bool = False, now: Optional[datetime] = None
) -> str:
"""Return a full header of the agent's status, summary, and current time."""
now = datetime.now() if now ... | https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html |
a188dffdda6e-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 |
ff7b2e1a7faa-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 |
ff7b2e1a7faa-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 |
ff7b2e1a7faa-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 |
a30c4d813f67-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://python.langchain.com/en/latest/_modules/langchain/retrievers/pupmed.html |
19f8fca17d41-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 |
19f8fca17d41-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 |
c8ddbcbaa2fc-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 |
c8ddbcbaa2fc-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 |
c8ddbcbaa2fc-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 |
b0a5e8d6d52d-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 |
12f3ca851a30-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 |
12f3ca851a30-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 |
cbdfa619a38d-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 |
cbdfa619a38d-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... | https://python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html |
cbdfa619a38d-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 |
da2be2fe8b23-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 |
da2be2fe8b23-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 |
da2be2fe8b23-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 |
da2be2fe8b23-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://python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html |
c2c8dd5d90a5-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 |
c2c8dd5d90a5-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 |
c2c8dd5d90a5-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://python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html |
ee989284a269-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://python.langchain.com/en/latest/_modules/langchain/retrievers/zep.html |
ee989284a269-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://python.langchain.com/en/latest/_modules/langchain/retrievers/zep.html |
0d4fdac9f8a2-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 |
0d4fdac9f8a2-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... | https://python.langchain.com/en/latest/_modules/langchain/retrievers/knn.html |
32d37bcc875c-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 |
32d37bcc875c-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 |
1a04a6add156-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 |
d532b8aed272-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 |
d532b8aed272-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 |
d532b8aed272-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 |
4ea7338bfc21-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 |
4ea7338bfc21-1 | 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 |
745e96522f02-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://python.langchain.com/en/latest/_modules/langchain/retrievers/merger_retriever.html |
745e96522f02-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://python.langchain.com/en/latest/_modules/langchain/retrievers/merger_retriever.html |
55e6d3c7e2be-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 |
55e6d3c7e2be-1 | return list(compressed_docs)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 11, 2023. | https://python.langchain.com/en/latest/_modules/langchain/retrievers/contextual_compression.html |
fc90dc88438a-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 |
faeac3fc9c0f-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... | https://python.langchain.com/en/latest/_modules/langchain/retrievers/aws_kendra_index_retriever.html |
faeac3fc9c0f-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":... | https://python.langchain.com/en/latest/_modules/langchain/retrievers/aws_kendra_index_retriever.html |
95f2bf39d14e-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 |
95f2bf39d14e-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 |
51edcea0bcee-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 |
51edcea0bcee-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://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/cohere_rerank.html |
de3863e2f03c-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 |
de3863e2f03c-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 |
ba936cb49a3e-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 |
ba936cb49a3e-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 |
8ce6b3c39fe3-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 |
8ce6b3c39fe3-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 |
8ce6b3c39fe3-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 Jun 11, 2023. | https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html |
f06de8e32e77-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 |
f06de8e32e77-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
... | https://python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html |
f06de8e32e77-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... | https://python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html |
f06de8e32e77-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 11, 2023. | https://python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html |
63674000c00a-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
63674000c00a-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
63674000c00a-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
63674000c00a-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
63674000c00a-4 | """
ids = []
prefix = _redis_prefix(self.index_name)
# Write data to redis
pipeline = self.client.pipeline(transaction=False)
for i, text in enumerate(texts):
# Use provided values by default or fallback
key = keys[i] if keys else _redis_key(prefix)
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
63674000c00a-5 | ) -> List[Document]:
"""
Returns the most similar indexed documents to the query text within the
score_threshold range.
Args:
query (str): The query text for which to find similar documents.
k (int): The number of documents to return. Default is 4.
sco... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
63674000c00a-6 | .paging(0, k)
.dialect(2)
)
[docs] def similarity_search_with_score(
self, query: str, k: int = 4
) -> List[Tuple[Document, float]]:
"""Return docs most similar to query.
Args:
query: Text to look up documents similar to.
k: Number of Documents ... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
63674000c00a-7 | 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)
return [(doc, self.relevance_score_fn(score)) for doc, score in docs_and_scores]
[docs] @cl... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
63674000c00a-8 | kwargs.pop("redis_url")
# Name of the search index if not given
if not index_name:
index_name = uuid.uuid4().hex
# Create instance
instance = cls(
redis_url,
index_name,
embedding.embed_query,
content_key=content_key,
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
63674000c00a-9 | embeddings = OpenAIEmbeddings()
redisearch = RediSearch.from_texts(
texts,
embeddings,
redis_url="redis://username:password@localhost:6379"
)
"""
instance, _ = cls.from_texts_return_keys(
texts,
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
63674000c00a-10 | try:
client.ft(index_name).dropindex(delete_documents)
logger.info("Drop index")
return True
except: # noqa: E722
# Index not exist
return False
[docs] @classmethod
def from_existing_index(
cls,
embedding: Embeddings,
in... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
63674000c00a-11 | vector_key=vector_key,
**kwargs,
)
[docs] def as_retriever(self, **kwargs: Any) -> RedisVectorStoreRetriever:
return RedisVectorStoreRetriever(vectorstore=self, **kwargs)
class RedisVectorStoreRetriever(VectorStoreRetriever, BaseModel):
vectorstore: Redis
search_type: str = "simil... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
63674000c00a-12 | """Add documents to vectorstore."""
return self.vectorstore.add_documents(documents, **kwargs)
async def aadd_documents(
self, documents: List[Document], **kwargs: Any
) -> List[str]:
"""Add documents to vectorstore."""
return await self.vectorstore.aadd_documents(documents, **kw... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
c421bd8e3941-0 | Source code for langchain.vectorstores.clickhouse
"""Wrapper around open source ClickHouse VectorSearch capability."""
from __future__ import annotations
import json
import logging
from hashlib import sha1
from threading import Thread
from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
from pydantic im... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
c421bd8e3941-1 | column_map (Dict) : Column type map to project column name onto langchain
semantics. Must have keys: `text`, `id`, `vector`,
must be same size to number of columns. For example:
.. code-block:: python
{
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
c421bd8e3941-2 | to connect to ClickHouse.
ClickHouse can not only search with simple vector indexes,
it also supports complex query with multiple conditions,
constraints and even sub-queries.
For more information, please visit
[ClickHouse official site](https://clickhouse.com/clickhouse)
"""
def __init_... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
c421bd8e3941-3 | "angular",
"euclidean",
"manhattan",
"hamming",
"dot",
]
# initialize the schema
dim = len(embedding.embed_query("test"))
index_params = (
(
",".join([f"'{k}={v}'" for k, v in self.config.index_param.items()])
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
c421bd8e3941-4 | host=self.config.host,
port=self.config.port,
username=self.config.username,
password=self.config.password,
**kwargs,
)
# Enable JSON type
self.client.command("SET allow_experimental_object_type=1")
# Enable Annoy index
self.client.... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
c421bd8e3941-5 | """Insert more texts through the embeddings and add to the VectorStore.
Args:
texts: Iterable of strings to add to the VectorStore.
ids: Optional list of ids to associate with the texts.
batch_size: Batch size of insertion
metadata: Optional column data to be inse... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
c421bd8e3941-6 | if t:
t.join()
self._insert(transac, keys)
return [i for i in ids]
except Exception as e:
logger.error(f"\033[91m\033[1m{type(e)}\033[0m \033[95m{str(e)}\033[0m")
return []
[docs] @classmethod
def from_texts(
cls,
tex... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
c421bd8e3941-7 | return ctx
def __repr__(self) -> str:
"""Text representation for ClickHouse Vector Store, prints backends, username
and schemas. Easy to use with `str(ClickHouse())`
Returns:
repr: string to show connection info and data schema
"""
_repr = f"\033[92m\033[1m{se... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
c421bd8e3941-8 | q_str = f"""
SELECT {self.config.column_map['document']},
{self.config.column_map['metadata']}, dist
FROM {self.config.database}.{self.config.table}
{where_str}
ORDER BY L2Distance({self.config.column_map['embedding']}, [{q_emb_str}])
AS ... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
c421bd8e3941-9 | Args:
query (str): query string
k (int, optional): Top K neighbors to retrieve. Defaults to 4.
where_str (Optional[str], optional): where condition string.
Defaults to None.
NOTE: Please do not let end-user to fill this and... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
c421bd8e3941-10 | NOTE: Please do not let end-user to fill this and always be aware
of SQL injection. When dealing with metadatas, remember to
use `{self.metadata_column}.attribute` instead of `attribute`
alone. The default name for it is `metadata`.
Returns:
List... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
2b0cfa121219-0 | Source code for langchain.vectorstores.mongodb_atlas
from __future__ import annotations
import logging
from typing import (
TYPE_CHECKING,
Any,
Dict,
Generator,
Iterable,
List,
Optional,
Tuple,
TypeVar,
Union,
)
from langchain.docstore.document import Document
from langchain.embe... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
2b0cfa121219-1 | """
Args:
collection: MongoDB collection to add the texts to.
embedding: Text embedding model to use.
text_key: MongoDB field that will contain the text for each
document.
embedding_key: MongoDB field that will contain the embedding for
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
2b0cfa121219-2 | """
batch_size = kwargs.get("batch_size", DEFAULT_INSERT_BATCH_SIZE)
_metadatas: Union[List, Generator] = metadatas or ({} for _ in texts)
texts_batch = []
metadatas_batch = []
result_ids = []
for i, (text, metadata) in enumerate(zip(texts, _metadatas)):
texts... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
2b0cfa121219-3 | """Return MongoDB documents most similar to query, along with scores.
Use the knnBeta Operator available in MongoDB Atlas Search
This feature is in early access and available only for evaluation purposes, to
validate functionality, and to gather feedback from a small closed group of
earl... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
2b0cfa121219-4 | docs.append((Document(page_content=text, metadata=res), score))
return docs
[docs] def similarity_search(
self,
query: str,
k: int = 4,
pre_filter: Optional[dict] = None,
post_filter_pipeline: Optional[List[Dict]] = None,
**kwargs: Any,
) -> List[Document]:... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
2b0cfa121219-5 | collection: Optional[Collection[MongoDBDocumentType]] = None,
**kwargs: Any,
) -> MongoDBAtlasVectorSearch:
"""Construct MongoDBAtlasVectorSearch wrapper from raw documents.
This is a user-friendly interface that:
1. Embeds documents.
2. Adds the documents to a provid... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/mongodb_atlas.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.