id stringlengths 14 15 | text stringlengths 35 2.51k | source stringlengths 61 154 |
|---|---|---|
582e0941f8e0-3 | run_id_ = str(run_id)
llm_run = self.run_map.get(run_id_)
if llm_run is None or llm_run.run_type != RunTypeEnum.llm:
raise TracerException("No LLM Run found to be traced")
llm_run.error = repr(error)
llm_run.end_time = datetime.utcnow()
self._end_trace(llm_run)
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/base.html |
582e0941f8e0-4 | """End a trace for a chain run."""
if not run_id:
raise TracerException("No run_id provided for on_chain_end callback.")
chain_run = self.run_map.get(str(run_id))
if chain_run is None or chain_run.run_type != RunTypeEnum.chain:
raise TracerException("No chain Run found to... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/base.html |
582e0941f8e0-5 | parent_run_id_ = str(parent_run_id) if parent_run_id else None
execution_order = self._get_execution_order(parent_run_id_)
tool_run = Run(
id=run_id,
parent_run_id=parent_run_id,
serialized=serialized,
inputs={"input": input_str},
extra=kwargs,... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/base.html |
582e0941f8e0-6 | tool_run = self.run_map.get(str(run_id))
if tool_run is None or tool_run.run_type != RunTypeEnum.tool:
raise TracerException("No tool Run found to be traced")
tool_run.error = repr(error)
tool_run.end_time = datetime.utcnow()
self._end_trace(tool_run)
self._on_tool_er... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/base.html |
582e0941f8e0-7 | retrieval_run = self.run_map.get(str(run_id))
if retrieval_run is None or retrieval_run.run_type != RunTypeEnum.retriever:
raise TracerException("No retriever Run found to be traced")
retrieval_run.error = repr(error)
retrieval_run.end_time = datetime.utcnow()
self._end_trace... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/base.html |
582e0941f8e0-8 | """Process the LLM Run upon error."""
def _on_chain_start(self, run: Run) -> None:
"""Process the Chain Run upon start."""
def _on_chain_end(self, run: Run) -> None:
"""Process the Chain Run."""
def _on_chain_error(self, run: Run) -> None:
"""Process the Chain Run upon error."""
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/base.html |
e5e161b1da14-0 | Source code for langchain.callbacks.tracers.run_collector
"""A tracer that collects all nested runs in a list."""
from typing import Any, List, Optional, Union
from uuid import UUID
from langchain.callbacks.tracers.base import BaseTracer
from langchain.callbacks.tracers.schemas import Run
[docs]class RunCollectorCallba... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/run_collector.html |
1ba31767b458-0 | Source code for langchain.docstore.in_memory
"""Simple in memory docstore in the form of a dict."""
from typing import Dict, Union
from langchain.docstore.base import AddableMixin, Docstore
from langchain.docstore.document import Document
[docs]class InMemoryDocstore(Docstore, AddableMixin):
"""Simple in memory doc... | https://api.python.langchain.com/en/latest/_modules/langchain/docstore/in_memory.html |
5e4dc0e3138c-0 | Source code for langchain.docstore.wikipedia
"""Wrapper around wikipedia API."""
from typing import Union
from langchain.docstore.base import Docstore
from langchain.docstore.document import Document
[docs]class Wikipedia(Docstore):
"""Wrapper around wikipedia API."""
def __init__(self) -> None:
"""Chec... | https://api.python.langchain.com/en/latest/_modules/langchain/docstore/wikipedia.html |
84f388b9755d-0 | Source code for langchain.docstore.arbitrary_fn
from typing import Callable, Union
from langchain.docstore.base import Docstore
from langchain.schema import Document
[docs]class DocstoreFn(Docstore):
"""
Langchain Docstore via arbitrary lookup function.
This is useful when:
* it's expensive to construc... | https://api.python.langchain.com/en/latest/_modules/langchain/docstore/arbitrary_fn.html |
72795652a2ce-0 | Source code for langchain.docstore.base
"""Interface to access to place that stores documents."""
from abc import ABC, abstractmethod
from typing import Dict, Union
from langchain.docstore.document import Document
[docs]class Docstore(ABC):
"""Interface to access to place that stores documents."""
[docs] @abstra... | https://api.python.langchain.com/en/latest/_modules/langchain/docstore/base.html |
2c7b530146da-0 | Source code for langchain.vectorstores.utils
"""Utility functions for working with vectors and vectorstores."""
from typing import List
import numpy as np
from langchain.math_utils import cosine_similarity
[docs]def maximal_marginal_relevance(
query_embedding: np.ndarray,
embedding_list: list,
lambda_mult: ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/utils.html |
1450a24e10b4-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 |
1450a24e10b4-1 | 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 connection args used for
this class comes ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
1450a24e10b4-2 | the ca.pem path.
server_pem_path (str): If use tls one-way authentication, need to
write the server.pem path.
server_name (str): If use tls, need to write the common name.
consistency_level (str): The consistency level to use for a collection.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
1450a24e10b4-3 | corresponding to the user.
secure (bool): Default is false. If set to true, tls will be enabled.
client_key_path (str): If use tls two-way authentication, need to
write the client.key path.
client_pem_path (str): If use tls two-way authentication, need to
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
1450a24e10b4-4 | "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": "L2", "params": {}},
}
self.embedding_func = embedd... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
1450a24e10b4-5 | 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 import MilvusException, connections
# Grab the connection arguments that are used for c... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/milvus.html |
1450a24e10b4-6 | 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 |
1450a24e10b4-7 | 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 |
1450a24e10b4-8 | 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 |
1450a24e10b4-9 | 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 |
1450a24e10b4-10 | 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 |
1450a24e10b4-11 | 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 |
1450a24e10b4-12 | 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 |
1450a24e10b4-13 | 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 |
1450a24e10b4-14 | 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 |
1450a24e10b4-15 | # 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 |
1450a24e10b4-16 | 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 |
1450a24e10b4-17 | 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 |
1450a24e10b4-18 | )
# 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 |
1450a24e10b4-19 | "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 |
877f2af6693a-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 |
877f2af6693a-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 |
877f2af6693a-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 |
f51a7d6f708f-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 |
f51a7d6f708f-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 |
f51a7d6f708f-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 |
f51a7d6f708f-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 |
f51a7d6f708f-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 |
f51a7d6f708f-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 |
956921057284-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 |
956921057284-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 |
956921057284-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 |
956921057284-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 |
7084ea178ec9-0 | Source code for langchain.vectorstores.weaviate
"""Wrapper around weaviate vector database."""
from __future__ import annotations
import datetime
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Type
from uuid import uuid4
import numpy as np
from langchain.docstore.document import Document
from ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
7084ea178ec9-1 | if weaviate_api_key is not None
else None
)
client = weaviate.Client(weaviate_url, auth_client_secret=auth)
return client
def _default_score_normalizer(val: float) -> float:
return 1 - 1 / (1 + np.exp(val))
def _json_serializable(value: Any) -> Any:
if isinstance(value, datetime.datetime):
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
7084ea178ec9-2 | )
if not isinstance(client, weaviate.Client):
raise ValueError(
f"client should be an instance of weaviate.Client, got {type(client)}"
)
self._client = client
self._index_name = index_name
self._embedding = embedding
self._text_key = text_k... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
7084ea178ec9-3 | if self._embedding is not None:
vector = self._embedding.embed_documents([text])[0]
else:
vector = None
batch.add_data_object(
data_object=data_properties,
class_name=self._index_name,
uui... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
7084ea178ec9-4 | if kwargs.get("search_distance"):
content["certainty"] = kwargs.get("search_distance")
query_obj = self._client.query.get(self._index_name, self._query_attrs)
if kwargs.get("where_filter"):
query_obj = query_obj.with_where(kwargs.get("where_filter"))
if kwargs.get("additi... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
7084ea178ec9-5 | docs.append(Document(page_content=text, metadata=res))
return docs
[docs] def max_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... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
7084ea178ec9-6 | **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:
embedding: Embedding to look up documents similar to.
k... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
7084ea178ec9-7 | return docs
[docs] def similarity_search_with_score(
self, query: str, k: int = 4, **kwargs: Any
) -> List[Tuple[Document, float]]:
"""
Return list of documents most similar to the query
text and cosine distance in float for each.
Lower score represents more similarity.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
7084ea178ec9-8 | return docs_and_scores
def _similarity_search_with_relevance_scores(
self,
query: str,
k: int = 4,
**kwargs: Any,
) -> List[Tuple[Document, float]]:
"""Return docs and relevance scores, normalized on a scale from 0 to 1.
0 is dissimilar, 1 is most similar.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
7084ea178ec9-9 | weaviate = Weaviate.from_texts(
texts,
embeddings,
weaviate_url="http://localhost:8080"
)
"""
client = _create_weaviate_client(**kwargs)
from weaviate.util import get_valid_uuid
index_name = kwargs.get("index_nam... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
7084ea178ec9-10 | "class_name": index_name,
}
if embeddings is not None:
params["vector"] = embeddings[i]
batch.add_data_object(**params)
batch.flush()
relevance_score_fn = kwargs.get("relevance_score_fn")
by_text: bool = kwargs.get("by_text"... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
4934b106acc0-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 |
4934b106acc0-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 |
4934b106acc0-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 |
4934b106acc0-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 |
4934b106acc0-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 |
4934b106acc0-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 |
4934b106acc0-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 |
4934b106acc0-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 |
4934b106acc0-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 |
4934b106acc0-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 |
4934b106acc0-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 |
fb3b6c178a9e-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 |
fb3b6c178a9e-1 | r = {}
for idx, datum in enumerate(value):
k = columns[idx][0]
r[k] = datum
result.append(r)
debug_output(result)
cursor.close()
return result
[docs]class StarRocksSettings(BaseSettings):
"""StarRocks Client Configuration
Attribute:
StarRocks_host (str... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html |
fb3b6c178a9e-2 | "metadata": "metadata",
}
database: str = "default"
table: str = "langchain"
def __getitem__(self, item: str) -> Any:
return getattr(self, item)
[docs] class Config:
env_file = ".env"
env_prefix = "starrocks_"
env_file_encoding = "utf-8"
[docs]class StarRocks(VectorSto... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html |
fb3b6c178a9e-3 | except ImportError:
# Just in case if tqdm is not installed
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.con... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html |
fb3b6c178a9e-4 | [docs] def escape_str(self, value: str) -> str:
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)
embed_tuple_index = tuple(column_names).index(
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html |
fb3b6c178a9e-5 | Args:
texts: Iterable of strings to add to the VectorStore.
ids: Optional list of ids to associate with the texts.
batch_size: Batch size of insertion
metadata: Optional column data to be inserted
Returns:
List of ids from adding the texts into the Vec... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html |
fb3b6c178a9e-6 | return [i for i in ids]
except Exception as e:
logger.error(f"\033[91m\033[1m{type(e)}\033[0m \033[95m{str(e)}\033[0m")
return []
[docs] @classmethod
def from_texts(
cls,
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[Dict[Any, An... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html |
fb3b6c178a9e-7 | Returns:
repr: string to show connection info and data schema
"""
_repr = f"\033[92m\033[1m{self.config.database}.{self.config.table} @ "
_repr += f"{self.config.host}:{self.config.port}\033[0m\n\n"
_repr += f"\033[1musername: {self.config.username}\033[0m\n\nTable Schema:\n"... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html |
fb3b6c178a9e-8 | ) -> str:
q_emb_str = ",".join(map(str, q_emb))
if where_str:
where_str = f"WHERE {where_str}"
else:
where_str = ""
q_str = f"""
SELECT {self.config.column_map['document']},
{self.config.column_map['metadata']},
cosine... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html |
fb3b6c178a9e-9 | self,
embedding: List[float],
k: int = 4,
where_str: Optional[str] = None,
**kwargs: Any,
) -> List[Document]:
"""Perform a similarity search with StarRocks by vectors
Args:
query (str): query string
k (int, optional): Top K neighbors to retrie... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/starrocks.html |
fb3b6c178a9e-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/starrocks.html |
c580523be8b9-0 | Source code for langchain.vectorstores.faiss
"""Wrapper around FAISS vector database."""
from __future__ import annotations
import math
import os
import pickle
import uuid
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple
import numpy as np
from langchain.docstore.base imp... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
c580523be8b9-1 | return faiss
def _default_relevance_score_fn(score: float) -> float:
"""Return a similarity score on a scale [0, 1]."""
# The 'correct' relevance function
# may differ depending on a few things, including:
# - the distance / similarity metric used by the VectorStore
# - the scale of your embeddings ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
c580523be8b9-2 | self._normalize_L2 = normalize_L2
def __add(
self,
texts: Iterable[str],
embeddings: Iterable[List[float]],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
**kwargs: Any,
) -> List[str]:
if not isinstance(self.docstore, AddableMixi... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
c580523be8b9-3 | return [_id for _, _id, _ in full_info]
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
**kwargs: Any,
) -> List[str]:
"""Run more texts through the embeddings and add to the vectorstore.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
c580523be8b9-4 | ids: Optional list of unique IDs.
Returns:
List of ids from adding the texts into the vectorstore.
"""
if not isinstance(self.docstore, AddableMixin):
raise ValueError(
"If trying to add texts, the underlying docstore should support "
f"add... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
c580523be8b9-5 | vector = np.array([embedding], dtype=np.float32)
if self._normalize_L2:
faiss.normalize_L2(vector)
scores, indices = self.index.search(vector, k if filter is None else fetch_k)
docs = []
for j, i in enumerate(indices[0]):
if i == -1:
# This happens... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
c580523be8b9-6 | Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.
fetch_k: (Optional[int]) Number of Documents to fetch before filtering.
Defau... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
c580523be8b9-7 | )
return [doc for doc, _ in docs_and_scores]
[docs] def similarity_search(
self,
query: str,
k: int = 4,
filter: Optional[Dict[str, Any]] = None,
fetch_k: int = 20,
**kwargs: Any,
) -> List[Document]:
"""Return docs most similar to query.
Ar... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
c580523be8b9-8 | k: Number of Documents to return. Defaults to 4.
fetch_k: Number of Documents to fetch before filtering to
pass to MMR algorithm.
lambda_mult: Number between 0 and 1 that determines the degree
of diversity among the results with 0 corresponding
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
c580523be8b9-9 | selected_indices = [indices[0][i] for i in mmr_selected]
selected_scores = [scores[0][i] for i in mmr_selected]
docs_and_scores = []
for i, score in zip(selected_indices, selected_scores):
if i == -1:
# This happens when not enough docs are returned.
c... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
c580523be8b9-10 | Returns:
List of Documents selected by maximal marginal relevance.
"""
docs_and_scores = self.max_marginal_relevance_search_with_score_by_vector(
embedding, k=k, fetch_k=fetch_k, lambda_mult=lambda_mult, filter=filter
)
return [doc for doc, _ in docs_and_scores]
[... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
c580523be8b9-11 | [docs] def merge_from(self, target: FAISS) -> None:
"""Merge another FAISS object with the current one.
Add the target FAISS to the current one.
Args:
target: FAISS object you wish to merge into the current one
Returns:
None.
"""
if not isinstan... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
c580523be8b9-12 | ) -> FAISS:
faiss = dependable_faiss_import()
index = faiss.IndexFlatL2(len(embeddings[0]))
vector = np.array(embeddings, dtype=np.float32)
if normalize_L2:
faiss.normalize_L2(vector)
index.add(vector)
documents = []
if ids is None:
ids = [... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
c580523be8b9-13 | faiss = FAISS.from_texts(texts, embeddings)
"""
embeddings = embedding.embed_documents(texts)
return cls.__from(
texts,
embeddings,
embedding,
metadatas=metadatas,
ids=ids,
**kwargs,
)
[docs] @classmethod
def ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
c580523be8b9-14 | """Save FAISS index, docstore, and index_to_docstore_id to disk.
Args:
folder_path: folder path to save index, docstore,
and index_to_docstore_id to.
index_name: for saving with a specific index file name
"""
path = Path(folder_path)
path.mkdir(exi... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
c580523be8b9-15 | )
# load docstore and index_to_docstore_id
with open(path / "{index_name}.pkl".format(index_name=index_name), "rb") as f:
docstore, index_to_docstore_id = pickle.load(f)
return cls(embeddings.embed_query, index, docstore, index_to_docstore_id)
def _similarity_search_with_relevanc... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html |
173f0a856c90-0 | Source code for langchain.vectorstores.chroma
"""Wrapper around ChromaDB embeddings platform."""
from __future__ import annotations
import logging
import uuid
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple, Type
import numpy as np
from langchain.docstore.document import Document
from langc... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
173f0a856c90-1 | embeddings = OpenAIEmbeddings()
vectorstore = Chroma("langchain_store", embeddings)
"""
_LANGCHAIN_DEFAULT_COLLECTION_NAME = "langchain"
def __init__(
self,
collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,
embedding_function: Optional[Embeddings] = None,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
173f0a856c90-2 | @xor_args(("query_texts", "query_embeddings"))
def __query_collection(
self,
query_texts: Optional[List[str]] = None,
query_embeddings: Optional[List[List[float]]] = None,
n_results: int = 4,
where: Optional[Dict[str, str]] = None,
**kwargs: Any,
) -> List[Documen... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
173f0a856c90-3 | ids = [str(uuid.uuid1()) for _ in texts]
embeddings = None
if self._embedding_function is not None:
embeddings = self._embedding_function.embed_documents(list(texts))
self._collection.upsert(
metadatas=metadatas, embeddings=embeddings, documents=texts, ids=ids
)
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
173f0a856c90-4 | Returns:
List of Documents most similar to the query vector.
"""
results = self.__query_collection(
query_embeddings=embedding, n_results=k, where=filter
)
return _results_to_docs(results)
[docs] def similarity_search_with_score(
self,
query: st... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
173f0a856c90-5 | return self.similarity_search_with_score(query, k, **kwargs)
[docs] def max_marginal_relevance_search_by_vector(
self,
embedding: List[float],
k: int = DEFAULT_K,
fetch_k: int = 20,
lambda_mult: float = 0.5,
filter: Optional[Dict[str, str]] = None,
**kwargs: An... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/chroma.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.