id stringlengths 14 16 | text stringlengths 4 1.28k | source stringlengths 54 121 |
|---|---|---|
6adb2cb75201-35 | return [
# First, try to split along Markdown headings (starting with level 2)
"\n#{1,6} ",
# Note the alternative syntax for headings (below) is not handled here
# Heading level 2
# ---------------
# End of code block
... | https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
6adb2cb75201-36 | "\n\\\chapter{",
"\n\\\section{",
"\n\\\subsection{",
"\n\\\subsubsection{",
# Now split by environments
"\n\\\begin{enumerate}",
"\n\\\begin{itemize}",
"\n\\\begin{description}",
"\n\\\begin{... | https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
6adb2cb75201-37 | "<div",
"<p",
"<br",
"<li",
"<h1",
"<h2",
"<h3",
"<h4",
"<h5",
"<h6",
"<span",
"<table",
"<tr",
"<td",
... | https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
6adb2cb75201-38 | "\nlibrary ",
# Split along method definitions
"\nconstructor ",
"\ntype ",
"\nfunction ",
"\nevent ",
"\nmodifier ",
"\nerror ",
"\nstruct ",
"\nenum ",
# Spli... | https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
6adb2cb75201-39 | def __init__(self, separator: str = "\n\n", **kwargs: Any) -> None:
"""Initialize the NLTK splitter."""
super().__init__(**kwargs)
try:
from nltk.tokenize import sent_tokenize
self._tokenizer = sent_tokenize
except ImportError:
raise ImportError(
... | https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
6adb2cb75201-40 | def __init__(
self, separator: str = "\n\n", pipeline: str = "en_core_web_sm", **kwargs: Any
) -> None:
"""Initialize the spacy text splitter."""
super().__init__(**kwargs)
try:
import spacy
except ImportError:
raise ImportError(
"Spacy... | https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
6adb2cb75201-41 | # For backwards compatibility
[docs]class PythonCodeTextSplitter(RecursiveCharacterTextSplitter):
"""Attempts to split the text along Python syntax."""
def __init__(self, **kwargs: Any) -> None:
"""Initialize a PythonCodeTextSplitter."""
separators = self.get_separators_for_language(Language.PYT... | https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
6adb2cb75201-42 | """Attempts to split the text along Latex-formatted layout elements."""
def __init__(self, **kwargs: Any) -> None:
"""Initialize a LatexTextSplitter."""
separators = self.get_separators_for_language(Language.LATEX)
super().__init__(separators=separators, **kwargs) | https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
7284a5d10f76-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 |
7284a5d10f76-1 | elif isinstance(m, AIMessage):
role = ai_prefix
elif isinstance(m, SystemMessage):
role = "System"
elif isinstance(m, FunctionMessage):
role = "Function"
elif isinstance(m, ChatMessage):
role = m.role
else:
raise ValueError(f"Go... | https://api.python.langchain.com/en/latest/_modules/langchain/schema.html |
7284a5d10f76-2 | """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 |
7284a5d10f76-3 | @property
def lc_serializable(self) -> bool:
"""This class is LangChain serializable."""
return True
[docs]class HumanMessage(BaseMessage):
"""Type of message that is spoken by the human."""
example: bool = False
@property
def type(self) -> str:
"""Type of the message, used f... | https://api.python.langchain.com/en/latest/_modules/langchain/schema.html |
7284a5d10f76-4 | 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 with arbitrary speaker."""
role: str
@property
de... | https://api.python.langchain.com/en/latest/_modules/langchain/schema.html |
7284a5d10f76-5 | List of dicts.
"""
return [_message_to_dict(m) for m in messages]
def _message_from_dict(message: dict) -> BaseMessage:
_type = message["type"]
if _type == "human":
return HumanMessage(**message["data"])
elif _type == "ai":
return AIMessage(**message["data"])
elif _type == "syste... | https://api.python.langchain.com/en/latest/_modules/langchain/schema.html |
7284a5d10f76-6 | 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]:
values["text"... | https://api.python.langchain.com/en/latest/_modules/langchain/schema.html |
7284a5d10f76-7 | [docs]class LLMResult(BaseModel):
"""Class that contains all relevant information for an LLM Result."""
generations: List[List[Generation]]
"""List of the things generated. This is List[List[]] because
each input could have multiple generations."""
llm_output: Optional[dict] = None
"""For arbitr... | https://api.python.langchain.com/en/latest/_modules/langchain/schema.html |
7284a5d10f76-8 | 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 |
7284a5d10f76-9 | def to_string(self) -> str:
"""Return prompt as string."""
[docs] @abstractmethod
def to_messages(self) -> List[BaseMessage]:
"""Return prompt as messages."""
[docs]class BaseMemory(Serializable, ABC):
"""Base interface for memory in chains."""
class Config:
"""Configuration for t... | https://api.python.langchain.com/en/latest/_modules/langchain/schema.html |
7284a5d10f76-10 | """
[docs] @abstractmethod
def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None:
"""Save the context of this model run to memory."""
[docs] @abstractmethod
def clear(self) -> None:
"""Clear memory contents."""
[docs]class BaseChatMessageHistory(ABC):
"""Base ... | https://api.python.langchain.com/en/latest/_modules/langchain/schema.html |
7284a5d10f76-11 | return messages_from_dict(messages)
def add_message(self, message: BaseMessage) -> None:
messages = self.messages.append(_message_to_dict(message))
with open(os.path.join(storage_path, session_id), 'w') as f:
json.dump(f, messages)
... | https://api.python.langchain.com/en/latest/_modules/langchain/schema.html |
7284a5d10f76-12 | [docs] def add_message(self, message: BaseMessage) -> None:
"""Add a self-created message to the store"""
raise NotImplementedError
[docs] @abstractmethod
def clear(self) -> None:
"""Remove all messages from the store"""
[docs]class Document(Serializable):
"""Interface for interact... | https://api.python.langchain.com/en/latest/_modules/langchain/schema.html |
7284a5d10f76-13 | """
[docs] @abstractmethod
async def aget_relevant_documents(self, query: str) -> List[Document]:
"""Get documents relevant for a query.
Args:
query: string to find relevant documents for
Returns:
List of relevant documents
"""
# For backwards compatibility... | https://api.python.langchain.com/en/latest/_modules/langchain/schema.html |
7284a5d10f76-14 | return self.parse(result[0].text)
[docs] @abstractmethod
def parse(self, text: str) -> T:
"""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
... | https://api.python.langchain.com/en/latest/_modules/langchain/schema.html |
7284a5d10f76-15 | Returns:
structured output
"""
return self.parse(completion)
[docs] def get_format_instructions(self) -> str:
"""Instructions on how the LLM output should be formatted."""
raise NotImplementedError
@property
def _type(self) -> str:
"""Return the type key.""... | https://api.python.langchain.com/en/latest/_modules/langchain/schema.html |
7284a5d10f76-16 | @property
def lc_serializable(self) -> bool:
return True
@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 e... | https://api.python.langchain.com/en/latest/_modules/langchain/schema.html |
7284a5d10f76-17 | ):
super(OutputParserException, self).__init__(error)
if send_to_llm:
if observation is None or llm_output is None:
raise ValueError(
"Arguments 'observation' & 'llm_output'"
" are required if 'send_to_llm' is True"
)
... | https://api.python.langchain.com/en/latest/_modules/langchain/schema.html |
7284a5d10f76-18 | ) -> Sequence[Document]:
"""Asynchronously transform a list of documents.""" | https://api.python.langchain.com/en/latest/_modules/langchain/schema.html |
473f3ea87a42-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 |
473f3ea87a42-1 | return doc
return cls(page_content=doc.page_content, metadata=doc.metadata)
[docs]def get_stateful_documents(
documents: Sequence[Document],
) -> Sequence[_DocumentWithState]:
"""Convert a list of documents to a list of documents with state.
Args:
documents: The documents to convert.
Ret... | https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers.html |
473f3ea87a42-2 | 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:
# Default to dropping the second document of any hig... | https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers.html |
473f3ea87a42-3 | )
for doc, embedding in zip(documents, embedded_documents):
doc.state["embedded_doc"] = embedding
return embedded_documents
[docs]class EmbeddingsRedundantFilter(BaseDocumentTransformer, BaseModel):
"""Filter that drops redundant documents by comparing their embeddings."""
embeddings: Em... | https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers.html |
473f3ea87a42-4 | [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(
self.embeddings, sta... | https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers.html |
cd50fce0f13f-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 |
cd50fce0f13f-1 | return False
return True
[docs]class ClickhouseSettings(BaseSettings):
"""ClickHouse Client Configuration
Attribute:
clickhouse_host (str) : An URL to connect to MyScale backend.
Defaults to 'localhost'.
clickhouse_port (int) : URL port to connect with HTTP. Defa... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
cd50fce0f13f-2 | supported are ('angular', 'euclidean', 'manhattan', 'hamming',
'dot'). Defaults to 'angular'.
https://github.com/spotify/annoy/blob/main/src/annoymodule.cc#L149-L169
column_map (Dict) : Column type map to project column name onto langchain
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
cd50fce0f13f-3 | username: Optional[str] = None
password: Optional[str] = None
index_type: str = "annoy"
# Annoy supports L2Distance and cosineDistance.
index_param: Optional[Union[List, Dict]] = ["'L2Distance'", 100]
index_query_params: Dict[str, str] = {}
column_map: Dict[str, str] = {
"id": "id",
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
cd50fce0f13f-4 | 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 ClickHouse.
ClickHouse can not only search with sim... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
cd50fce0f13f-5 | embedding_function (Embeddings):
config (ClickHouseSettings): Configuration to ClickHouse Client
Other keyword arguments will pass into
[clickhouse-connect](https://docs.clickhouse.com/)
"""
try:
from clickhouse_connect import get_client
except ImportError... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
cd50fce0f13f-6 | 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"]:
assert k in self.config.column_map
assert self.config.metric in [
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
cd50fce0f13f-7 | if isinstance(self.config.index_param, List)
else self.config.index_param
)
self.schema = f"""\
CREATE TABLE IF NOT EXISTS {self.config.database}.{self.config.table}(
{self.config.column_map['id']} Nullable(String),
{self.config.column_map['document']} Nullable(String),
{self.con... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
cd50fce0f13f-8 | """
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 |
cd50fce0f13f-9 | return "".join(f"{self.BS}{c}" if c in self.must_escape else c for c in value)
def _build_insert_sql(self, transac: Iterable, column_names: Iterable[str]) -> str:
ks = ",".join(column_names)
_data = []
for n in transac:
n = ",".join([f"'{self.escape_str(str(_n))}'" for _n in n])
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
cd50fce0f13f-10 | self.client.command(_insert_query)
[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 embedding... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
cd50fce0f13f-11 | colmap_ = self.config.column_map
transac = []
column_names = {
colmap_["id"]: ids,
colmap_["document"]: texts,
colmap_["embedding"]: self.embedding_function.embed_documents(list(texts)),
}
metadatas = metadatas or [{} for _ in texts]
column_nam... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
cd50fce0f13f-12 | )
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:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
cd50fce0f13f-13 | config: Optional[ClickhouseSettings] = None,
text_ids: Optional[Iterable[str]] = None,
batch_size: int = 32,
**kwargs: Any,
) -> Clickhouse:
"""Create ClickHouse wrapper with existing texts
Args:
embedding_function (Embeddings): Function to extract text embedding
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
cd50fce0f13f-14 | Other keyword arguments will pass into
[clickhouse-connect](https://clickhouse.com/docs/en/integrations/python#clickhouse-connect-driver-api)
Returns:
ClickHouse Index
"""
ctx = cls(embedding, config, **kwargs)
ctx.add_texts(texts, ids=text_ids, batch_size=bat... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
cd50fce0f13f-15 | _repr += f"\033[1musername: {self.config.username}\033[0m\n\nTable Schema:\n"
_repr += "-" * 51 + "\n"
for r in self.client.query(
f"DESC {self.config.database}.{self.config.table}"
).named_results():
_repr += (
f"|\033[94m{r['name']:24s}\033[0m|\033[96m{r... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
cd50fce0f13f-16 | if where_str:
where_str = f"PREWHERE {where_str}"
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]}")
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
cd50fce0f13f-17 | [docs] def similarity_search(
self, query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any
) -> List[Document]:
"""Perform a similarity search with ClickHouse
Args:
query (str): query string
k (int, optional): Top K neighbors to retrieve. Defaults t... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
cd50fce0f13f-18 | return self.similarity_search_by_vector(
self.embedding_function.embed_query(query), k, where_str, **kwargs
)
[docs] def similarity_search_by_vector(
self,
embedding: List[float],
k: int = 4,
where_str: Optional[str] = None,
**kwargs: Any,
) -> List[Doc... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
cd50fce0f13f-19 | alone. The default name for it is `metadata`.
Returns:
List[Document]: List of (Document, similarity)
"""
q_str = self._build_query_sql(embedding, k, where_str)
try:
return [
Document(
page_content=r[self.config.column_map["docu... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
cd50fce0f13f-20 | ) -> List[Tuple[Document, float]]:
"""Perform a similarity search with ClickHouse
Args:
query (str): query string
k (int, optional): Top K neighbors to retrieve. Defaults to 4.
where_str (Optional[str], optional): where condition string.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
cd50fce0f13f-21 | (
Document(
page_content=r[self.config.column_map["document"]],
metadata=r[self.config.column_map["metadata"]],
),
r["dist"],
)
for r in self.client.query(q_str).named_results()
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
dc2c0476501a-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 |
dc2c0476501a-1 | password (str) : The password specified when purchasing the instance.
embedding_index_name (str) : The name of the vector attribute specified
when configuring the instance attributes.
field_name_mapping (Dict) : Using field name mapping between opensearch
vector store and opensearch ins... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
dc2c0476501a-2 | 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 |
dc2c0476501a-3 | self.embedding_index_name = embedding_index_name
self.field_name_mapping = field_name_mapping
def __getitem__(self, item: str) -> Any:
return getattr(self, item)
def create_metadata(fields: Dict[str, Any]) -> Dict[str, Any]:
"""Create metadata from fields.
Args:
fields: The fields of... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
dc2c0476501a-4 | 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 |
dc2c0476501a-5 | models.Config(
endpoint=config.endpoint,
instance_id=config.instance_id,
protocol="http",
access_user_name=config.username,
access_pass_word=config.password,
)
)
self.options_headers: Dict[str, str] = {}
[docs] ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
dc2c0476501a-6 | 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 |
dc2c0476501a-7 | add_doc_list = []
text_list = list(texts)
for idx, doc_id in enumerate(ids):
embedding = embeddings[idx] if idx < len(embeddings) else None
metadata = metadatas[idx] if idx < len(metadatas) else None
text = text_list[idx] if idx < len(text_list) else None
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
dc2c0476501a-8 | 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.__setitem__("cmd",... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
dc2c0476501a-9 | )
)
[docs] def similarity_search_with_relevance_scores(
self,
query: str,
k: int = 4,
search_filter: Optional[dict] = None,
**kwargs: Any,
) -> List[Tuple[Document, float]]:
embedding: List[float] = self.embedding.embed_query(query)
return self.crea... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
dc2c0476501a-10 | self.inner_embedding_query(
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 ge... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
dc2c0476501a-11 | + "'"
)
if search_filter is not None:
filter_clause = "&&filter=" + " AND ".join(
[
create_filter(md_key, md_value)
for md_key, md_value in search_filter.items()
]
)
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
dc2c0476501a-12 | 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 |
dc2c0476501a-13 | f"errors:{json_response['errors']} failed."
)
else:
return json_response
except Exception as e:
logger.error(
f"query instance endpoint:{self.config.endpoint} "
f"instance_id:{self.config.instance_id} failed.",
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
dc2c0476501a-14 | 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 |
dc2c0476501a-15 | **kwargs: Any,
) -> "AlibabaCloudOpenSearch":
if config is None:
raise Exception("config can't be none")
ctx = cls(embedding, config, **kwargs)
ctx.add_texts(texts=texts, metadatas=metadatas)
return ctx
[docs] @classmethod
def from_documents(
cls,
d... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
dc2c0476501a-16 | 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 |
e0c213ad49b4-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 |
e0c213ad49b4-1 | collection.
See: https://rockset.com/blog/introducing-vector-search-on-rockset/ for more details
Everything below assumes `commons` Rockset workspace.
TODO: Add support for workspace args.
Example:
.. code-block:: python
from langchain.vectorstores import Rockset
from lan... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html |
e0c213ad49b4-2 | """
def __init__(
self,
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 t... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html |
e0c213ad49b4-3 | "Please install it with `pip install rockset`."
)
if not isinstance(client, RocksetClient):
raise ValueError(
f"client should be an instance of rockset.RocksetClient, "
f"got {type(client)}"
)
# TODO: check that `collection_name` exists... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html |
e0c213ad49b4-4 | ) -> List[str]:
"""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 tex... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html |
e0c213ad49b4-5 | doc = metadatas[i]
if ids and len(ids) > i:
doc["_id"] = ids[i]
doc[self._text_key] = text
doc[self._embedding_key] = self._embeddings.embed_query(text)
batch.append(doc)
if len(batch) > 0:
stored_ids += self._write_documents_to_rockset... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html |
e0c213ad49b4-6 | batch_size: int = 32,
**kwargs: Any,
) -> 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, "Collec... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html |
e0c213ad49b4-7 | EUCLIDEAN_DIST = "EUCLIDEAN_DIST"
DOT_PRODUCT = "DOT_PRODUCT"
# how to sort results for "similarity"
[docs] def order_by(self) -> str:
if self.value == "EUCLIDEAN_DIST":
return "ASC"
return "DESC"
[docs] def similarity_search_with_relevance_scores(
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html |
e0c213ad49b4-8 | vectors in Rockset.
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 d... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html |
e0c213ad49b4-9 | k: int = 4,
distance_func: DistanceFunction = DistanceFunction.COSINE_SIM,
where_str: Optional[str] = None,
**kwargs: Any,
) -> List[Document]:
"""Same as `similarity_search_with_relevance_scores` but
doesn't return the scores.
"""
return self.similarity_searc... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html |
e0c213ad49b4-10 | ) -> List[Document]:
"""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_an... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html |
e0c213ad49b4-11 | similar embeddings along with their relevance scores."""
q_str = self._build_query_sql(embedding, distance_func, k, where_str)
try:
query_response = self._client.Queries.query(sql={"query": q_str})
except Exception as e:
logger.error("Exception when querying Rockset: %s\n... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html |
e0c213ad49b4-12 | assert isinstance(
v, str
), "page content stored in column `{}` must be of type `str`. \
But found: `{}`".format(
self._text_key, type(v)
)
page_content = v
elif k == "dis... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html |
e0c213ad49b4-13 | return finalResult
# Helper functions
def _build_query_sql(
self,
query_embedding: List[float],
distance_func: DistanceFunction,
k: int = 4,
where_str: Optional[str] = None,
) -> str:
"""Builds Rockset SQL query to query similar vectors to query_vector"""
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html |
e0c213ad49b4-14 | LIMIT {str(k)}
"""
def _write_documents_to_rockset(self, batch: List[dict]) -> List[str]:
add_doc_res = self._client.Documents.add_documents(
collection=self._collection_name, data=batch
)
return [doc_status._id for doc_status in add_doc_res.data]
[docs] def delete_texts(self,... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/rocksetdb.html |
e557f61be02a-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 |
e557f61be02a-1 | texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
**kwargs: Any,
) -> List[str]:
"""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 ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
e557f61be02a-2 | """
raise NotImplementedError(
"delete_by_id method must be implemented by subclass."
)
[docs] async def aadd_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
**kwargs: Any,
) -> List[str]:
"""Run more texts through the... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
e557f61be02a-3 | texts = [doc.page_content for doc in documents]
metadatas = [doc.metadata for doc in documents]
return self.add_texts(texts, metadatas, **kwargs)
[docs] async def aadd_documents(
self, documents: List[Document], **kwargs: Any
) -> List[str]:
"""Run more documents through the embed... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
e557f61be02a-4 | [docs] def search(self, query: str, search_type: str, **kwargs: Any) -> List[Document]:
"""Return docs most similar to query using specified search type."""
if search_type == "similarity":
return self.similarity_search(query, **kwargs)
elif search_type == "mmr":
return... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
e557f61be02a-5 | if search_type == "similarity":
return await self.asimilarity_search(query, **kwargs)
elif search_type == "mmr":
return await self.amax_marginal_relevance_search(query, **kwargs)
else:
raise ValueError(
f"search_type of {search_type} not allowed. Expec... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
e557f61be02a-6 | """Return docs and relevance scores in the range [0, 1].
0 is dissimilar, 1 is most similar.
Args:
query: input text
k: Number of Documents to return. Defaults to 4.
**kwargs: kwargs to be passed to similarity search. Should include:
score_threshold: O... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
e557f61be02a-7 | "Relevance scores must be between"
f" 0 and 1, got {docs_and_similarities}"
)
score_threshold = kwargs.get("score_threshold")
if score_threshold is not None:
docs_and_similarities = [
(doc, similarity)
for doc, similarity in docs_an... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
e557f61be02a-8 | """Return docs and relevance scores, normalized on a scale from 0 to 1.
0 is dissimilar, 1 is most similar.
"""
raise NotImplementedError
[docs] async def asimilarity_search_with_relevance_scores(
self, query: str, k: int = 4, **kwargs: Any
) -> List[Tuple[Document, float]]:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
e557f61be02a-9 | self, query: str, k: int = 4, **kwargs: Any
) -> List[Document]:
"""Return docs most similar to query."""
# This is a temporary workaround to make the similarity search
# asynchronous. The proper solution is to make the similarity search
# asynchronous in the vector store implementat... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
e557f61be02a-10 | Returns:
List of Documents most similar to the query vector.
"""
raise NotImplementedError
[docs] async def asimilarity_search_by_vector(
self, embedding: List[float], k: int = 4, **kwargs: Any
) -> List[Document]:
"""Return docs most similar to embedding vector."""
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
e557f61be02a-11 | fetch_k: int = 20,
lambda_mult: float = 0.5,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
Args:
query:... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
e557f61be02a-12 | """
raise NotImplementedError
[docs] async def amax_marginal_relevance_search(
self,
query: str,
k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected using the maximal marginal relevanc... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
e557f61be02a-13 | self,
embedding: List[float],
k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.