id
stringlengths
14
15
text
stringlengths
44
2.47k
source
stringlengths
61
181
7c93fefe504b-0
Source code for langchain.retrievers.kendra import re from abc import ABC, abstractmethod from typing import Any, Callable, Dict, List, Literal, Optional, Sequence, Union from langchain.callbacks.manager import CallbackManagerForRetrieverRun from langchain.docstore.document import Document from langchain.pydantic_v1 im...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html
7c93fefe504b-1
"""Information that highlights the key words in the excerpt.""" BeginOffset: int """The zero-based location in the excerpt where the highlight starts.""" EndOffset: int """The zero-based location in the excerpt where the highlight ends.""" TopAnswer: Optional[bool] """Indicates whether the resul...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html
7c93fefe504b-2
return self.Value.TextWithHighlightsValue.Text # Unexpected keyword argument "extra" for "__init_subclass__" of "object" [docs]class DocumentAttributeValue(BaseModel, extra=Extra.allow): # type: ignore[call-arg] """Value of a document attribute.""" DateValue: Optional[str] """The date expressed as an ISO 8...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html
7c93fefe504b-3
Id: Optional[str] """The ID of the relevant result item.""" DocumentId: Optional[str] """The document ID.""" DocumentURI: Optional[str] """The document URI.""" DocumentAttributes: Optional[List[DocumentAttribute]] = [] """The document attributes.""" [docs] @abstractmethod def get_titl...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html
7c93fefe504b-4
[docs]class QueryResultItem(ResultItem): """Query API result item.""" DocumentTitle: TextWithHighLights """The document title.""" FeedbackToken: Optional[str] """Identifies a particular result from a particular query.""" Format: Optional[str] """ If the Type is ANSWER, then format is eit...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html
7c93fefe504b-5
[docs]class RetrieveResultItem(ResultItem): """Retrieve API result item.""" DocumentTitle: Optional[str] """The document title.""" Content: Optional[str] """The content of the item.""" [docs] def get_title(self) -> str: return self.DocumentTitle or "" [docs] def get_excerpt(self) -> st...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html
7c93fefe504b-6
Fallsback to AWS_DEFAULT_REGION env variable or region specified in ~/.aws/config. credentials_profile_name: The name of the profile in the ~/.aws/credentials or ~/.aws/config files, which has either access keys or role information specified. If not specified, the default cre...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html
7c93fefe504b-7
return value @root_validator(pre=True) def create_client(cls, values: Dict[str, Any]) -> Dict[str, Any]: if values.get("client") is not None: return values try: import boto3 if values.get("credentials_profile_name"): session = boto3.Session(pro...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html
7c93fefe504b-8
# Retrieve API returned 0 results, fall back to Query API response = self.client.query(**kendra_kwargs) q_result = QueryResult.parse_obj(response) return q_result.ResultItems def _get_top_k_docs(self, result_items: Sequence[ResultItem]) -> List[Document]: top_docs = [ ite...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html
4957a2955e7c-0
Source code for langchain.retrievers.wikipedia from typing import List from langchain.callbacks.manager import CallbackManagerForRetrieverRun from langchain.schema import BaseRetriever, Document from langchain.utilities.wikipedia import WikipediaAPIWrapper [docs]class WikipediaRetriever(BaseRetriever, WikipediaAPIWrapp...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/wikipedia.html
fff3d795c7d3-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...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/deeplake.html
fff3d795c7d3-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...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/deeplake.html
a2684c0dc1c7-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...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/timescalevector.html
a2684c0dc1c7-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...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/timescalevector.html
9d5058cd9d96-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, ) ...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/dashvector.html
9d5058cd9d96-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: ...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/dashvector.html
6694568e605b-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....
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/qdrant.html
6694568e605b-1
"Cannot import qdrant_client. Please install with `pip install " "qdrant-client`." ) from e self._validate_func(comparison.comparator) attribute = self.metadata_key + "." + comparison.attribute if comparison.comparator == Comparator.EQ: return rest.FieldCo...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/qdrant.html
d393c03572d6-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...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/milvus.html
d393c03572d6-1
value = COMPARATOR_TO_BER[func] return f"{value}" [docs] def visit_operation(self, operation: Operation) -> str: if operation.operator in UNARY_OPERATORS and len(operation.arguments) == 1: operator = self._format_func(operation.operator) return operator + "(" + operation.argum...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/milvus.html
d2b11cb59e83-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...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/supabase.html
d2b11cb59e83-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,...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/supabase.html
5f322ddc3d2c-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 langchain.callbacks.manager import CallbackManagerForRetrieverRun from langchain.chains import LLMChain from langcha...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html
5f322ddc3d2c-1
Chroma, DashVector, DeepLake, ElasticsearchStore, Milvus, MyScale, OpenSearchVectorSearch, Pinecone, Qdrant, Redis, SupabaseVectorStore, TimescaleVector, Vectara, VectorStore, Weaviate, ) def _get_builtin_translator(vectorstore: VectorStore) -> Visitor: """Get...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html
5f322ddc3d2c-2
f"Self query retriever with Vector Store type {vectorstore.__class__}" f" not supported." ) [docs]class SelfQueryRetriever(BaseRetriever, BaseModel): """Retriever that uses a vector store and an LLM to generate the vector store queries.""" vectorstore: VectorStore """The underlying v...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html
5f322ddc3d2c-3
Returns: List of relevant documents """ inputs = self.llm_chain.prep_inputs({"query": query}) structured_query = cast( StructuredQuery, self.llm_chain.predict_and_parse( callbacks=run_manager.get_child(), **inputs ), ) ...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html
5f322ddc3d2c-4
chain_kwargs[ "allowed_operators" ] = structured_query_translator.allowed_operators llm_chain = load_query_constructor_chain( llm, document_contents, metadata_field_info, enable_limit=enable_limit, **chain_kwargs, ) ...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html
248efdb28577-0
Source code for langchain.retrievers.self_query.weaviate from typing import Dict, Tuple, Union from langchain.chains.query_constructor.ir import ( Comparator, Comparison, Operation, Operator, StructuredQuery, Visitor, ) [docs]class WeaviateTranslator(Visitor): """Translate `Weaviate` interna...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/weaviate.html
390129541e5a-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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/redis.html
390129541e5a-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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/redis.html
390129541e5a-2
def from_vectorstore(cls, vectorstore: Redis) -> RedisTranslator: return cls(vectorstore._schema)
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/redis.html
86930716d637-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: if isinstance(va...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/vectara.html
86930716d637-1
[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." + attribute + " " + comparator + " " + processe...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/vectara.html
725ff0fbaf30-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...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/elasticsearch.html
725ff0fbaf30-1
# ElasticsearchStore filters require to target # the metadata object field field = f"metadata.{comparison.attribute}" is_range_comparator = comparison.comparator in [ Comparator.GT, Comparator.GTE, Comparator.LT, Comparator.LTE, ] i...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/elasticsearch.html
ec65ea32aafd-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...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/pinecone.html
afc5050cfcbc-0
Source code for langchain.retrievers.self_query.myscale import datetime 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) -> Call...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/myscale.html
afc5050cfcbc-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:...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/myscale.html
afc5050cfcbc-2
# convert timestamp for datetime objects if type(value) is datetime.date: attr = f"parseDateTime32BestEffort({attr})" value = f"parseDateTime32BestEffort('{value.strftime('%Y-%m-%d')}')" # string pattern match if comp is Comparator.LIKE: value = f"'%{value[1:-...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/myscale.html
71c031476986-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...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/opensearch.html
71c031476986-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): ...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/opensearch.html
e74c2c75fa38-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...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/chroma.html
856162346c8b-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...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/cohere_rerank.html
856162346c8b-1
raise ImportError( "Could not import cohere python package. " "Please install it with `pip install cohere`." ) return values [docs] def compress_documents( self, documents: Sequence[Document], query: str, callbacks: Optional[Callback...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/cohere_rerank.html
ed696cd01a0e-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...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_filter.html
ed696cd01a0e-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: ...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_filter.html
19eea034f859-0
Source code for langchain.retrievers.document_compressors.base 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 BaseDocumentTrans...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/base.html
19eea034f859-1
accepts_callbacks = ( signature(_transformer.compress_documents).parameters.get( "callbacks" ) is not None ) if accepts_callbacks: documents = _transformer.compress_documents( ...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/base.html
59ae9c35ced7-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...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html
59ae9c35ced7-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...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html
59ae9c35ced7-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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html
044a3cb2e049-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...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/embeddings_filter.html
044a3cb2e049-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] = ...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/embeddings_filter.html
95a530187ada-0
Source code for langchain.document_transformers.doctran_text_qa from typing import Any, Optional, Sequence from langchain.schema import BaseDocumentTransformer, Document from langchain.utils import get_from_env [docs]class DoctranQATransformer(BaseDocumentTransformer): """Extract QA from text documents using doctra...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/doctran_text_qa.html
95a530187ada-1
from doctran import Doctran doctran = Doctran( openai_api_key=self.openai_api_key, openai_model=self.openai_api_model ) except ImportError: raise ImportError( "Install doctran to use this parser. (pip install doctran)" ) for...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/doctran_text_qa.html
a8a7e8aae5d0-0
Source code for langchain.document_transformers.embeddings_redundant_filter """Transform documents""" from typing import Any, Callable, List, Sequence import numpy as np from langchain.pydantic_v1 import BaseModel, Field from langchain.schema import BaseDocumentTransformer, Document from langchain.schema.embeddings imp...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/embeddings_redundant_filter.html
a8a7e8aae5d0-1
redundant_stacked = np.column_stack(redundant) redundant_sorted = np.argsort(similarity[redundant])[::-1] included_idxs = set(range(len(embedded_documents))) for first_idx, second_idx in redundant_stacked[redundant_sorted]: if first_idx in included_idxs and second_idx in included_idxs: #...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/embeddings_redundant_filter.html
a8a7e8aae5d0-2
) closest_indices = [] # Loop through the number of clusters you have for i in range(num_clusters): # Get the list of distances from that particular cluster center distances = np.linalg.norm( embedded_documents - kmeans.cluster_centers_[i], axis=1 ) # Find the ind...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/embeddings_redundant_filter.html
a8a7e8aae5d0-3
) -> Sequence[Document]: """Filter down documents.""" stateful_documents = get_stateful_documents(documents) embedded_documents = _get_embeddings_from_stateful_docs( self.embeddings, stateful_documents ) included_idxs = _filter_similar_embeddings( embedded...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/embeddings_redundant_filter.html
a8a7e8aae5d0-4
""" By default duplicated results are skipped and replaced by the next closest vector in the cluster. If remove_duplicates is true no replacement will be done: This could dramatically reduce results when there is a lot of overlap between clusters. """ class Config: """Configuration for thi...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/embeddings_redundant_filter.html
69f212dd083b-0
Source code for langchain.document_transformers.beautiful_soup_transformer from typing import Any, List, Sequence from langchain.schema import BaseDocumentTransformer, Document [docs]class BeautifulSoupTransformer(BaseDocumentTransformer): """Transform HTML content by extracting specific tags and removing unwanted ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/beautiful_soup_transformer.html
69f212dd083b-1
Returns: A sequence of Document objects with transformed content. """ for doc in documents: cleaned_content = doc.page_content cleaned_content = self.remove_unwanted_tags(cleaned_content, unwanted_tags) cleaned_content = self.extract_tags(cleaned_content, ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/beautiful_soup_transformer.html
69f212dd083b-2
href = element.get("href") if href: text_parts.append(f"{element.get_text()} ({href})") else: text_parts.append(element.get_text()) else: text_parts.append(element.get_text()) return " ".j...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/beautiful_soup_transformer.html
15c48fbe9cdc-0
Source code for langchain.document_transformers.nuclia_text_transform import asyncio import json import uuid from typing import Any, Sequence from langchain.schema.document import BaseDocumentTransformer, Document from langchain.tools.nuclia.tool import NucliaUnderstandingAPI [docs]class NucliaTextTransformer(BaseDocum...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/nuclia_text_transform.html
215362d89fdf-0
Source code for langchain.document_transformers.openai_functions """Document transformers that use OpenAI Functions models""" from typing import Any, Dict, Optional, Sequence, Type, Union from langchain.chains.llm import LLMChain from langchain.chains.openai_functions import create_tagging_chain from langchain.prompts ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/openai_functions.html
215362d89fdf-1
original_documents = [ Document(page_content="Review of The Bee Movie\nBy Roger Ebert\n\This is the greatest movie ever made. 4 out of 5 stars."), Document(page_content="Review of The Godfather\nBy Anonymous\n\nThis movie was super boring. 1 out of 5 stars.", metadata={"reliable"...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/openai_functions.html
215362d89fdf-2
"""Create a DocumentTransformer that uses an OpenAI function chain to automatically tag documents with metadata based on their content and an input schema. Args: metadata_schema: Either a dictionary or pydantic.BaseModel class. If a dictionary is passed in, it's assumed to already be a v...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/openai_functions.html
215362d89fdf-3
original_documents = [ Document(page_content="Review of The Bee Movie\nBy Roger Ebert\n\This is the greatest movie ever made. 4 out of 5 stars."), Document(page_content="Review of The Godfather\nBy Anonymous\n\nThis movie was super boring. 1 out of 5 stars.", metadata={"reliable"...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/openai_functions.html
38d5d6db29b8-0
Source code for langchain.document_transformers.doctran_text_extract from typing import Any, List, Optional, Sequence from langchain.schema import BaseDocumentTransformer, Document from langchain.utils import get_from_env [docs]class DoctranPropertyExtractor(BaseDocumentTransformer): """Extract properties from text...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/doctran_text_extract.html
38d5d6db29b8-1
transformed_document = await qa_transformer.atransform_documents(documents) """ # noqa: E501 [docs] def __init__( self, properties: List[dict], openai_api_key: Optional[str] = None, openai_api_model: Optional[str] = None, ) -> None: self.properties = properties ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/doctran_text_extract.html
2a7c4a399224-0
Source code for langchain.document_transformers.html2text from typing import Any, Sequence from langchain.schema import BaseDocumentTransformer, Document [docs]class Html2TextTransformer(BaseDocumentTransformer): """Replace occurrences of a particular search pattern with a replacement string Arguments: ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/html2text.html
c4e80ea3a62c-0
Source code for langchain.document_transformers.doctran_text_translate from typing import Any, Optional, Sequence from langchain.schema import BaseDocumentTransformer, Document from langchain.utils import get_from_env [docs]class DoctranTextTranslator(BaseDocumentTransformer): """Translate text documents using doct...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/doctran_text_translate.html
c4e80ea3a62c-1
"""Translates text documents using doctran.""" try: from doctran import Doctran doctran = Doctran( openai_api_key=self.openai_api_key, openai_model=self.openai_api_model ) except ImportError: raise ImportError( "Install doct...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/doctran_text_translate.html
8b6a5ca19c2a-0
Source code for langchain.document_transformers.long_context_reorder """Reorder documents""" from typing import Any, List, Sequence from langchain.pydantic_v1 import BaseModel from langchain.schema import BaseDocumentTransformer, Document def _litm_reordering(documents: List[Document]) -> List[Document]: """Los in ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/long_context_reorder.html
bea1d7248c75-0
Source code for langchain.storage.encoder_backed from typing import ( Any, Callable, Iterator, List, Optional, Sequence, Tuple, TypeVar, Union, ) from langchain.schema import BaseStore K = TypeVar("K") V = TypeVar("V") [docs]class EncoderBackedStore(BaseStore[K, V]): """Wraps a s...
https://api.python.langchain.com/en/latest/_modules/langchain/storage/encoder_backed.html
bea1d7248c75-1
value_serializer: Callable[[V], bytes], value_deserializer: Callable[[Any], V], ) -> None: """Initialize an EncodedStore.""" self.store = store self.key_encoder = key_encoder self.value_serializer = value_serializer self.value_deserializer = value_deserializer [docs] ...
https://api.python.langchain.com/en/latest/_modules/langchain/storage/encoder_backed.html
9e08d33fdadd-0
Source code for langchain.storage.in_memory """In memory store that is not thread safe and has no eviction policy. This is a simple implementation of the BaseStore using a dictionary that is useful primarily for unit testing purposes. """ from typing import Any, Dict, Iterator, List, Optional, Sequence, Tuple from lang...
https://api.python.langchain.com/en/latest/_modules/langchain/storage/in_memory.html
9e08d33fdadd-1
""" return [self.store.get(key) for key in keys] [docs] def mset(self, key_value_pairs: Sequence[Tuple[str, Any]]) -> None: """Set the values for the given keys. Args: key_value_pairs (Sequence[Tuple[str, V]]): A sequence of key-value pairs. Returns: None ...
https://api.python.langchain.com/en/latest/_modules/langchain/storage/in_memory.html
7f43ac4fd081-0
Source code for langchain.storage.file_system import re from pathlib import Path from typing import Iterator, List, Optional, Sequence, Tuple, Union from langchain.schema import BaseStore from langchain.storage.exceptions import InvalidKeyException [docs]class LocalFileStore(BaseStore[str, bytes]): """BaseStore int...
https://api.python.langchain.com/en/latest/_modules/langchain/storage/file_system.html
7f43ac4fd081-1
Returns: Path: The full path for the given key. """ if not re.match(r"^[a-zA-Z0-9_.\-/]+$", key): raise InvalidKeyException(f"Invalid characters in key: {key}") return self.root_path / key [docs] def mget(self, keys: Sequence[str]) -> List[Optional[bytes]]: """...
https://api.python.langchain.com/en/latest/_modules/langchain/storage/file_system.html
7f43ac4fd081-2
for key in keys: full_path = self._get_full_path(key) if full_path.exists(): full_path.unlink() [docs] def yield_keys(self, prefix: Optional[str] = None) -> Iterator[str]: """Get an iterator over keys that match the given prefix. Args: prefix (Optio...
https://api.python.langchain.com/en/latest/_modules/langchain/storage/file_system.html
21ac5fd37a25-0
Source code for langchain.storage.exceptions from langchain.schema import LangChainException [docs]class InvalidKeyException(LangChainException): """Raised when a key is invalid; e.g., uses incorrect characters."""
https://api.python.langchain.com/en/latest/_modules/langchain/storage/exceptions.html
0d42273d56a2-0
Source code for langchain.storage.redis from typing import Any, Iterator, List, Optional, Sequence, Tuple, cast from langchain.schema import BaseStore from langchain.utilities.redis import get_client [docs]class RedisStore(BaseStore[str, bytes]): """BaseStore implementation using Redis as the underlying store. ...
https://api.python.langchain.com/en/latest/_modules/langchain/storage/redis.html
0d42273d56a2-1
ttl: time to expire keys in seconds if provided, if None keys will never expire namespace: if provided, all keys will be prefixed with this namespace """ try: from redis import Redis except ImportError as e: raise ImportError( ...
https://api.python.langchain.com/en/latest/_modules/langchain/storage/redis.html
0d42273d56a2-2
"""Get the values associated with the given keys.""" return cast( List[Optional[bytes]], self.client.mget([self._get_prefixed_key(key) for key in keys]), ) [docs] def mset(self, key_value_pairs: Sequence[Tuple[str, bytes]]) -> None: """Set the given key-value pairs."""...
https://api.python.langchain.com/en/latest/_modules/langchain/storage/redis.html
44dd9fd2d675-0
Source code for langchain.prompts.prompt """Prompt schema definition.""" from __future__ import annotations from pathlib import Path from string import Formatter from typing import Any, Dict, List, Optional, Union from langchain.prompts.base import ( DEFAULT_FORMATTER_MAPPING, StringPromptTemplate, _get_jin...
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html
44dd9fd2d675-1
def __add__(self, other: Any) -> PromptTemplate: """Override the + operator to allow for combining prompt templates.""" # Allow for easy combining if isinstance(other, PromptTemplate): if self.template_format != "f-string": raise ValueError( "Addin...
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html
44dd9fd2d675-2
Args: kwargs: Any arguments to be passed to the prompt template. Returns: A formatted string. Example: .. code-block:: python prompt.format(variable1="foo") """ kwargs = self._merge_partial_and_user_variables(**kwargs) return DE...
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html
44dd9fd2d675-3
Returns: The final prompt generated. """ template = example_separator.join([prefix, *examples, suffix]) return cls(input_variables=input_variables, template=template, **kwargs) [docs] @classmethod def from_file( cls, template_file: Union[str, Path], input_variables: Li...
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html
44dd9fd2d675-4
`"foo {variable2}"`. Returns: The prompt template loaded from the template. """ if template_format == "jinja2": # Get the variables for the template input_variables = _get_jinja2_variables_from_template(template) elif template_format == "f-string": ...
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html
92393eeb1755-0
Source code for langchain.prompts.few_shot_with_templates """Prompt template that contains few shot examples.""" from typing import Any, Dict, List, Optional from langchain.prompts.base import DEFAULT_FORMATTER_MAPPING, StringPromptTemplate from langchain.prompts.example_selector.base import BaseExampleSelector from la...
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html
92393eeb1755-1
examples = values.get("examples", None) example_selector = values.get("example_selector", None) if examples and example_selector: raise ValueError( "Only one of 'examples' and 'example_selector' should be provided" ) if examples is None and example_selecto...
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html
92393eeb1755-2
Args: kwargs: Any arguments to be passed to the prompt template. Returns: A formatted string. Example: .. code-block:: python prompt.format(variable1="foo") """ kwargs = self._merge_partial_and_user_variables(**kwargs) # Get the example...
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html
92393eeb1755-3
"""Return a dictionary of the prompt.""" if self.example_selector: raise ValueError("Saving an example selector is not currently supported") return super().dict(**kwargs)
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html
4e6754f2de47-0
Source code for langchain.prompts.chat """Chat prompt template.""" from __future__ import annotations from abc import ABC, abstractmethod from pathlib import Path from typing import ( Any, Callable, Dict, List, Sequence, Set, Tuple, Type, TypeVar, Union, overload, ) from lang...
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html
4e6754f2de47-1
""" def __add__(self, other: Any) -> ChatPromptTemplate: """Combine two prompt templates. Args: other: Another prompt template. Returns: Combined prompt template. """ prompt = ChatPromptTemplate(messages=[self]) return prompt + other [docs]clas...
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html
4e6754f2de47-2
"""Base class for message prompt templates that use a string prompt template.""" prompt: StringPromptTemplate """String prompt template.""" additional_kwargs: dict = Field(default_factory=dict) """Additional keyword arguments to pass to the prompt template.""" [docs] @classmethod def from_templat...
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html
4e6754f2de47-3
Args: **kwargs: Keyword arguments to use for formatting. Returns: Formatted message. """ [docs] def format_messages(self, **kwargs: Any) -> List[BaseMessage]: """Format messages from kwargs. Args: **kwargs: Keyword arguments to use for formatting. ...
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html
4e6754f2de47-4
[docs]class AIMessagePromptTemplate(BaseStringMessagePromptTemplate): """AI message prompt template. This is a message sent from the AI.""" [docs] def format(self, **kwargs: Any) -> BaseMessage: """Format the prompt template. Args: **kwargs: Keyword arguments to use for formatting. ...
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html
4e6754f2de47-5
For use in external schemas.""" messages: Sequence[AnyMessage] [docs]class BaseChatPromptTemplate(BasePromptTemplate, ABC): """Base class for chat prompt templates.""" @property def lc_attributes(self) -> Dict: """ Return a list of attribute names that should be included in the s...
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html