id stringlengths 14 16 | text stringlengths 31 2.41k | source stringlengths 54 121 |
|---|---|---|
9f819fb5da00-7 | documents = []
for i, text in enumerate(texts):
metadata = metadatas[i] if metadatas else {}
documents.append(Document(page_content=text, metadata=metadata))
index_to_id = {i: str(uuid.uuid4()) for i in range(len(documents))}
docstore = InMemoryDocstore(
{inde... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
9f819fb5da00-8 | from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
index = Annoy.from_texts(texts, embeddings)
"""
embeddings = embedding.embed_documents(texts)
return cls.__from(
texts, embeddings, embedding, metadatas, metric, trees, n... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
9f819fb5da00-9 | text_embedding_pairs = list(zip(texts, text_embeddings))
db = Annoy.from_embeddings(text_embedding_pairs, embeddings)
"""
texts = [t[0] for t in text_embeddings]
embeddings = [t[1] for t in text_embeddings]
return cls.__from(
texts, embeddings, embedding, meta... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
9f819fb5da00-10 | Args:
folder_path: folder path to load index, docstore,
and index_to_docstore_id from.
embeddings: Embeddings to use when generating queries.
"""
path = Path(folder_path)
# load index separately since it is not picklable
annoy = dependable_annoy_im... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
0fc245448f98-0 | Source code for langchain.vectorstores.typesense
"""Wrapper around Typesense vector search"""
from __future__ import annotations
import uuid
from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple, Union
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings
fro... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html |
0fc245448f98-1 | typesense_client: Client,
embedding: Embeddings,
*,
typesense_collection_name: Optional[str] = None,
text_key: str = "text",
):
"""Initialize with Typesense client."""
try:
from typesense import Client
except ImportError:
raise ValueErr... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html |
0fc245448f98-2 | for _id, vec, text, metadata in zip(_ids, embedded_texts, texts, _metadatas)
]
def _create_collection(self, num_dim: int) -> None:
fields = [
{"name": "vec", "type": "float[]", "num_dim": num_dim},
{"name": f"{self._text_key}", "type": "string"},
{"name": ".*", "t... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html |
0fc245448f98-3 | return [doc["id"] for doc in docs]
[docs] def similarity_search_with_score(
self,
query: str,
k: int = 10,
filter: Optional[str] = "",
) -> List[Tuple[Document, float]]:
"""Return typesense documents most similar to query, along with scores.
Args:
query... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html |
0fc245448f98-4 | ) -> List[Document]:
"""Return typesense documents most similar to query.
Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 10.
Minimum 10 results would be returned.
filter: typesense filter_by expression ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html |
0fc245448f98-5 | "Please install it with `pip install typesense`."
)
node = {
"host": host,
"port": str(port),
"protocol": protocol,
}
typesense_api_key = typesense_api_key or get_from_env(
"typesense_api_key", "TYPESENSE_API_KEY"
)
clie... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html |
87b9971f5e44-0 | Source code for langchain.vectorstores.pinecone
"""Wrapper around Pinecone vector database."""
from __future__ import annotations
import logging
import uuid
from typing import Any, Callable, Iterable, List, Optional, Tuple
import numpy as np
from langchain.docstore.document import Document
from langchain.embeddings.bas... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
87b9971f5e44-1 | f"client should be an instance of pinecone.index.Index, "
f"got {type(index)}"
)
self._index = index
self._embedding_function = embedding_function
self._text_key = text_key
self._namespace = namespace
[docs] def add_texts(
self,
texts: Itera... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
87b9971f5e44-2 | self,
query: str,
k: int = 4,
filter: Optional[dict] = None,
namespace: Optional[str] = None,
) -> List[Tuple[Document, float]]:
"""Return pinecone documents most similar to query, along with scores.
Args:
query: Text to look up documents similar to.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
87b9971f5e44-3 | """Return pinecone documents most similar to query.
Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
filter: Dictionary of argument(s) to filter on metadata
namespace: Namespace to search in. Default will search i... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
87b9971f5e44-4 | lambda_mult: Number between 0 and 1 that determines the degree
of diversity among the results with 0 corresponding
to maximum diversity and 1 to minimum diversity.
Defaults to 0.5.
Returns:
List of Documents selected by maximal ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
87b9971f5e44-5 | k: Number of Documents to return. Defaults to 4.
fetch_k: Number of Documents to fetch to pass to MMR algorithm.
lambda_mult: Number between 0 and 1 that determines the degree
of diversity among the results with 0 corresponding
to maximum diversity... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
87b9971f5e44-6 | embeddings = OpenAIEmbeddings()
pinecone = Pinecone.from_texts(
texts,
embeddings,
index_name="langchain-demo"
)
"""
try:
import pinecone
except ImportError:
raise ValueError(
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
87b9971f5e44-7 | else:
metadata = [{} for _ in range(i, i_end)]
for j, line in enumerate(lines_batch):
metadata[j][text_key] = line
to_upsert = zip(ids_batch, embeds, metadata)
# upsert to Pinecone
index.upsert(vectors=list(to_upsert), namespace=namespace)
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
6b6892ddfe63-0 | Source code for langchain.vectorstores.tigris
from __future__ import annotations
import itertools
from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple
from langchain.embeddings.base import Embeddings
from langchain.schema import Document
from langchain.vectorstores import VectorStore
if TYPE_CHECKING:... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tigris.html |
6b6892ddfe63-1 | metadatas: Optional list of metadatas associated with the texts.
ids: Optional list of ids for documents.
Ids will be autogenerated if not provided.
kwargs: vectorstore specific parameters
Returns:
List of ids from adding the texts into the vectorstore.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tigris.html |
6b6892ddfe63-2 | vector=vector, k=k, filter_by=filter
)
docs: List[Tuple[Document, float]] = []
for r in result:
docs.append(
(
Document(
page_content=r.doc["text"], metadata=r.doc.get("metadata")
),
r... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tigris.html |
6b6892ddfe63-3 | "text": t,
"embeddings": e or [],
"metadata": m or {},
}
if _id:
doc["id"] = _id
docs.append(doc)
return docs | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/tigris.html |
381602e71446-0 | Source code for langchain.vectorstores.starrocks
"""Wrapper around open source StarRocks 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
from pydantic import Base... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html |
381602e71446-1 | for idx, datum in enumerate(value):
k = columns[idx][0]
r[k] = datum
result.append(r)
debug_output(result)
cursor.close()
return result
class StarRocksSettings(BaseSettings):
"""StarRocks Client Configuration
Attribute:
StarRocks_host (str) : An URL to connect... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html |
381602e71446-2 | database: str = "default"
table: str = "langchain"
def __getitem__(self, item: str) -> Any:
return getattr(self, item)
class Config:
env_file = ".env"
env_prefix = "starrocks_"
env_file_encoding = "utf-8"
[docs]class StarRocks(VectorStore):
"""Wrapper around StarRocks vec... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html |
381602e71446-3 | self.pgbar = lambda x, **kwargs: x
super().__init__()
if config is not None:
self.config = config
else:
self.config = StarRocksSettings()
assert self.config
assert self.config.host and self.config.port
assert self.config.column_map and self.config.... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html |
381602e71446-4 | def _build_insert_sql(self, transac: Iterable, column_names: Iterable[str]) -> str:
ks = ",".join(column_names)
embed_tuple_index = tuple(column_names).index(
self.config.column_map["embedding"]
)
_data = []
for n in transac:
n = ",".join(
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html |
381602e71446-5 | metadata: Optional column data to be inserted
Returns:
List of ids from adding the texts into the VectorStore.
"""
# Embed and create the documents
ids = ids or [sha1(t.encode("utf-8")).hexdigest() for t in texts]
colmap_ = self.config.column_map
transac = []
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html |
381602e71446-6 | return []
[docs] @classmethod
def from_texts(
cls,
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[Dict[Any, Any]]] = None,
config: Optional[StarRocksSettings] = None,
text_ids: Optional[Iterable[str]] = None,
batch_size: int = 32,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html |
381602e71446-7 | _repr += f"\033[1musername: {self.config.username}\033[0m\n\nTable Schema:\n"
width = 25
fields = 3
_repr += "-" * (width * fields + 1) + "\n"
columns = ["name", "type", "key"]
_repr += f"|\033[94m{columns[0]:24s}\033[0m|\033[96m{columns[1]:24s}"
_repr += f"\033[0m|\033[9... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html |
381602e71446-8 | q_str = f"""
SELECT {self.config.column_map['document']},
{self.config.column_map['metadata']},
cosine_similarity_norm(array<float>[{q_emb_str}],
{self.config.column_map['embedding']}) as dist
FROM {self.config.database}.{self.config.table}
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html |
381602e71446-9 | """Perform a similarity search with StarRocks by vectors
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 No... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html |
381602e71446-10 | where_str (Optional[str], optional): where condition string.
Defaults to None.
NOTE: Please do not let end-user to fill this and always be aware
of SQL injection. When dealing with metadatas, remember to
use `{self.metadata... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html |
d2ff981ad89c-0 | Source code for langchain.vectorstores.vectara
"""Wrapper around Vectara vector database."""
from __future__ import annotations
import json
import logging
import os
from hashlib import md5
from typing import Any, Iterable, List, Optional, Tuple, Type
import requests
from pydantic import Field
from langchain.embeddings.... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
d2ff981ad89c-1 | or self._vectara_api_key is None
):
logging.warning(
"Cant find Vectara credentials, customer_id or corpus_id in "
"environment."
)
else:
logging.debug(f"Using corpus id {self._vectara_corpus_id}")
self._session = requests.Sessi... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
d2ff981ad89c-2 | f"{response.status_code}, reason {response.reason}, text "
f"{response.text}"
)
return False
return True
def _index_doc(self, doc: dict) -> bool:
request: dict[str, Any] = {}
request["customer_id"] = self._vectara_customer_id
request["corpus_id... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
d2ff981ad89c-3 | metadatas = [{} for _ in texts]
doc = {
"document_id": doc_id,
"metadataJson": json.dumps({"source": "langchain"}),
"parts": [
{"text": text, "metadataJson": json.dumps(md)}
for text, md in zip(texts, metadatas)
],
}
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
d2ff981ad89c-4 | {
"query": [
{
"query": query,
"start": 0,
"num_results": k,
"context_config": {
"sentences_before": n_sentence_context,
"sentences_... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
d2ff981ad89c-5 | self,
query: str,
k: int = 5,
lambda_val: float = 0.025,
filter: Optional[str] = None,
n_sentence_context: int = 0,
**kwargs: Any,
) -> List[Document]:
"""Return Vectara documents most similar to query, along with scores.
Args:
query: Text ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
d2ff981ad89c-6 | Example:
.. code-block:: python
from langchain import Vectara
vectara = Vectara.from_texts(
texts,
vectara_customer_id=customer_id,
vectara_corpus_id=corpus_id,
vectara_api_key=api_key,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
d2ff981ad89c-7 | ) -> None:
"""Add text to the Vectara vectorstore.
Args:
texts (List[str]): The text
metadatas (List[dict]): Metadata dicts, must line up with existing store
"""
self.vectorstore.add_texts(texts, metadatas) | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
2c2730649d55-0 | Source code for langchain.vectorstores.hologres
"""VectorStore wrapper around a Hologres database."""
from __future__ import annotations
import json
import logging
import uuid
from typing import Any, Dict, Iterable, List, Optional, Tuple, Type
from langchain.docstore.document import Document
from langchain.embeddings.b... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html |
2c2730649d55-1 | '{"embedding":{"algorithm":"Graph",
"distance_method":"SquaredEuclidean",
"build_params":{"min_flush_proxima_row_count" : 1,
"min_compaction_proxima_row_count" : 1,
"max_total_size_to_merge_mb" : 2000}}}');"""
)
self.conn.commit()
def get_by_id(self, id: str) -> List[Tuple]:
statement = (
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html |
2c2730649d55-2 | params.append(key)
params.append(val)
filter_clause = "where " + " and ".join(conjuncts)
sql = (
f"select document, metadata::text, "
f"pm_approx_squared_euclidean_distance(array{json.dumps(embedding)}"
f"::float4[], embedding) as distance from"
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html |
2c2730649d55-3 | self.connection_string = connection_string
self.ndims = ndims
self.table_name = table_name
self.embedding_function = embedding_function
self.pre_delete_table = pre_delete_table
self.logger = logger or logging.getLogger(__name__)
self.__post_init__()
def __post_init__(... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html |
2c2730649d55-4 | embedding_function=embedding_function,
ndims=ndims,
table_name=table_name,
pre_delete_table=pre_delete_table,
)
store.add_embeddings(
texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs
)
return store
[docs] def ad... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html |
2c2730649d55-5 | List of ids from adding the texts into the vectorstore.
"""
if ids is None:
ids = [str(uuid.uuid1()) for _ in texts]
embeddings = self.embedding_function.embed_documents(list(texts))
if not metadatas:
metadatas = [{} for _ in texts]
self.add_embeddings(tex... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html |
2c2730649d55-6 | Returns:
List of Documents most similar to the query vector.
"""
docs_and_scores = self.similarity_search_with_score_by_vector(
embedding=embedding, k=k, filter=filter
)
return [doc for doc, _ in docs_and_scores]
[docs] def similarity_search_with_score(
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html |
2c2730649d55-7 | ]
return docs
[docs] @classmethod
def from_texts(
cls: Type[Hologres],
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
ndims: int = ADA_TOKEN_COUNT,
table_name: str = _LANGCHAIN_DEFAULT_TABLE_NAME,
ids: Optional[List... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html |
2c2730649d55-8 | Return VectorStore initialized from documents and embeddings.
Postgres connection string is required
"Either pass it as a parameter
or set the HOLOGRES_CONNECTION_STRING environment variable.
Example:
.. code-block:: python
from langchain import Hologres
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html |
2c2730649d55-9 | embedding_function=embedding,
pre_delete_table=pre_delete_table,
)
return store
[docs] @classmethod
def get_connection_string(cls, kwargs: Dict[str, Any]) -> str:
connection_string: str = get_from_dict_or_env(
data=kwargs,
key="connection_string",
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html |
2c2730649d55-10 | ndims=ndims,
table_name=table_name,
**kwargs,
)
[docs] @classmethod
def connection_string_from_db_params(
cls,
host: str,
port: int,
database: str,
user: str,
password: str,
) -> str:
"""Return connection string from data... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/hologres.html |
780aeb929fc5-0 | Source code for langchain.vectorstores.redis
"""Wrapper around Redis vector database."""
from __future__ import annotations
import json
import logging
import uuid
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
Literal,
Mapping,
Optional,
Tuple,
Type,... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
780aeb929fc5-1 | "Redis cannot be used as a vector database without RediSearch >=2.4"
"Please head to https://redis.io/docs/stack/search/quick_start/"
"to know more about installing the RediSearch module within Redis Stack."
)
logging.error(error_message)
raise ValueError(error_message)
def _check_index_exis... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
780aeb929fc5-2 | index_name: str,
embedding_function: Callable,
content_key: str = "content",
metadata_key: str = "metadata",
vector_key: str = "content_vector",
relevance_score_fn: Optional[
Callable[[float], float]
] = _default_relevance_score,
**kwargs: Any,
):
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
780aeb929fc5-3 | if not _check_index_exists(self.client, self.index_name):
# Define schema
schema = (
TextField(name=self.content_key),
TextField(name=self.metadata_key),
VectorField(
self.vector_key,
"FLAT",
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
780aeb929fc5-4 | prefix = _redis_prefix(self.index_name)
# Get keys or ids from kwargs
# Other vectorstores use ids
keys_or_ids = kwargs.get("keys", kwargs.get("ids"))
# Write data to redis
pipeline = self.client.pipeline(transaction=False)
for i, text in enumerate(texts):
# U... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
780aeb929fc5-5 | [docs] def similarity_search_limit_score(
self, query: str, k: int = 4, score_threshold: float = 0.2, **kwargs: Any
) -> List[Document]:
"""
Returns the most similar indexed documents to the query text within the
score_threshold range.
Args:
query (str): The qu... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
780aeb929fc5-6 | return (
Query(base_query)
.return_fields(*return_fields)
.sort_by("vector_score")
.paging(0, k)
.dialect(2)
)
[docs] def similarity_search_with_score(
self, query: str, k: int = 4
) -> List[Tuple[Document, float]]:
"""Return doc... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
780aeb929fc5-7 | 0 is dissimilar, 1 is most similar.
"""
if self.relevance_score_fn is None:
raise ValueError(
"relevance_score_fn must be provided to"
" Redis constructor to normalize scores"
)
docs_and_scores = self.similarity_search_with_score(query, k=k... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
780aeb929fc5-8 | )
"""
redis_url = get_from_dict_or_env(kwargs, "redis_url", "REDIS_URL")
if "redis_url" in kwargs:
kwargs.pop("redis_url")
# Name of the search index if not given
if not index_name:
index_name = uuid.uuid4().hex
# Create instance
instance =... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
780aeb929fc5-9 | Example:
.. code-block:: python
from langchain.vectorstores import Redis
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
redisearch = RediSearch.from_texts(
texts,
embedd... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
780aeb929fc5-10 | except ValueError as e:
raise ValueError(f"Your redis connected error: {e}")
# Check if index exists
try:
client.delete(*ids)
logger.info("Entries deleted")
return True
except: # noqa: E722
# ids does not exist
return False... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
780aeb929fc5-11 | [docs] @classmethod
def from_existing_index(
cls,
embedding: Embeddings,
index_name: str,
content_key: str = "content",
metadata_key: str = "metadata",
vector_key: str = "content_vector",
**kwargs: Any,
) -> Redis:
"""Connect to an existing Redi... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
780aeb929fc5-12 | return RedisVectorStoreRetriever(vectorstore=self, **kwargs)
class RedisVectorStoreRetriever(VectorStoreRetriever, BaseModel):
vectorstore: Redis
search_type: str = "similarity"
k: int = 4
score_threshold: float = 0.4
class Config:
"""Configuration for this pydantic object."""
arbitr... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
780aeb929fc5-13 | ) -> List[str]:
"""Add documents to vectorstore."""
return await self.vectorstore.aadd_documents(documents, **kwargs) | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis.html |
c50bc8e67d91-0 | Source code for langchain.vectorstores.zilliz
from __future__ import annotations
import logging
from typing import Any, List, Optional
from langchain.embeddings.base import Embeddings
from langchain.vectorstores.milvus import Milvus
logger = logging.getLogger(__name__)
[docs]class Zilliz(Milvus):
def _create_index(... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html |
c50bc8e67d91-1 | "Failed to create an index on collection: %s", self.collection_name
)
raise e
[docs] @classmethod
def from_texts(
cls,
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
collection_name: str = "LangChainCollecti... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html |
c50bc8e67d91-2 | """
vector_db = cls(
embedding_function=embedding,
collection_name=collection_name,
connection_args=connection_args,
consistency_level=consistency_level,
index_params=index_params,
search_params=search_params,
drop_old=drop_old,... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html |
81787403ca09-0 | Source code for langchain.vectorstores.supabase
from __future__ import annotations
import uuid
from itertools import repeat
from typing import (
TYPE_CHECKING,
Any,
Iterable,
List,
Optional,
Tuple,
Type,
Union,
)
import numpy as np
from langchain.docstore.document import Document
from la... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
81787403ca09-1 | embedding: Embeddings,
table_name: str,
query_name: Union[str, None] = None,
) -> None:
"""Initialize with supabase client."""
try:
import supabase # noqa: F401
except ImportError:
raise ValueError(
"Could not import supabase python pa... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
81787403ca09-2 | """Return VectorStore initialized from texts and embeddings."""
if not client:
raise ValueError("Supabase client is required.")
if not table_name:
raise ValueError("Supabase document table_name is required.")
embeddings = embedding.embed_documents(texts)
ids = [st... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
81787403ca09-3 | ) -> List[Tuple[Document, float]]:
vectors = self._embedding.embed_documents([query])
return self.similarity_search_by_vector_with_relevance_scores(vectors[0], k)
[docs] def similarity_search_by_vector_with_relevance_scores(
self, query: List[float], k: int
) -> List[Tuple[Document, float... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
81787403ca09-4 | ),
)
for search in res.data
if search.get("content")
]
return match_result
@staticmethod
def _texts_to_documents(
texts: Iterable[str],
metadatas: Optional[Iterable[dict[Any, Any]]] = None,
) -> List[Document]:
"""Return list of Doc... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
81787403ca09-5 | if len(result.data) == 0:
raise Exception("Error inserting: No rows added")
# VectorStore.add_vectors returns ids as strings
ids = [str(i.get("id")) for i in result.data if i.get("id")]
id_list.extend(ids)
return id_list
[docs] def max_marginal_relevance_se... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
81787403ca09-6 | matched_embeddings,
k=k,
lambda_mult=lambda_mult,
)
filtered_documents = [matched_documents[i] for i in mmr_selected]
return filtered_documents
[docs] def max_marginal_relevance_search(
self,
query: str,
k: int = 4,
fetch_k: int = 20,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
81787403ca09-7 | SELECT
id,
content,
metadata,
embedding,
1 -(docstore.embedding <=> query_embedding) AS similarity
FROM
docstore
ORDER BY
docstore.embedding <=> query_embedding
LIMIT match... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
1a0d391f3655-0 | Source code for langchain.vectorstores.docarray.in_memory
"""Wrapper around in-memory storage."""
from __future__ import annotations
from typing import Any, Dict, List, Literal, Optional
from langchain.embeddings.base import Embeddings
from langchain.vectorstores.docarray.base import (
DocArrayIndex,
_check_doc... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/in_memory.html |
1a0d391f3655-1 | [docs] @classmethod
def from_texts(
cls,
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[Dict[Any, Any]]] = None,
**kwargs: Any,
) -> DocArrayInMemorySearch:
"""Create an DocArrayInMemorySearch store and insert data.
Args:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/in_memory.html |
ab7be1d45063-0 | Source code for langchain.vectorstores.docarray.hnsw
"""Wrapper around Hnswlib store."""
from __future__ import annotations
from typing import Any, List, Literal, Optional
from langchain.embeddings.base import Embeddings
from langchain.vectorstores.docarray.base import (
DocArrayIndex,
_check_docarray_import,
)... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html |
ab7be1d45063-1 | "cosine", "ip", and "l2". Defaults to "cosine".
max_elements (int): Maximum number of vectors that can be stored.
Defaults to 1024.
index (bool): Whether an index should be built for this field.
Defaults to True.
ef_construction (int): defines a constr... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html |
ab7be1d45063-2 | work_dir: Optional[str] = None,
n_dim: Optional[int] = None,
**kwargs: Any,
) -> DocArrayHnswSearch:
"""Create an DocArrayHnswSearch store and insert data.
Args:
texts (List[str]): Text data.
embedding (Embeddings): Embedding function.
metadatas (O... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html |
6f3ec2414715-0 | Source code for langchain.utilities.powerbi
"""Wrapper around a Power BI endpoint."""
from __future__ import annotations
import asyncio
import logging
import os
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Union
import aiohttp
import requests
from aiohttp import ServerTimeoutError
from pydanti... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
6f3ec2414715-1 | """Fix the table names."""
return [fix_table_name(table) for table in table_names]
@root_validator(pre=True, allow_reuse=True)
def token_or_credential_present(cls, values: Dict[str, Any]) -> Dict[str, Any]:
"""Validate that at least one of token and credentials is present."""
if "token" ... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
6f3ec2414715-2 | "Could not get a token from the supplied credentials."
) from exc
raise ClientAuthenticationError("No credential or token supplied.")
[docs] def get_table_names(self) -> Iterable[str]:
"""Get names of tables available."""
return self.table_names
[docs] def get_schemas(self)... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
6f3ec2414715-3 | if isinstance(table_names, str) and table_names != "":
if table_names not in self.table_names:
_LOGGER.warning("Table %s not found in dataset.", table_names)
return None
return [fix_table_name(table_names)]
return self.table_names
def _... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
6f3ec2414715-4 | tables_todo = self._get_tables_todo(tables_requested)
await asyncio.gather(*[self._aget_schema(table) for table in tables_todo])
return self._get_schema_for_tables(tables_requested)
def _get_schema(self, table: str) -> None:
"""Get the schema for a table."""
try:
result =... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
6f3ec2414715-5 | self.schemas[table] = "unknown"
def _create_json_content(self, command: str) -> dict[str, Any]:
"""Create the json content for the request."""
return {
"queries": [{"query": rf"{command}"}],
"impersonatedUserName": self.impersonated_user_name,
"serializerSettings"... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
6f3ec2414715-6 | json_contents: List[Dict[str, Union[str, int, float]]],
table_name: Optional[str] = None,
) -> str:
"""Converts a JSON object to a markdown table."""
output_md = ""
headers = json_contents[0].keys()
for header in headers:
header.replace("[", ".").replace("]", "")
if table_name:
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
dd9db3efc645-0 | Source code for langchain.utilities.bing_search
"""Util that calls Bing Search.
In order to set this up, follow instructions at:
https://levelup.gitconnected.com/api-tutorial-how-to-use-bing-web-search-api-in-python-4165d5592a7e
"""
from typing import Dict, List
import requests
from pydantic import BaseModel, Extra, ro... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html |
dd9db3efc645-1 | bing_subscription_key = get_from_dict_or_env(
values, "bing_subscription_key", "BING_SUBSCRIPTION_KEY"
)
values["bing_subscription_key"] = bing_subscription_key
bing_search_url = get_from_dict_or_env(
values,
"bing_search_url",
"BING_SEARCH_URL",
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html |
dd9db3efc645-2 | "snippet": result["snippet"],
"title": result["name"],
"link": result["url"],
}
metadata_results.append(metadata_result)
return metadata_results | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html |
f9af61f9ffb6-0 | Source code for langchain.utilities.serpapi
"""Chain that calls SerpAPI.
Heavily borrowed from https://github.com/ofirpress/self-ask
"""
import os
import sys
from typing import Any, Dict, Optional, Tuple
import aiohttp
from pydantic import BaseModel, Extra, Field, root_validator
from langchain.utils import get_from_dic... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html |
f9af61f9ffb6-1 | aiosession: Optional[aiohttp.ClientSession] = None
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
arbitrary_types_allowed = True
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python packag... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html |
f9af61f9ffb6-2 | """Use aiohttp to run query through SerpAPI and return the results async."""
def construct_url_and_params() -> Tuple[str, Dict[str, str]]:
params = self.get_params(query)
params["source"] = "python"
if self.serpapi_api_key:
params["serp_api_key"] = self.serpap... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html |
f9af61f9ffb6-3 | toret = res["answer_box"]["answer"]
elif "answer_box" in res.keys() and "snippet" in res["answer_box"].keys():
toret = res["answer_box"]["snippet"]
elif (
"answer_box" in res.keys()
and "snippet_highlighted_words" in res["answer_box"].keys()
):
tor... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html |
0a1d2b3a0427-0 | Source code for langchain.utilities.awslambda
"""Util that calls Lambda."""
import json
from typing import Any, Dict, Optional
from pydantic import BaseModel, Extra, root_validator
[docs]class LambdaWrapper(BaseModel):
"""Wrapper for AWS Lambda SDK.
Docs for using:
1. pip install boto3
2. Create a lambd... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/awslambda.html |
0a1d2b3a0427-1 | answer = json.loads(payload_string)["body"]
except StopIteration:
return "Failed to parse response from Lambda"
if answer is None or answer == "":
# We don't want to return the assumption alone if answer is empty
return "Request failed."
else:
retu... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/awslambda.html |
b0922af55c9f-0 | Source code for langchain.utilities.bash
"""Wrapper around subprocess to run commands."""
from __future__ import annotations
import platform
import re
import subprocess
from typing import TYPE_CHECKING, List, Union
from uuid import uuid4
if TYPE_CHECKING:
import pexpect
def _lazy_import_pexpect() -> pexpect:
""... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bash.html |
b0922af55c9f-1 | # Set the custom prompt
process.sendline("PS1=" + prompt)
process.expect_exact(prompt, timeout=10)
return process
[docs] def run(self, commands: Union[str, List[str]]) -> str:
"""Run commands and return final output."""
if isinstance(commands, str):
commands = [com... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bash.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.