id
stringlengths
14
16
text
stringlengths
31
2.41k
source
stringlengths
54
121
f1cd9c5ba011-7
lines = text.split("\n") # Final output lines_with_metadata: List[LineType] = [] # Content and metadata of the chunk currently being processed current_content: List[str] = [] current_metadata: Dict[str, str] = {} # Keep track of the nested header structure # heade...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
f1cd9c5ba011-8
# Push the current header to the stack header: HeaderType = { "level": current_header_level, "name": name, "data": stripped_line[len(sep) :].strip(), } header_stack...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
f1cd9c5ba011-9
class Tokenizer: chunk_overlap: int tokens_per_chunk: int decode: Callable[[list[int]], str] encode: Callable[[str], List[int]] [docs]def split_text_on_tokens(*, text: str, tokenizer: Tokenizer) -> List[str]: """Split incoming text and return chunks.""" splits: List[str] = [] input_ids = tok...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
f1cd9c5ba011-10
) if model_name is not None: enc = tiktoken.encoding_for_model(model_name) else: enc = tiktoken.get_encoding(encoding_name) self._tokenizer = enc self._allowed_special = allowed_special self._disallowed_special = disallowed_special [docs] def split_text...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
f1cd9c5ba011-11
) self.model_name = model_name self._model = SentenceTransformer(self.model_name) self.tokenizer = self._model.tokenizer self._initialize_chunk_configuration(tokens_per_chunk=tokens_per_chunk) def _initialize_chunk_configuration( self, *, tokens_per_chunk: Optional[int] )...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
f1cd9c5ba011-12
token_ids_with_start_and_end_token_ids = self.tokenizer.encode( text, max_length=self._max_length_equal_32_bit_integer, truncation="do_not_truncate", ) return token_ids_with_start_and_end_token_ids [docs]class Language(str, Enum): CPP = "cpp" GO = "go" JAV...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
f1cd9c5ba011-13
for i, _s in enumerate(separators): if _s == "": separator = _s break if re.search(_s, text): separator = _s new_separators = separators[i + 1 :] break splits = _split_text_with_regex(text, separator, self._k...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
f1cd9c5ba011-14
if language == Language.CPP: return [ # Split along class definitions "\nclass ", # Split along function definitions "\nvoid ", "\nint ", "\nfloat ", "\ndouble ", # Split along con...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
f1cd9c5ba011-15
"\nfunction ", "\nconst ", "\nlet ", "\nvar ", "\nclass ", # Split along control flow statements "\nif ", "\nfor ", "\nwhile ", "\nswitch ", "\ncase ", ...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
f1cd9c5ba011-16
# Now split by the normal type of lines "\n\n", "\n", " ", "", ] elif language == Language.RST: return [ # Split along section titles "\n=+\n", "\n-+\n", "\n\*+...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
f1cd9c5ba011-17
"\nobject ", # Split along method definitions "\ndef ", "\nval ", "\nvar ", # Split along control flow statements "\nif ", "\nfor ", "\nwhile ", "\nmatch ", "\n...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
f1cd9c5ba011-18
"\n", " ", "", ] elif language == Language.LATEX: return [ # First, try to split along Latex sections "\n\\\chapter{", "\n\\\section{", "\n\\\subsection{", "\n\\\subsubsection{...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
f1cd9c5ba011-19
return [ # Split along compiler informations definitions "\npragma ", "\nusing ", # Split along contract definitions "\ncontract ", "\ninterface ", "\nlibrary ", # Split along method definitio...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
f1cd9c5ba011-20
splits = self._tokenizer(text) return self._merge_splits(splits, self._separator) [docs]class SpacyTextSplitter(TextSplitter): """Implementation of splitting text that looks at sentences using Spacy.""" def __init__( self, separator: str = "\n\n", pipeline: str = "en_core_web_sm", **kwargs: Any ...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
f1cd9c5ba011-21
separators = self.get_separators_for_language(Language.MARKDOWN) super().__init__(separators=separators, **kwargs) [docs]class LatexTextSplitter(RecursiveCharacterTextSplitter): """Attempts to split the text along Latex-formatted layout elements.""" def __init__(self, **kwargs: Any) -> None: """...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
f89ccc5b6942-0
Source code for langchain.schema """Common schema objects.""" from __future__ import annotations from abc import ABC, abstractmethod from dataclasses import dataclass from typing import ( Any, Dict, Generic, List, NamedTuple, Optional, Sequence, TypeVar, Union, ) from uuid import UUI...
https://api.python.langchain.com/en/latest/_modules/langchain/schema.html
f89ccc5b6942-1
"""Agent's return value.""" return_values: dict log: str [docs]class Generation(Serializable): """Output of a single generation.""" text: str """Generated text output.""" generation_info: Optional[Dict[str, Any]] = None """Raw generation info response from the provider""" """May include ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema.html
f89ccc5b6942-2
"""Type of the message, used for serialization.""" return "system" [docs]class FunctionMessage(BaseMessage): name: str @property def type(self) -> str: """Type of the message, used for serialization.""" return "function" [docs]class ChatMessage(BaseMessage): """Type of message wi...
https://api.python.langchain.com/en/latest/_modules/langchain/schema.html
f89ccc5b6942-3
Returns: List of messages (BaseMessages). """ return [_message_from_dict(m) for m in messages] [docs]class ChatGeneration(Generation): """Output of a single generation.""" text = "" message: BaseMessage @root_validator def set_text(cls, values: Dict[str, Any]) -> Dict[str, Any]: ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema.html
f89ccc5b6942-4
llm_output=self.llm_output, ) ) else: if self.llm_output is not None: llm_output = self.llm_output.copy() llm_output["token_usage"] = dict() else: llm_output = None ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema.html
f89ccc5b6942-5
"""Save the context of this model run to memory.""" [docs] @abstractmethod def clear(self) -> None: """Clear memory contents.""" [docs]class BaseChatMessageHistory(ABC): """Base interface for chat message history See `ChatMessageHistory` for default implementation. """ """ Example: ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema.html
f89ccc5b6942-6
raise NotImplementedError [docs] @abstractmethod def clear(self) -> None: """Remove all messages from the store""" [docs]class Document(Serializable): """Interface for interacting with a document.""" page_content: str metadata: dict = Field(default_factory=dict) [docs]class BaseRetriever(ABC)...
https://api.python.langchain.com/en/latest/_modules/langchain/schema.html
f89ccc5b6942-7
"""Parse the output of an LLM call. A method which takes in a string (assumed output of a language model ) and parses it into some structure. Args: text: output of language model Returns: structured output """ [docs] def parse_with_prompt(self, completi...
https://api.python.langchain.com/en/latest/_modules/langchain/schema.html
f89ccc5b6942-8
@property def _type(self) -> str: return "default" [docs] def parse(self, text: str) -> str: return text [docs]class OutputParserException(ValueError): """Exception that output parsers should raise to signify a parsing error. This exists to differentiate parsing errors from other code or ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema.html
649767acfe47-0
Source code for langchain.document_transformers """Transform documents""" from typing import Any, Callable, List, Sequence import numpy as np from pydantic import BaseModel, Field from langchain.embeddings.base import Embeddings from langchain.math_utils import cosine_similarity from langchain.schema import BaseDocumen...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers.html
649767acfe47-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.html
649767acfe47-2
arbitrary_types_allowed = True [docs] def transform_documents( self, documents: Sequence[Document], **kwargs: Any ) -> Sequence[Document]: """Filter down documents.""" stateful_documents = get_stateful_documents(documents) embedded_documents = _get_embeddings_from_stateful_docs( ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers.html
af5ade709a82-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://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html
af5ade709a82-1
Defaults to 'vector_table'. metric (str) : Metric to compute distance, supported are ('angular', 'euclidean', 'manhattan', 'hamming', 'dot'). Defaults to 'angular'. https://github.com/spotify/annoy/blob/main/src/annoymodule.cc#L149-L169 ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html
af5ade709a82-2
return getattr(self, item) class Config: env_file = ".env" env_prefix = "clickhouse_" env_file_encoding = "utf-8" [docs]class Clickhouse(VectorStore): """Wrapper around ClickHouse vector database You need a `clickhouse-connect` python package, and a valid account to connect to Cl...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html
af5ade709a82-3
assert self.config assert self.config.host and self.config.port assert ( self.config.column_map and self.config.database and self.config.table and self.config.metric ) for k in ["id", "embedding", "document", "metadata", "uuid"]: ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html
af5ade709a82-4
""" self.dim = dim self.BS = "\\" self.must_escape = ("\\", "'") self.embedding_function = embedding self.dist_order = "ASC" # Only support ConsingDistance and L2Distance # Create a connection to clickhouse self.client = get_client( host=self.config.h...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html
af5ade709a82-5
[docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, batch_size: int = 32, ids: Optional[Iterable[str]] = None, **kwargs: Any, ) -> List[str]: """Insert more texts through the embeddings and add to the VectorStore. ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html
af5ade709a82-6
transac.append(v) if len(transac) == batch_size: if t: t.join() t = Thread(target=self._insert, args=[transac, keys]) t.start() transac = [] if len(transac) > 0: if t: ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html
af5ade709a82-7
Returns: ClickHouse Index """ ctx = cls(embedding, config, **kwargs) ctx.add_texts(texts, ids=text_ids, batch_size=batch_size, metadatas=metadatas) return ctx def __repr__(self) -> str: """Text representation for ClickHouse Vector Store, prints backends, username ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html
af5ade709a82-8
else: where_str = "" settings_strs = [] if self.config.index_query_params: for k in self.config.index_query_params: settings_strs.append(f"SETTING {k}={self.config.index_query_params[k]}") q_str = f""" SELECT {self.config.column_map['document']...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html
af5ade709a82-9
self, embedding: List[float], k: int = 4, where_str: Optional[str] = None, **kwargs: Any, ) -> List[Document]: """Perform a similarity search with ClickHouse by vectors Args: query (str): query string k (int, optional): Top K neighbors to retri...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html
af5ade709a82-10
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://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html
0b748921a2ca-0
Source code for langchain.vectorstores.alibabacloud_opensearch import json import logging import numbers from hashlib import sha1 from typing import Any, Dict, Iterable, List, Optional, Tuple from langchain.embeddings.base import Embeddings from langchain.schema import Document from langchain.vectorstores.base import V...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html
0b748921a2ca-1
instance_id: str username: str password: str datasource_name: str embedding_index_name: str field_name_mapping: Dict[str, str] = { "id": "id", "document": "document", "embedding": "embedding", "metadata_field_x": "metadata_field_x,operator", } def __init__( ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html
0b748921a2ca-2
def __init__( self, embedding: Embeddings, config: AlibabaCloudOpenSearchSettings, **kwargs: Any, ) -> None: try: from alibabacloud_ha3engine import client, models from alibabacloud_tea_util import models as util_models except ImportError: ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html
0b748921a2ca-3
self.config.datasource_name, field_name_map["id"], push_request ) json_response = json.loads(push_response.body) if json_response["status"] == "OK": return [ push_doc["fields"][field_name_map["id"]] for p...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html
0b748921a2ca-4
) if metadata is not None: for md_key, md_value in metadata.items(): add_doc_fields.__setitem__( field_name_map[md_key].split(",")[0], md_value ) add_doc.__setitem__("fields", add_doc_fields) add_doc.__se...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html
0b748921a2ca-5
embedding=embedding, search_filter=search_filter, k=k ) ) [docs] def inner_embedding_query( self, embedding: List[float], search_filter: Optional[Dict[str, Any]] = None, k: int = 4, ) -> Dict[str, Any]: def generate_embedding_query() -> str: ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html
0b748921a2ca-6
md_filter_operator = expr[1].strip() if isinstance(md_value, numbers.Number): return f"{md_filter_key} {md_filter_operator} {md_value}" return f'{md_filter_key}{md_filter_operator}"{md_value}"' def search_data(single_query_str: str) -> Dict[str, Any]: search_q...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html
0b748921a2ca-7
self, json_result: Dict[str, Any] ) -> List[Tuple[Document, float]]: items = json_result["result"]["items"] query_result_list: List[Tuple[Document, float]] = [] for item in items: fields = item["fields"] query_result_list.append( ( ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html
0b748921a2ca-8
return cls.from_texts( texts=texts, embedding=embedding, metadatas=metadatas, config=config, **kwargs, )
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html
026424a18e61-0
Source code for langchain.vectorstores.rocksetdb """Wrapper around Rockset vector database.""" from __future__ import annotations import logging from enum import Enum from typing import Any, Iterable, List, Optional, Tuple from langchain.docstore.document import Document from langchain.embeddings.base import Embeddings...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html
026424a18e61-1
client: Any, embeddings: Embeddings, collection_name: str, text_key: str, embedding_key: str, ): """Initialize with Rockset client. Args: client: Rockset client object collection: Rockset collection to insert docs / query embeddings...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html
026424a18e61-2
"""Run more texts through the embeddings and add to the vectorstore Args: texts: Iterable of strings to add to the vectorstore. metadatas: Optional list of metadatas associated with the texts. ids: Optional list of ids to associate with the texts. batch_si...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html
026424a18e61-3
) -> Rockset: """Create Rockset wrapper with existing texts. This is intended as a quicker way to get started. """ # Sanitize imputs assert client is not None, "Rockset Client cannot be None" assert collection_name, "Collection name cannot be empty" assert text_ke...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html
026424a18e61-4
k (int, optional): Top K neighbors to retrieve. Defaults to 4. where_str (Optional[str], optional): Metadata filters supplied as a SQL `where` condition string. Defaults to None. eg. "price<=70.0 AND brand='Nintendo'" NOTE: Please do not let end-user to fill this ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html
026424a18e61-5
"""Accepts a query_embedding (vector), and returns documents with similar embeddings.""" docs_and_scores = self.similarity_search_by_vector_with_relevance_scores( embedding, k, distance_func, where_str, **kwargs ) return [doc for doc, _ in docs_and_scores] [docs] def simil...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html
026424a18e61-6
self._text_key, type(v) ) page_content = v elif k == "dist": assert isinstance( v, float ), "Computed distance between vectors must of type `float`. \ But found {}".format( ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html
026424a18e61-7
collection=self._collection_name, data=batch ) return [doc_status._id for doc_status in add_doc_res.data] [docs] def delete_texts(self, ids: List[str]) -> None: """Delete a list of docs from the Rockset collection""" try: from rockset.models import DeleteDocumentsRequestDa...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html
0245ad0cd55d-0
Source code for langchain.vectorstores.base """Interface for vector stores.""" from __future__ import annotations import asyncio import warnings from abc import ABC, abstractmethod from functools import partial from typing import ( Any, ClassVar, Collection, Dict, Iterable, List, Optional, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
0245ad0cd55d-1
) [docs] async def aadd_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, **kwargs: Any, ) -> List[str]: """Run more texts through the embeddings and add to the vectorstore.""" raise NotImplementedError [docs] def add_documents(self, doc...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
0245ad0cd55d-2
if search_type == "similarity": return self.similarity_search(query, **kwargs) elif search_type == "mmr": return self.max_marginal_relevance_search(query, **kwargs) else: raise ValueError( f"search_type of {search_type} not allowed. Expected " ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
0245ad0cd55d-3
k: Number of Documents to return. Defaults to 4. **kwargs: kwargs to be passed to similarity search. Should include: score_threshold: Optional, a floating point value between 0 to 1 to filter the resulting set of retrieved docs Returns: List of Tuples ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
0245ad0cd55d-4
raise NotImplementedError [docs] async def asimilarity_search_with_relevance_scores( self, query: str, k: int = 4, **kwargs: Any ) -> List[Tuple[Document, float]]: """Return docs most similar to query.""" # This is a temporary workaround to make the similarity search # asynchronou...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
0245ad0cd55d-5
self, embedding: List[float], k: int = 4, **kwargs: Any ) -> List[Document]: """Return docs most similar to embedding vector.""" # This is a temporary workaround to make the similarity search # asynchronous. The proper solution is to make the similarity search # asynchronous in the v...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
0245ad0cd55d-6
lambda_mult: float = 0.5, **kwargs: Any, ) -> List[Document]: """Return docs selected using the maximal marginal relevance.""" # This is a temporary workaround to make the similarity search # asynchronous. The proper solution is to make the similarity search # asynchronous in...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
0245ad0cd55d-7
k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any, ) -> List[Document]: """Return docs selected using the maximal marginal relevance.""" raise NotImplementedError [docs] @classmethod def from_documents( cls: Type[VST], documents: Li...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
0245ad0cd55d-8
cls: Type[VST], texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any, ) -> VST: """Return VectorStore initialized from texts and embeddings.""" raise NotImplementedError [docs] def as_retriever(self, **kwargs: Any) -> Vecto...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
0245ad0cd55d-9
def get_relevant_documents(self, query: str) -> List[Document]: if self.search_type == "similarity": docs = self.vectorstore.similarity_search(query, **self.search_kwargs) elif self.search_type == "similarity_score_threshold": docs_and_similarities = ( self.vector...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
0245ad0cd55d-10
"""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://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
42d60dfd50ce-0
Source code for langchain.vectorstores.awadb """Wrapper around AwaDB for embedding vectors""" from __future__ import annotations import logging import uuid from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple, Type from langchain.docstore.document import Document from langchain.embeddings.base import ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html
42d60dfd50ce-1
self.table2embeddings: dict[str, Embeddings] = {} if embedding_model is not None: self.table2embeddings[table_name] = embedding_model self.using_table_name = table_name [docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html
42d60dfd50ce-2
[docs] def similarity_search( self, query: str, k: int = DEFAULT_TOPN, **kwargs: Any, ) -> List[Document]: """Return docs most similar to query.""" if self.awadb_client is None: raise ValueError("AwaDB client is None!!!") embedding = None ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html
42d60dfd50ce-3
retrieval_docs = self.similarity_search_by_vector(embedding, k, scores) L2_Norm = 0.0 for score in scores: L2_Norm = L2_Norm + score * score L2_Norm = pow(L2_Norm, 0.5) doc_no = 0 for doc in retrieval_docs: doc_tuple = (doc, 1 - (scores[doc_no] / L2_Norm))...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html
42d60dfd50ce-4
L2_Norm = L2_Norm + score * score L2_Norm = pow(L2_Norm, 0.5) doc_no = 0 for doc in retrieval_docs: doc_tuple = (doc, 1 - scores[doc_no] / L2_Norm) results.append(doc_tuple) doc_no = doc_no + 1 return results [docs] def similarity_search_by_vector( ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html
42d60dfd50ce-5
content = item_detail[item_key] elif ( item_key == "Field@1" or item_key == "text_embedding" ): # embedding field for the document continue elif item_key == "score": # L2 distance if scores is not None: ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html
42d60dfd50ce-6
) -> str: """Get the current table.""" return self.using_table_name [docs] @classmethod def from_texts( cls: Type[AwaDB], texts: List[str], embedding: Optional[Embeddings] = None, metadatas: Optional[List[dict]] = None, table_name: str = _DEFAULT_TABLE_NAME...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html
42d60dfd50ce-7
table_name: str = _DEFAULT_TABLE_NAME, logging_and_data_dir: Optional[str] = None, client: Optional[awadb.Client] = None, **kwargs: Any, ) -> AwaDB: """Create an AwaDB vectorstore from a list of documents. If a logging_and_data_dir specified, the table will be persisted there...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/awadb.html
43606bb90b19-0
Source code for langchain.vectorstores.milvus """Wrapper around the Milvus vector database.""" from __future__ import annotations import logging from typing import Any, Iterable, List, Optional, Tuple, Union from uuid import uuid4 import numpy as np from langchain.docstore.document import Document from langchain.embedd...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
43606bb90b19-1
The connection args used for this class comes in the form of a dict, here are a few of the options: address (str): The actual address of Milvus instance. Example address: "localhost:19530" uri (str): The uri of Milvus instance. Example uri: "http://randomw...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
43606bb90b19-2
Args: embedding_function (Embeddings): Function used to embed the text. collection_name (str): Which Milvus collection to use. Defaults to "LangChainCollection". connection_args (Optional[dict[str, any]]): The arguments for connection to Milvus/Zilliz ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
43606bb90b19-3
"RHNSW_SQ": {"metric_type": "L2", "params": {"ef": 10}}, "RHNSW_PQ": {"metric_type": "L2", "params": {"ef": 10}}, "IVF_HNSW": {"metric_type": "L2", "params": {"nprobe": 10, "ef": 10}}, "ANNOY": {"metric_type": "L2", "params": {"search_k": 10}}, "AUTOINDEX": {"metric_type"...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
43606bb90b19-4
if drop_old and isinstance(self.col, Collection): self.col.drop() self.col = None # Initialize the vector store self._init() def _create_connection_alias(self, connection_args: dict) -> str: """Create the connection to the Milvus server.""" from pymilvus impor...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
43606bb90b19-5
and (addr["user"] == tmp_user) ): logger.debug("Using previous connection: %s", con[0]) return con[0] # Generate a new connection if one doesnt exist alias = uuid4().hex try: connections.connect(alias=alias, **connection_args) ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
43606bb90b19-6
if dtype == DataType.UNKNOWN or dtype == DataType.NONE: logger.error( "Failure to create collection, unrecognized dtype for key: %s", key, ) raise ValueError(f"Unrecognized datatype for {key}.") #...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
43606bb90b19-7
for x in schema.fields: self.fields.append(x.name) # Since primary field is auto-id, no need to track it self.fields.remove(self._primary_field) def _get_index(self) -> Optional[dict[str, Any]]: """Return the vector index information if it exists""" from pymil...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
43606bb90b19-8
using=self.alias, ) logger.debug( "Successfully created an index on collection: %s", self.collection_name, ) except MilvusException as e: logger.error( "Failed to create an index o...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
43606bb90b19-9
embedding and the columns are decided by the first metadata dict. Metada keys will need to be present for all inserted values. At the moment there is no None equivalent in Milvus. Args: texts (Iterable[str]): The texts to embed, it is assumed that they all fit in memo...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
43606bb90b19-10
for key, value in d.items(): if key in self.fields: insert_dict.setdefault(key, []).append(value) # Total insert count vectors: list = insert_dict[self._vector_field] total_count = len(vectors) pks: list[str] = [] assert isinstance(self...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
43606bb90b19-11
expr (str, optional): Filtering expression. Defaults to None. timeout (int, optional): How long to wait before timeout error. Defaults to None. kwargs: Collection.search() keyword arguments. Returns: List[Document]: Document results for search. """ ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
43606bb90b19-12
return [] res = self.similarity_search_with_score_by_vector( embedding=embedding, k=k, param=param, expr=expr, timeout=timeout, **kwargs ) return [doc for doc, _ in res] [docs] def similarity_search_with_score( self, query: str, k: int = 4, param: O...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
43606bb90b19-13
res = self.similarity_search_with_score_by_vector( embedding=embedding, k=k, param=param, expr=expr, timeout=timeout, **kwargs ) return res [docs] def similarity_search_with_score_by_vector( self, embedding: List[float], k: int = 4, param: Optional[dict] = ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
43606bb90b19-14
# Perform the search. res = self.col.search( data=[embedding], anns_field=self._vector_field, param=param, limit=k, expr=expr, output_fields=output_fields, timeout=timeout, **kwargs, ) # Organize resu...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
43606bb90b19-15
Defaults to None. expr (str, optional): Filtering expression. Defaults to None. timeout (int, optional): How long to wait before timeout error. Defaults to None. kwargs: Collection.search() keyword arguments. Returns: List[Document]: Document resul...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
43606bb90b19-16
to maximum diversity and 1 to minimum diversity. Defaults to 0.5 param (dict, optional): The search params for the specified index. Defaults to None. expr (str, optional): Filtering expression. Defaults to None. timeout (int, optional): How lon...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
43606bb90b19-17
) # Reorganize the results from query to match search order. vectors = {x[self._primary_field]: x[self._vector_field] for x in vectors} ordered_result_embeddings = [vectors[x] for x in ids] # Get the new order of results. new_ordering = maximal_marginal_relevance( np....
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
43606bb90b19-18
"LangChainCollection". connection_args (dict[str, Any], optional): Connection args to use. Defaults to DEFAULT_MILVUS_CONNECTION. consistency_level (str, optional): Which consistency level to use. Defaults to "Session". index_params (Optional[dict], op...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html
5d704991e9bc-0
Source code for langchain.vectorstores.elastic_vector_search """Wrapper around Elasticsearch vector database.""" from __future__ import annotations import uuid from abc import ABC from typing import ( TYPE_CHECKING, Any, Dict, Iterable, List, Mapping, Optional, Tuple, Union, ) from l...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
5d704991e9bc-1
# defined as an abstract base class itself, allowing the creation of subclasses with # their own specific implementations. If you plan to subclass ElasticVectorSearch, # you can inherit from it and define your own implementation of the necessary methods # and attributes. [docs]class ElasticVectorSearch(VectorStore, ABC...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
5d704991e9bc-2
4. Click "Reset password" 5. Follow the prompts to reset the password The format for Elastic Cloud URLs is https://username:password@cluster_id.region_id.gcp.cloud.es.io:9243. Example: .. code-block:: python from langchain import ElasticVectorSearch from langchain.embeddi...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
5d704991e9bc-3
self.index_name = index_name _ssl_verify = ssl_verify or {} try: self.client = elasticsearch.Elasticsearch(elasticsearch_url, **_ssl_verify) except ValueError as e: raise ValueError( f"Your elasticsearch client string is mis-formatted. Got error: {e} " ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
5d704991e9bc-4
# just to save expensive steps for last self.create_index(self.client, self.index_name, mapping) for i, text in enumerate(texts): metadata = metadatas[i] if metadatas else {} request = { "_op_type": "index", "_index": self.index_name, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
5d704991e9bc-5
Returns: List of Documents most similar to the query. """ embedding = self.embedding.embed_query(query) script_query = _default_script_query(embedding, filter) response = self.client_search( self.client, self.index_name, script_query, size=k ) hits...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
5d704991e9bc-6
elasticsearch_url="http://localhost:9200" ) """ elasticsearch_url = elasticsearch_url or get_from_env( "elasticsearch_url", "ELASTICSEARCH_URL" ) index_name = index_name or uuid.uuid4().hex vectorsearch = cls(elasticsearch_url, index_name, embedding, *...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html