id stringlengths 14 16 | text stringlengths 13 2.7k | source stringlengths 57 178 |
|---|---|---|
012377404a81-2 | to set this to False if the documents are already in the docstore
and you don't want to re-add them.
"""
if self.parent_splitter is not None:
documents = self.parent_splitter.split_documents(documents)
if ids is None:
doc_ids = [str(uuid.uuid4()) for _ in ... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/parent_document_retriever.html |
767448b82452-0 | Source code for langchain.retrievers.time_weighted_retriever
import datetime
from copy import deepcopy
from typing import Any, Dict, List, Optional, Tuple
from langchain.callbacks.manager import CallbackManagerForRetrieverRun
from langchain.pydantic_v1 import Field
from langchain.schema import BaseRetriever, Document
f... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html |
767448b82452-1 | """
class Config:
"""Configuration for this pydantic object."""
arbitrary_types_allowed = True
def _document_get_date(self, field: str, document: Document) -> datetime.datetime:
"""Return the value of the date field of a document."""
if field in document.metadata:
if ... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html |
767448b82452-2 | results[buffer_idx] = (doc, relevance)
return results
def _get_relevant_documents(
self, query: str, *, run_manager: CallbackManagerForRetrieverRun
) -> List[Document]:
"""Return documents that are relevant to the query."""
current_time = datetime.datetime.now()
docs_and_... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html |
767448b82452-3 | if "last_accessed_at" not in doc.metadata:
doc.metadata["last_accessed_at"] = current_time
if "created_at" not in doc.metadata:
doc.metadata["created_at"] = current_time
doc.metadata["buffer_idx"] = len(self.memory_stream) + i
self.memory_stream.extend(dup... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html |
63be1662c062-0 | Source code for langchain.retrievers.chatgpt_plugin_retriever
from __future__ import annotations
from typing import List, Optional
import aiohttp
import requests
from langchain.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
from langchain.schema import BaseRetr... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/chatgpt_plugin_retriever.html |
63be1662c062-1 | return docs
async def _aget_relevant_documents(
self, query: str, *, run_manager: AsyncCallbackManagerForRetrieverRun
) -> List[Document]:
url, json, headers = self._create_request(query)
if not self.aiosession:
async with aiohttp.ClientSession() as session:
a... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/chatgpt_plugin_retriever.html |
d5a8a13d84fd-0 | Source code for langchain.retrievers.merger_retriever
import asyncio
from typing import List
from langchain.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
from langchain.schema import BaseRetriever, Document
[docs]class MergerRetriever(BaseRetriever):
"""Re... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/merger_retriever.html |
d5a8a13d84fd-1 | """
Merge the results of the retrievers.
Args:
query: The query to search for.
Returns:
A list of merged documents.
"""
# Get the results of all retrievers.
retriever_docs = [
retriever.get_relevant_documents(
query, cal... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/merger_retriever.html |
d5a8a13d84fd-2 | for i in range(max_docs):
for retriever, doc in zip(self.retrievers, retriever_docs):
if i < len(doc):
merged_documents.append(doc[i])
return merged_documents | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/merger_retriever.html |
27fad2887f89-0 | Source code for langchain.retrievers.pubmed
from typing import List
from langchain.callbacks.manager import CallbackManagerForRetrieverRun
from langchain.schema import BaseRetriever, Document
from langchain.utilities.pubmed import PubMedAPIWrapper
[docs]class PubMedRetriever(BaseRetriever, PubMedAPIWrapper):
"""`Pu... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/pubmed.html |
8caf3b79fbb5-0 | Source code for langchain.retrievers.ensemble
"""
Ensemble retriever that ensemble the results of
multiple retrievers by using weighted Reciprocal Rank Fusion
"""
from typing import Any, Dict, List
from langchain.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/ensemble.html |
8caf3b79fbb5-1 | Args:
query: The query to search for.
Returns:
A list of reranked documents.
"""
# Get fused result of the retrievers.
fused_documents = self.rank_fusion(query, run_manager)
return fused_documents
async def _aget_relevant_documents(
self,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/ensemble.html |
8caf3b79fbb5-2 | self, query: str, run_manager: AsyncCallbackManagerForRetrieverRun
) -> List[Document]:
"""
Asynchronously retrieve the results of the retrievers
and use rank_fusion_func to get the final result.
Args:
query: The query to search for.
Returns:
A list of... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/ensemble.html |
8caf3b79fbb5-3 | for doc_list in doc_lists:
for doc in doc_list:
all_documents.add(doc.page_content)
# Initialize the RRF score dictionary for each document
rrf_score_dic = {doc: 0.0 for doc in all_documents}
# Calculate RRF scores for each document
for doc_list, weight in zip... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/ensemble.html |
e23fd02f59f4-0 | Source code for langchain.retrievers.weaviate_hybrid_search
from __future__ import annotations
from typing import Any, Dict, List, Optional, cast
from uuid import uuid4
from langchain.callbacks.manager import CallbackManagerForRetrieverRun
from langchain.docstore.document import Document
from langchain.pydantic_v1 impo... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html |
e23fd02f59f4-1 | client = values["client"]
raise ValueError(
f"client should be an instance of weaviate.Client, got {type(client)}"
)
if values.get("attributes") is None:
values["attributes"] = []
cast(List, values["attributes"]).append(values["text_key"])
if v... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html |
e23fd02f59f4-2 | return ids
def _get_relevant_documents(
self,
query: str,
*,
run_manager: CallbackManagerForRetrieverRun,
where_filter: Optional[Dict[str, object]] = None,
score: bool = False,
hybrid_search_kwargs: Optional[Dict[str, object]] = None,
) -> List[Document]:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html |
e23fd02f59f4-3 | to be used during the hybrid search portion.
Example - hybrid_search_kwargs={"vector": [0.1, 0.2, 0.3, ...]}
https://weaviate.io/developers/weaviate/search/hybrid#with-a-custom-vector
4) Use Fusion ranking method
Example - from weaviate.gql.get import HybridFusion... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html |
ffe3488b7cad-0 | Source code for langchain.retrievers.re_phraser
import logging
from typing import List
from langchain.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
from langchain.chains.llm import LLMChain
from langchain.llms.base import BaseLLM
from langchain.prompts.prompt ... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/re_phraser.html |
ffe3488b7cad-1 | Returns:
RePhraseQueryRetriever
"""
llm_chain = LLMChain(llm=llm, prompt=prompt)
return cls(
retriever=retriever,
llm_chain=llm_chain,
)
def _get_relevant_documents(
self,
query: str,
*,
run_manager: CallbackManagerF... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/re_phraser.html |
6059e267b354-0 | Source code for langchain.retrievers.google_vertex_ai_search
"""Retriever wrapper for Google Vertex AI Search."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence
from langchain.callbacks.manager import CallbackManagerForRetrieverRun
from langchain.pydantic_v1 imp... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/google_vertex_ai_search.html |
6059e267b354-1 | """Validates the environment."""
try:
from google.cloud import discoveryengine_v1beta # noqa: F401
except ImportError as exc:
raise ImportError(
"google.cloud.discoveryengine is not installed."
"Please install it with pip install "
... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/google_vertex_ai_search.html |
6059e267b354-2 | else None
)
def _convert_structured_search_response(
self, results: Sequence[SearchResult]
) -> List[Document]:
"""Converts a sequence of search results to a list of LangChain documents."""
import json
from google.protobuf.json_format import MessageToDict
document... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/google_vertex_ai_search.html |
6059e267b354-3 | documents.append(
Document(
page_content=chunk.get("content", ""), metadata=doc_metadata
)
)
return documents
def _convert_website_search_response(
self, results: Sequence[SearchResult], chunk_type: str
) -> List[Doc... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/google_vertex_ai_search.html |
6059e267b354-4 | )
return documents
[docs]class GoogleVertexAISearchRetriever(BaseRetriever, _BaseGoogleVertexAISearchRetriever):
"""`Google Vertex AI Search` retriever.
For a detailed explanation of the Vertex AI Search concepts
and configuration parameters, refer to the product documentation.
https://cloud.goo... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/google_vertex_ai_search.html |
6059e267b354-5 | 2 - Automatic query expansion built by the Search API.
"""
spell_correction_mode: int = Field(default=2, ge=0, le=2)
"""Specification to determine under which conditions query expansion should occur.
0 - Unspecified spell correction mode. In this case, server behavior defaults
to auto.
1 - ... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/google_vertex_ai_search.html |
6059e267b354-6 | )
self._serving_config = self._client.serving_config_path(
project=self.project_id,
location=self.location_id,
data_store=self.data_store_id,
serving_config=self.serving_config_id,
)
def _create_search_request(self, query: str) -> SearchRequest:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/google_vertex_ai_search.html |
6059e267b354-7 | ),
)
else:
raise NotImplementedError(
"Only data store type 0 (Unstructured), 1 (Structured),"
"or 2 (Website) are supported currently."
+ f" Got {self.engine_data_type}"
)
return SearchRequest(
query=query,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/google_vertex_ai_search.html |
6059e267b354-8 | response.results, chunk_type
)
else:
raise NotImplementedError(
"Only data store type 0 (Unstructured), 1 (Structured),"
"or 2 (Website) are supported currently."
+ f" Got {self.engine_data_type}"
)
return documents
[doc... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/google_vertex_ai_search.html |
6059e267b354-9 | )
def _get_relevant_documents(
self, query: str, *, run_manager: CallbackManagerForRetrieverRun
) -> List[Document]:
"""Get documents relevant for a query."""
from google.cloud.discoveryengine_v1beta import (
ConverseConversationRequest,
TextInput,
)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/google_vertex_ai_search.html |
857e62d570f4-0 | Source code for langchain.retrievers.vespa_retriever
from __future__ import annotations
import json
from typing import Any, Dict, List, Literal, Optional, Sequence, Union
from langchain.callbacks.manager import CallbackManagerForRetrieverRun
from langchain.schema import BaseRetriever, Document
[docs]class VespaRetrieve... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/vespa_retriever.html |
857e62d570f4-1 | ) -> List[Document]:
body = self.body.copy()
body["query"] = query
return self._query(body)
[docs] def get_relevant_documents_with_filter(
self, query: str, *, _filter: Optional[str] = None
) -> List[Document]:
body = self.body.copy()
_filter = f" and {_filter}" if... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/vespa_retriever.html |
857e62d570f4-2 | yql (Optional[str]): Full YQL query to be used. Should not be specified
if _filter or sources are specified. Defaults to None.
kwargs (Any): Keyword arguments added to query body.
Returns:
VespaRetriever: Instantiated VespaRetriever.
"""
try:
f... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/vespa_retriever.html |
61068e6a3711-0 | Source code for langchain.retrievers.you
from typing import Any, Dict, List, Optional
from langchain.callbacks.manager import CallbackManagerForRetrieverRun
from langchain.pydantic_v1 import root_validator
from langchain.schema import BaseRetriever, Document
from langchain.utils import get_from_dict_or_env
[docs]class ... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/you.html |
61068e6a3711-1 | headers=headers,
).json()
docs = []
n_hits = self.n_hits or len(results["hits"])
for hit in results["hits"][:n_hits]:
n_snippets_per_hit = self.n_snippets_per_hit or len(hit["snippets"])
for snippet in hit["snippets"][:n_snippets_per_hit]:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/you.html |
7cc089ce94b5-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 langchain.callbacks.manager import CallbackManagerForRetrieverRun
from langchain.pydantic_v1 import Extra, root_validator
from langch... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html |
7cc089ce94b5-1 | if ids is None:
# create unique ids using hash of the text
ids = [hash_text(context) for context in contexts]
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... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html |
7cc089ce94b5-2 | """Embeddings model to use."""
"""description"""
sparse_encoder: Any
"""Sparse encoder to use."""
index: Any
"""Pinecone index to use."""
top_k: int = 4
"""Number of documents to return."""
alpha: float = 0.5
"""Alpha value for hybrid search."""
namespace: Optional[str] = None
... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html |
7cc089ce94b5-3 | self, query: str, *, run_manager: CallbackManagerForRetrieverRun
) -> List[Document]:
from pinecone_text.hybrid import hybrid_convex_scale
sparse_vec = self.sparse_encoder.encode_queries(query)
# convert the question into a dense vector
dense_vec = self.embeddings.embed_query(query)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html |
71625645dfbd-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.callbacks.manager import Callbacks
from langchain.chains import LLMChain
from langchain.outp... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_filter.html |
71625645dfbd-1 | """Filter down documents based on their relevance to the query."""
filtered_docs = []
for doc in documents:
_input = self.get_input(query, doc)
include_doc = self.llm_chain.predict_and_parse(
**_input, callbacks=callbacks
)
if include_doc:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_filter.html |
90e3a0c5dc9b-0 | Source code for langchain.retrievers.document_compressors.cohere_rerank
from __future__ import annotations
from typing import TYPE_CHECKING, Dict, Optional, Sequence
from langchain.callbacks.manager import Callbacks
from langchain.pydantic_v1 import Extra, root_validator
from langchain.retrievers.document_compressors.b... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/cohere_rerank.html |
90e3a0c5dc9b-1 | "Please install it with `pip install cohere`."
)
cohere_api_key = get_from_dict_or_env(
values, "cohere_api_key", "COHERE_API_KEY"
)
client_name = values["user_agent"]
values["client"] = cohere.Client(cohere_api_key, client_name=client_name)
return values
... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/cohere_rerank.html |
0cc4b162dbae-0 | Source code for langchain.retrievers.document_compressors.base
import asyncio
from abc import ABC, abstractmethod
from inspect import signature
from typing import List, Optional, Sequence, Union
from langchain.callbacks.manager import Callbacks
from langchain.pydantic_v1 import BaseModel
from langchain.schema import Ba... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/base.html |
0cc4b162dbae-1 | """Transform a list of documents."""
for _transformer in self.transformers:
if isinstance(_transformer, BaseDocumentCompressor):
accepts_callbacks = (
signature(_transformer.compress_documents).parameters.get(
"callbacks"
... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/base.html |
5eddf846c1e4-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.callbacks.manager import Callbacks
f... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html |
5eddf846c1e4-1 | """LLM wrapper to use for compressing documents."""
get_input: Callable[[str, Document], dict] = default_get_input
"""Callable for constructing the chain input from the query and a Document."""
[docs] def compress_documents(
self,
documents: Sequence[Document],
query: str,
cal... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html |
5eddf846c1e4-2 | prompt: Optional[PromptTemplate] = None,
get_input: Optional[Callable[[str, Document], str]] = None,
llm_chain_kwargs: Optional[dict] = None,
) -> LLMChainExtractor:
"""Initialize from LLM."""
_prompt = prompt if prompt is not None else _get_default_chain_prompt()
_get_input ... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html |
279eb365d026-0 | Source code for langchain.retrievers.document_compressors.embeddings_filter
from typing import Callable, Dict, Optional, Sequence
import numpy as np
from langchain.callbacks.manager import Callbacks
from langchain.document_transformers.embeddings_redundant_filter import (
_get_embeddings_from_stateful_docs,
get... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/embeddings_filter.html |
279eb365d026-1 | if values["k"] is None and values["similarity_threshold"] is None:
raise ValueError("Must specify one of `k` or `similarity_threshold`.")
return values
[docs] def compress_documents(
self,
documents: Sequence[Document],
query: str,
callbacks: Optional[Callbacks] = ... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/embeddings_filter.html |
cf8858655bb0-0 | Source code for langchain.retrievers.self_query.chroma
from typing import Dict, Tuple, Union
from langchain.chains.query_constructor.ir import (
Comparator,
Comparison,
Operation,
Operator,
StructuredQuery,
Visitor,
)
[docs]class ChromaTranslator(Visitor):
"""Translate `Chroma` internal quer... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/chroma.html |
749e62ef222c-0 | Source code for langchain.retrievers.self_query.qdrant
from __future__ import annotations
from typing import TYPE_CHECKING, Tuple
from langchain.chains.query_constructor.ir import (
Comparator,
Comparison,
Operation,
Operator,
StructuredQuery,
Visitor,
)
if TYPE_CHECKING:
from qdrant_client.... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/qdrant.html |
749e62ef222c-1 | try:
from qdrant_client.http import models as rest
except ImportError as e:
raise ImportError(
"Cannot import qdrant_client. Please install with `pip install "
"qdrant-client`."
) from e
self._validate_func(comparison.comparator)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/qdrant.html |
d35b2231bd3e-0 | Source code for langchain.retrievers.self_query.dashvector
"""Logic for converting internal query language to a valid DashVector query."""
from typing import Tuple, Union
from langchain.chains.query_constructor.ir import (
Comparator,
Comparison,
Operation,
Operator,
StructuredQuery,
Visitor,
)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/dashvector.html |
d35b2231bd3e-1 | else:
value = f"'{value}'"
return (
f"{comparison.attribute}{self._format_func(comparison.comparator)}{value}"
)
[docs] def visit_structured_query(
self, structured_query: StructuredQuery
) -> Tuple[str, dict]:
if structured_query.filter is None:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/dashvector.html |
66a0fc0c6533-0 | Source code for langchain.retrievers.self_query.supabase
from typing import Any, Dict, Tuple
from langchain.chains.query_constructor.ir import (
Comparator,
Comparison,
Operation,
Operator,
StructuredQuery,
Visitor,
)
[docs]class SupabaseVectorTranslator(Visitor):
"""Translate Langchain filt... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/supabase.html |
66a0fc0c6533-1 | if isinstance(value, str):
return "->>"
else:
return "->"
[docs] def visit_operation(self, operation: Operation) -> str:
args = [arg.accept(self) for arg in operation.arguments]
return f"{operation.operator.value}({','.join(args)})"
[docs] def visit_comparison(self,... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/supabase.html |
79b3672dee4e-0 | Source code for langchain.retrievers.self_query.timescalevector
from __future__ import annotations
from typing import TYPE_CHECKING, Tuple, Union
from langchain.chains.query_constructor.ir import (
Comparator,
Comparison,
Operation,
Operator,
StructuredQuery,
Visitor,
)
if TYPE_CHECKING:
fro... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/timescalevector.html |
79b3672dee4e-1 | "Cannot import timescale-vector. Please install with `pip install "
"timescale-vector`."
) from e
args = [arg.accept(self) for arg in operation.arguments]
return client.Predicates(*args, operator=self._format_func(operation.operator))
[docs] def visit_comparison(self, comp... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/timescalevector.html |
7cd8f0df84ec-0 | Source code for langchain.retrievers.self_query.opensearch
from typing import Dict, Tuple, Union
from langchain.chains.query_constructor.ir import (
Comparator,
Comparison,
Operation,
Operator,
StructuredQuery,
Visitor,
)
[docs]class OpenSearchTranslator(Visitor):
"""Translate `OpenSearch` i... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/opensearch.html |
7cd8f0df84ec-1 | field = f"metadata.{comparison.attribute}"
if comparison.comparator in [
Comparator.LT,
Comparator.LTE,
Comparator.GT,
Comparator.GTE,
]:
return {
"range": {
field: {self._format_func(comparison.comparator): ... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/opensearch.html |
7a7f0b1bc25e-0 | Source code for langchain.retrievers.self_query.base
"""Retriever that generates and executes structured queries over its own data source."""
import logging
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type, Union
from langchain.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
C... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html |
7a7f0b1bc25e-1 | from langchain.schema.language_model import BaseLanguageModel
from langchain.schema.runnable import Runnable
from langchain.schema.vectorstore import VectorStore
from langchain.vectorstores import (
Chroma,
DashVector,
DeepLake,
ElasticsearchStore,
Milvus,
MyScale,
OpenSearchVectorSearch,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html |
7a7f0b1bc25e-2 | elif vectorstore.__class__ in BUILTIN_TRANSLATORS:
return BUILTIN_TRANSLATORS[vectorstore.__class__]()
else:
raise ValueError(
f"Self query retriever with Vector Store type {vectorstore.__class__}"
f" not supported."
)
[docs]class SelfQueryRetriever(BaseRetriever, Bas... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html |
7a7f0b1bc25e-3 | values["vectorstore"]
)
return values
@property
def llm_chain(self) -> Runnable:
"""llm_chain is legacy name kept for backwards compatibility."""
return self.query_constructor
def _prepare_query(
self, query: str, structured_query: StructuredQuery
) -> Tuple[s... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html |
7a7f0b1bc25e-4 | )
if self.verbose:
logger.info(f"Generated Query: {structured_query}")
new_query, search_kwargs = self._prepare_query(query, structured_query)
docs = self._get_docs_with_query(new_query, search_kwargs)
return docs
async def _aget_relevant_documents(
self, query: s... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html |
7a7f0b1bc25e-5 | if (
"allowed_comparators" not in chain_kwargs
and structured_query_translator.allowed_comparators is not None
):
chain_kwargs[
"allowed_comparators"
] = structured_query_translator.allowed_comparators
if (
"allowed_operators" n... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html |
f653d616933a-0 | Source code for langchain.retrievers.self_query.myscale
import re
from typing import Any, Callable, Dict, Tuple
from langchain.chains.query_constructor.ir import (
Comparator,
Comparison,
Operation,
Operator,
StructuredQuery,
Visitor,
)
def _DEFAULT_COMPOSER(op_name: str) -> Callable:
"""
... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/myscale.html |
f653d616933a-1 | map_dict = {
Operator.AND: _DEFAULT_COMPOSER("AND"),
Operator.OR: _DEFAULT_COMPOSER("OR"),
Operator.NOT: _DEFAULT_COMPOSER("NOT"),
Comparator.EQ: _DEFAULT_COMPOSER("="),
Comparator.GT: _DEFAULT_COMPOSER(">"),
Comparator.GTE: _DEFAULT_COMPOSER(">="),
Comparator.LT:... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/myscale.html |
f653d616933a-2 | # convert timestamp for datetime objects
if isinstance(value, dict) and value.get("type") == "date":
attr = f"parseDateTime32BestEffort({attr})"
value = f"parseDateTime32BestEffort('{value['date']}')"
# string pattern match
if comp is Comparator.LIKE:
value = ... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/myscale.html |
3cc6ed280451-0 | Source code for langchain.retrievers.self_query.deeplake
"""Logic for converting internal query language to a valid Chroma query."""
from typing import Tuple, Union
from langchain.chains.query_constructor.ir import (
Comparator,
Comparison,
Operation,
Operator,
StructuredQuery,
Visitor,
)
COMPAR... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/deeplake.html |
3cc6ed280451-1 | value = COMPARATOR_TO_TQL[func.value] # type: ignore
return f"{value}"
[docs] def visit_operation(self, operation: Operation) -> str:
args = [arg.accept(self) for arg in operation.arguments]
operator = self._format_func(operation.operator)
return "(" + (" " + operator + " ").join(arg... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/deeplake.html |
f467654fbf8c-0 | Source code for langchain.retrievers.self_query.pinecone
from typing import Dict, Tuple, Union
from langchain.chains.query_constructor.ir import (
Comparator,
Comparison,
Operation,
Operator,
StructuredQuery,
Visitor,
)
[docs]class PineconeTranslator(Visitor):
"""Translate `Pinecone` interna... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/pinecone.html |
f467654fbf8c-1 | if structured_query.filter is None:
kwargs = {}
else:
kwargs = {"filter": structured_query.filter.accept(self)}
return structured_query.query, kwargs | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/pinecone.html |
78f55be927d5-0 | Source code for langchain.retrievers.self_query.elasticsearch
from typing import Dict, Tuple, Union
from langchain.chains.query_constructor.ir import (
Comparator,
Comparison,
Operation,
Operator,
StructuredQuery,
Visitor,
)
[docs]class ElasticsearchTranslator(Visitor):
"""Translate `Elastic... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/elasticsearch.html |
78f55be927d5-1 | # the metadata object field
field = f"metadata.{comparison.attribute}"
is_range_comparator = comparison.comparator in [
Comparator.GT,
Comparator.GTE,
Comparator.LT,
Comparator.LTE,
]
if is_range_comparator:
return {
... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/elasticsearch.html |
7481770f3ff7-0 | Source code for langchain.retrievers.self_query.milvus
"""Logic for converting internal query language to a valid Milvus query."""
from typing import Tuple, Union
from langchain.chains.query_constructor.ir import (
Comparator,
Comparison,
Operation,
Operator,
StructuredQuery,
Visitor,
)
COMPARAT... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/milvus.html |
7481770f3ff7-1 | def _format_func(self, func: Union[Operator, Comparator]) -> str:
self._validate_func(func)
value = func.value
if isinstance(func, Comparator):
value = COMPARATOR_TO_BER[func]
return f"{value}"
[docs] def visit_operation(self, operation: Operation) -> str:
if opera... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/milvus.html |
ba55fef2c0b2-0 | Source code for langchain.retrievers.self_query.redis
from __future__ import annotations
from typing import Any, Tuple
from langchain.chains.query_constructor.ir import (
Comparator,
Comparison,
Operation,
Operator,
StructuredQuery,
Visitor,
)
from langchain.vectorstores.redis import Redis
from ... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/redis.html |
ba55fef2c0b2-1 | return RedisText(attribute)
elif attribute in [tf.name for tf in self._schema.tag or []]:
return RedisTag(attribute)
elif attribute in [tf.name for tf in self._schema.numeric or []]:
return RedisNum(attribute)
else:
raise ValueError(
f"Invalid ... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/redis.html |
ba55fef2c0b2-2 | def from_vectorstore(cls, vectorstore: Redis) -> RedisTranslator:
return cls(vectorstore._schema) | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/redis.html |
b2c87bfa1f34-0 | Source code for langchain.retrievers.self_query.weaviate
from datetime import datetime
from typing import Dict, Tuple, Union
from langchain.chains.query_constructor.ir import (
Comparator,
Comparison,
Operation,
Operator,
StructuredQuery,
Visitor,
)
[docs]class WeaviateTranslator(Visitor):
"... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/weaviate.html |
b2c87bfa1f34-1 | value = comparison.value
if isinstance(comparison.value, bool):
value_type = "valueBoolean"
elif isinstance(comparison.value, float):
value_type = "valueNumber"
elif isinstance(comparison.value, int):
value_type = "valueInt"
elif (
isinstan... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/weaviate.html |
e2f90608eb61-0 | Source code for langchain.retrievers.self_query.vectara
from typing import Tuple, Union
from langchain.chains.query_constructor.ir import (
Comparator,
Comparison,
Operation,
Operator,
StructuredQuery,
Visitor,
)
[docs]def process_value(value: Union[int, float, str]) -> str:
"""Convert a val... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/vectara.html |
e2f90608eb61-1 | return "( " + operator.join(args) + " )"
[docs] def visit_comparison(self, comparison: Comparison) -> str:
comparator = self._format_func(comparison.comparator)
processed_value = process_value(comparison.value)
attribute = comparison.attribute
return (
"( " + "doc." + attr... | lang/api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/vectara.html |
0e4a5073f508-0 | Source code for langchain.runnables.openai_functions
from operator import itemgetter
from typing import Any, Callable, List, Mapping, Optional, Union
from typing_extensions import TypedDict
from langchain.output_parsers.openai_functions import JsonOutputFunctionsParser
from langchain.schema.messages import BaseMessage
... | lang/api.python.langchain.com/en/latest/_modules/langchain/runnables/openai_functions.html |
36e0516aa8bc-0 | Source code for langchain.runnables.hub
from typing import Any, Optional
from langchain.schema.runnable.base import Input, Output, RunnableBindingBase
[docs]class HubRunnable(RunnableBindingBase[Input, Output]):
"""
An instance of a runnable stored in the LangChain Hub.
"""
owner_repo_commit: str
de... | lang/api.python.langchain.com/en/latest/_modules/langchain/runnables/hub.html |
27cbd746a3d9-0 | Source code for langchain.chains.llm
"""Chain that just formats a prompt and calls an LLM."""
from __future__ import annotations
import warnings
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union, cast
from langchain.callbacks.manager import (
AsyncCallbackManager,
AsyncCallbackManagerForChain... | lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
27cbd746a3d9-1 | """
[docs] @classmethod
def is_lc_serializable(self) -> bool:
return True
prompt: BasePromptTemplate
"""Prompt object to use."""
llm: Union[
Runnable[LanguageModelInput, str], Runnable[LanguageModelInput, BaseMessage]
]
"""Language model to call."""
output_key: str = "text... | lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
27cbd746a3d9-2 | response = self.generate([inputs], run_manager=run_manager)
return self.create_outputs(response)[0]
[docs] def generate(
self,
input_list: List[Dict[str, Any]],
run_manager: Optional[CallbackManagerForChainRun] = None,
) -> LLMResult:
"""Generate LLM result from inputs."""... | lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
27cbd746a3d9-3 | prompts,
stop,
callbacks=callbacks,
**self.llm_kwargs,
)
else:
results = await self.llm.bind(stop=stop, **self.llm_kwargs).abatch(
cast(List, prompts), {"callbacks": callbacks}
)
generations: List[Lis... | lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
27cbd746a3d9-4 | )
prompts.append(prompt)
return prompts, stop
[docs] async def aprep_prompts(
self,
input_list: List[Dict[str, Any]],
run_manager: Optional[AsyncCallbackManagerForChainRun] = None,
) -> Tuple[List[PromptValue], Optional[List[str]]]:
"""Prepare prompts from inpu... | lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
27cbd746a3d9-5 | {"input_list": input_list},
)
try:
response = self.generate(input_list, run_manager=run_manager)
except BaseException as e:
run_manager.on_chain_error(e)
raise e
outputs = self.create_outputs(response)
run_manager.on_chain_end({"outputs": outpu... | lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
27cbd746a3d9-6 | return result
async def _acall(
self,
inputs: Dict[str, Any],
run_manager: Optional[AsyncCallbackManagerForChainRun] = None,
) -> Dict[str, str]:
response = await self.agenerate([inputs], run_manager=run_manager)
return self.create_outputs(response)[0]
[docs] def predi... | lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
27cbd746a3d9-7 | warnings.warn(
"The predict_and_parse method is deprecated, "
"instead pass an output parser directly to LLMChain."
)
result = self.predict(callbacks=callbacks, **kwargs)
if self.prompt.output_parser is not None:
return self.prompt.output_parser.parse(result)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
27cbd746a3d9-8 | self.prompt.output_parser.parse(res[self.output_key])
for res in generation
]
else:
return generation
[docs] async def aapply_and_parse(
self, input_list: List[Dict[str, Any]], callbacks: Callbacks = None
) -> Sequence[Union[str, List[str], Dict[str, str]]]... | lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
27cbd746a3d9-9 | else:
raise ValueError(
f"Unable to extract BaseLanguageModel from llm_like object of type "
f"{type(llm_like)}"
) | lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
01e09df3201d-0 | Source code for langchain.chains.example_generator
from typing import List
from langchain.chains.llm import LLMChain
from langchain.prompts.few_shot import FewShotPromptTemplate
from langchain.prompts.prompt import PromptTemplate
from langchain.schema.language_model import BaseLanguageModel
TEST_GEN_TEMPLATE_SUFFIX = "... | lang/api.python.langchain.com/en/latest/_modules/langchain/chains/example_generator.html |
fa7c749cec59-0 | Source code for langchain.chains.llm_requests
"""Chain that hits a URL and then uses an LLM to parse results."""
from __future__ import annotations
from typing import Any, Dict, List, Optional
from langchain.callbacks.manager import CallbackManagerForChainRun
from langchain.chains import LLMChain
from langchain.chains.... | lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm_requests.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.