id stringlengths 14 16 | text stringlengths 31 2.73k | source stringlengths 56 166 |
|---|---|---|
817a0012aebc-8 | cls,
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
bulk_size: int = 500,
**kwargs: Any,
) -> OpenSearchVectorSearch:
"""Construct OpenSearchVectorSearch wrapper from raw documents.
Example:
.. code-block:: python
... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
817a0012aebc-9 | Higher values lead to more accurate graph but slower indexing speed;
default: 512
m: Number of bidirectional links created for each new element. Large impact
on memory consumption. Between 2 and 100; default: 16
Keyword Args for Script Scoring or Painless Scripting:
... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
817a0012aebc-10 | mapping = _default_text_mapping(
dim, engine, space_type, ef_search, ef_construction, m, vector_field
)
else:
mapping = _default_scripting_text_mapping(dim)
client.indices.create(index=index_name, body=mapping)
_bulk_ingest_embeddings(
client, ... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
5d58b9273603-0 | Source code for langchain.vectorstores.base
"""Interface for vector stores."""
from __future__ import annotations
import asyncio
from abc import ABC, abstractmethod
from functools import partial
from typing import Any, Dict, Iterable, List, Optional, Type, TypeVar
from pydantic import BaseModel, Field, root_validator
f... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/base.html |
5d58b9273603-1 | documents (List[Document]: Documents to add to the vectorstore.
Returns:
List[str]: List of IDs of the added texts.
"""
# TODO: Handle the case where the user doesn't provide ids on the Collection
texts = [doc.page_content for doc in documents]
metadatas = [doc.metada... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/base.html |
5d58b9273603-2 | return await asyncio.get_event_loop().run_in_executor(None, func)
[docs] def similarity_search_by_vector(
self, embedding: List[float], k: int = 4, **kwargs: Any
) -> List[Document]:
"""Return docs most similar to embedding vector.
Args:
embedding: Embedding to look up documen... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/base.html |
5d58b9273603-3 | List of Documents selected by maximal marginal relevance.
"""
raise NotImplementedError
[docs] async def amax_marginal_relevance_search(
self, query: str, k: int = 4, fetch_k: int = 20
) -> List[Document]:
"""Return docs selected using the maximal marginal relevance."""
# ... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/base.html |
5d58b9273603-4 | cls: Type[VST],
documents: List[Document],
embedding: Embeddings,
**kwargs: Any,
) -> VST:
"""Return VectorStore initialized from documents and embeddings."""
texts = [d.page_content for d in documents]
metadatas = [d.metadata for d in documents]
return cls.fr... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/base.html |
5d58b9273603-5 | return VectorStoreRetriever(vectorstore=self, **kwargs)
class VectorStoreRetriever(BaseRetriever, BaseModel):
vectorstore: VectorStore
search_type: str = "similarity"
search_kwargs: dict = Field(default_factory=dict)
class Config:
"""Configuration for this pydantic object."""
arbitrary_t... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/base.html |
5d58b9273603-6 | return docs
def add_documents(self, documents: List[Document], **kwargs: Any) -> List[str]:
"""Add documents to vectorstore."""
return self.vectorstore.add_documents(documents, **kwargs)
async def aadd_documents(
self, documents: List[Document], **kwargs: Any
) -> List[str]:
... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/base.html |
27713943716c-0 | Source code for langchain.vectorstores.faiss
"""Wrapper around FAISS vector database."""
from __future__ import annotations
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 import AddableMixin, Docs... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/faiss.html |
27713943716c-1 | self.index_to_docstore_id = index_to_docstore_id
def __add(
self,
texts: Iterable[str],
embeddings: Iterable[List[float]],
metadatas: Optional[List[dict]] = None,
**kwargs: Any,
) -> List[str]:
if not isinstance(self.docstore, AddableMixin):
raise Valu... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/faiss.html |
27713943716c-2 | **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 associated with the texts.
Returns:
List of ids from addin... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/faiss.html |
27713943716c-3 | texts = [te[0] for te in text_embeddings]
embeddings = [te[1] for te in text_embeddings]
return self.__add(texts, embeddings, metadatas, **kwargs)
[docs] def similarity_search_with_score_by_vector(
self, embedding: List[float], k: int = 4
) -> List[Tuple[Document, float]]:
"""Retu... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/faiss.html |
27713943716c-4 | """
embedding = self.embedding_function(query)
docs = self.similarity_search_with_score_by_vector(embedding, k)
return docs
[docs] def similarity_search_by_vector(
self, embedding: List[float], k: int = 4, **kwargs: Any
) -> List[Document]:
"""Return docs most similar to e... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/faiss.html |
27713943716c-5 | Args:
embedding: Embedding to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
fetch_k: Number of Documents to fetch to pass to MMR algorithm.
Returns:
List of Documents selected by maximal marginal relevance.
"""
_, i... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/faiss.html |
27713943716c-6 | fetch_k: Number of Documents to fetch to pass to MMR algorithm.
Returns:
List of Documents selected by maximal marginal relevance.
"""
embedding = self.embedding_function(query)
docs = self.max_marginal_relevance_search_by_vector(embedding, k, fetch_k)
return docs
[do... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/faiss.html |
27713943716c-7 | cls,
texts: List[str],
embeddings: List[List[float]],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
**kwargs: Any,
) -> FAISS:
faiss = dependable_faiss_import()
index = faiss.IndexFlatL2(len(embeddings[0]))
index.add(np.array(embedding... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/faiss.html |
27713943716c-8 | faiss = FAISS.from_texts(texts, embeddings)
"""
embeddings = embedding.embed_documents(texts)
return cls.__from(texts, embeddings, embedding, metadatas, **kwargs)
[docs] @classmethod
def from_embeddings(
cls,
text_embeddings: List[Tuple[str, List[float]]],
embeddin... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/faiss.html |
27713943716c-9 | path = Path(folder_path)
path.mkdir(exist_ok=True, parents=True)
# save index separately since it is not picklable
faiss = dependable_faiss_import()
faiss.write_index(
self.index, str(path / "{index_name}.faiss".format(index_name=index_name))
)
# save docstore... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/faiss.html |
27713943716c-10 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 18, 2023. | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/faiss.html |
3e145381aeed-0 | Source code for langchain.vectorstores.atlas
"""Wrapper around Atlas by Nomic."""
from __future__ import annotations
import logging
import uuid
from typing import Any, Iterable, List, Optional, Type
import numpy as np
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings
from... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/atlas.html |
3e145381aeed-1 | is_public (bool): Whether your project is publicly accessible.
True by default.
reset_project_if_exists (bool): Whether to reset this project if it
already exists. Default False.
Generally userful during development and testing.
"""
try:
... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/atlas.html |
3e145381aeed-2 | metadatas (Optional[List[dict]], optional): Optional list of metadatas.
ids (Optional[List[str]]): An optional list of ids.
refresh(bool): Whether or not to refresh indices with the updated data.
Default True.
Returns:
List[str]: List of IDs of the added texts... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/atlas.html |
3e145381aeed-3 | else:
if metadatas is None:
data = [
{"text": text, AtlasDB._ATLAS_DEFAULT_ID_FIELD: ids[i]}
for i, text in enumerate(texts)
]
else:
for i, text in enumerate(texts):
metadatas[i]["text"] =... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/atlas.html |
3e145381aeed-4 | """
if self._embedding_function is None:
raise NotImplementedError(
"AtlasDB requires an embedding_function for text similarity search!"
)
_embedding = self._embedding_function.embed_documents([query])[0]
embedding = np.array(_embedding).reshape(1, -1)
... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/atlas.html |
3e145381aeed-5 | ids (Optional[List[str]]): Optional list of document IDs. If None,
ids will be auto created
description (str): A description for your project.
is_public (bool): Whether your project is publicly accessible.
True by default.
reset_project_if_exists (bool... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/atlas.html |
3e145381aeed-6 | ids: Optional[List[str]] = None,
name: Optional[str] = None,
api_key: Optional[str] = None,
persist_directory: Optional[str] = None,
description: str = "A description for your project",
is_public: bool = True,
reset_project_if_exists: bool = False,
index_kwargs: O... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/atlas.html |
3e145381aeed-7 | return cls.from_texts(
name=name,
api_key=api_key,
texts=texts,
embedding=embedding,
metadatas=metadatas,
ids=ids,
description=description,
is_public=is_public,
reset_project_if_exists=reset_project_if_exists,
... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/atlas.html |
fc9312b5fdb5-0 | Source code for langchain.vectorstores.pinecone
"""Wrapper around Pinecone vector database."""
from __future__ import annotations
import uuid
from typing import Any, Callable, Iterable, List, Optional, Tuple
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings
from langchain... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/pinecone.html |
fc9312b5fdb5-1 | self._embedding_function = embedding_function
self._text_key = text_key
self._namespace = namespace
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
namespace: Optional[str] = None,
... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/pinecone.html |
fc9312b5fdb5-2 | 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.
k: Number of Documents to return. Defaults to 4.
filter: Dictionary of arg... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/pinecone.html |
fc9312b5fdb5-3 | List of Documents most similar to the query and score for each
"""
if namespace is None:
namespace = self._namespace
query_obj = self._embedding_function(query)
docs = []
results = self._index.query(
[query_obj],
top_k=k,
include_me... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/pinecone.html |
fc9312b5fdb5-4 | pinecone = Pinecone.from_texts(
texts,
embeddings,
index_name="langchain-demo"
)
"""
try:
import pinecone
except ImportError:
raise ValueError(
"Could not import pinecone python pa... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/pinecone.html |
fc9312b5fdb5-5 | 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)
return cls(index, embedding.embed_query, text_key, namespace)
[docs... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/pinecone.html |
df5f53b93766-0 | Source code for langchain.vectorstores.weaviate
"""Wrapper around weaviate vector database."""
from __future__ import annotations
from typing import Any, Dict, Iterable, List, Optional, Type
from uuid import uuid4
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings
from lan... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/weaviate.html |
df5f53b93766-1 | )
self._client = client
self._index_name = index_name
self._text_key = text_key
self._query_attrs = [self._text_key]
if attributes is not None:
self._query_attrs.extend(attributes)
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas:... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/weaviate.html |
df5f53b93766-2 | content["certainty"] = kwargs.get("search_distance")
query_obj = self._client.query.get(self._index_name, self._query_attrs)
result = query_obj.with_near_text(content).with_limit(k).do()
if "errors" in result:
raise ValueError(f"Error during query: {result['errors']}")
docs =... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/weaviate.html |
df5f53b93766-3 | This is a user-friendly interface that:
1. Embeds documents.
2. Creates a new index for the embeddings in the Weaviate instance.
3. Adds the documents to the newly created Weaviate index.
This is intended to be a quick way to get started.
Example:
.. code-... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/weaviate.html |
df5f53b93766-4 | data_properties = {
text_key: text,
}
if metadatas is not None:
for key in metadatas[i].keys():
data_properties[key] = metadatas[i][key]
_id = get_valid_uuid(uuid4())
# if an embedding strateg... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/weaviate.html |
3619fe051ac5-0 | Source code for langchain.vectorstores.elastic_vector_search
"""Wrapper around Elasticsearch vector database."""
from __future__ import annotations
import uuid
from abc import ABC
from typing import Any, Dict, Iterable, List, Optional
from langchain.docstore.document import Document
from langchain.embeddings.base impor... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
3619fe051ac5-1 | embedding object to the constructor.
Example:
.. code-block:: python
from langchain import ElasticVectorSearch
from langchain.embeddings import OpenAIEmbeddings
embedding = OpenAIEmbeddings()
elastic_vector_search = ElasticVectorSearch(
elastic... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
3619fe051ac5-2 | elastic_host = "cluster_id.region_id.gcp.cloud.es.io"
elasticsearch_url = f"https://username:password@{elastic_host}:9243"
elastic_vector_search = ElasticVectorSearch(
elasticsearch_url=elasticsearch_url,
index_name="test_index",
embedding=embeddin... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
3619fe051ac5-3 | **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 associated with the texts.
refresh_indices: bool to refresh Elasti... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
3619fe051ac5-4 | if refresh_indices:
self.client.indices.refresh(index=self.index_name)
return ids
[docs] def similarity_search(
self, query: str, k: int = 4, **kwargs: Any
) -> List[Document]:
"""Return docs most similar to query.
Args:
query: Text to look up documents sim... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
3619fe051ac5-5 | elastic_vector_search = ElasticVectorSearch.from_texts(
texts,
embeddings,
elasticsearch_url="http://localhost:9200"
)
"""
elasticsearch_url = get_from_dict_or_env(
kwargs, "elasticsearch_url", "ELASTICSEARCH_URL"
... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
3619fe051ac5-6 | }
requests.append(request)
bulk(client, requests)
client.indices.refresh(index=index_name)
return cls(elasticsearch_url, index_name, embedding)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 18, 2023. | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
2339a87a008b-0 | Source code for langchain.vectorstores.qdrant
"""Wrapper around Qdrant vector database."""
from __future__ import annotations
import uuid
from operator import itemgetter
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Type, Union
from langchain.docstore.document import Document
from langchain.e... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/qdrant.html |
2339a87a008b-1 | f"client should be an instance of qdrant_client.QdrantClient, "
f"got {type(client)}"
)
self.client: qdrant_client.QdrantClient = client
self.collection_name = collection_name
self.embedding_function = embedding_function
self.content_payload_key = content_payl... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/qdrant.html |
2339a87a008b-2 | """Return docs most similar to query.
Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
filter: Filter by metadata. Defaults to None.
Returns:
List of Documents most similar to the query.
"""
... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/qdrant.html |
2339a87a008b-3 | ) -> 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: Text to look up documents similar to.
k: Number of Documents to ret... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/qdrant.html |
2339a87a008b-4 | timeout: Optional[float] = None,
host: Optional[str] = None,
path: Optional[str] = None,
collection_name: Optional[str] = None,
distance_func: str = "Cosine",
content_payload_key: str = CONTENT_KEY,
metadata_payload_key: str = METADATA_KEY,
**kwargs: Any,
) ->... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/qdrant.html |
2339a87a008b-5 | Example: service/v1 will result in
http://localhost:6333/service/v1/{qdrant-endpoint} for REST API.
Default: None
timeout:
Timeout for REST and gRPC API requests.
Default: 5.0 seconds for REST and unlimited for gRPC
host:
... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/qdrant.html |
2339a87a008b-6 | embeddings = OpenAIEmbeddings()
qdrant = Qdrant.from_texts(texts, embeddings, "localhost")
"""
try:
import qdrant_client
except ImportError:
raise ValueError(
"Could not import qdrant-client python package. "
"Please install... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/qdrant.html |
2339a87a008b-7 | ),
),
)
return cls(
client=client,
collection_name=collection_name,
embedding_function=embedding.embed_query,
content_payload_key=content_payload_key,
metadata_payload_key=metadata_payload_key,
)
@classmethod
def _bu... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/qdrant.html |
2339a87a008b-8 | rest.FieldCondition(
key=f"{self.metadata_payload_key}.{key}",
match=rest.MatchValue(value=value),
)
for key, value in filter.items()
]
)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Ap... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/qdrant.html |
6a52fdd89e62-0 | Source code for langchain.vectorstores.milvus
"""Wrapper around the Milvus vector database."""
from __future__ import annotations
import uuid
from typing import Any, Iterable, List, Optional, Tuple
import numpy as np
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings
from ... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/milvus.html |
6a52fdd89e62-1 | if not connections.has_connection("default"):
connections.connect(**connection_args)
self.embedding_func = embedding_function
self.collection_name = collection_name
self.text_field = text_field
self.auto_id = False
self.primary_field = None
self.vector_field =... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/milvus.html |
6a52fdd89e62-2 | metadatas: Optional[List[dict]] = None,
partition_name: Optional[str] = None,
timeout: Optional[int] = None,
**kwargs: Any,
) -> List[str]:
"""Insert text data into Milvus.
When using add_texts() it is assumed that a collecton has already
been made and indexed. If met... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/milvus.html |
6a52fdd89e62-3 | # Insert into the collection.
res = self.col.insert(
insert_list, partition_name=partition_name, timeout=timeout
)
# Flush to make sure newly inserted is immediately searchable.
self.col.flush()
return res.primary_keys
def _worker_search(
self,
que... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/milvus.html |
6a52fdd89e62-4 | ret.append(
(
Document(page_content=meta.pop(self.text_field), metadata=meta),
result.distance,
result.id,
)
)
return data[0], ret
[docs] def similarity_search_with_score(
self,
query: str,... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/milvus.html |
6a52fdd89e62-5 | )
return [(x, y) for x, y, _ in result]
[docs] def max_marginal_relevance_search(
self,
query: str,
k: int = 4,
fetch_k: int = 20,
param: Optional[dict] = None,
expr: Optional[str] = None,
partition_names: Optional[List[str]] = None,
round_decim... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/milvus.html |
6a52fdd89e62-6 | # Extract result IDs.
ids = [x for _, _, x in res]
# Get the raw vectors from Milvus.
vectors = self.col.query(
expr=f"{self.primary_field} in {ids}",
output_fields=[self.primary_field, self.vector_field],
)
# Reorganize the results from query to match res... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/milvus.html |
6a52fdd89e62-7 | expr (str, optional): Filtering expression. Defaults to None.
partition_names (List[str], optional): What partitions to search.
Defaults to None.
round_decimal (int, optional): What decimal point to round to.
Defaults to -1.
timeout (int, optional): Ho... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/milvus.html |
6a52fdd89e62-8 | "Please install it with `pip install pymilvus`."
)
# Connect to Milvus instance
if not connections.has_connection("default"):
connections.connect(**kwargs.get("connection_args", {"port": 19530}))
# Determine embedding dim
embeddings = embedding.embed_query(texts[0... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/milvus.html |
6a52fdd89e62-9 | )
else:
fields.append(FieldSchema(key, dtype))
# Find out max length of texts
max_length = 0
for y in texts:
max_length = max(max_length, len(y))
# Create the text field
fields.append(
FieldSchema(text_field, DataType.VA... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/milvus.html |
8e600b6b42bd-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://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/chroma.html |
8e600b6b42bd-1 | def __init__(
self,
collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,
embedding_function: Optional[Embeddings] = None,
persist_directory: Optional[str] = None,
client_settings: Optional[chromadb.config.Settings] = None,
collection_metadata: Optional[Dict] = None,... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/chroma.html |
8e600b6b42bd-2 | Args:
texts (Iterable[str]): Texts to add to the vectorstore.
metadatas (Optional[List[dict]], optional): Optional list of metadatas.
ids (Optional[List[str]], optional): Optional list of IDs.
Returns:
List[str]: List of IDs of the added texts.
"""
... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/chroma.html |
8e600b6b42bd-3 | self,
embedding: List[float],
k: int = 4,
filter: Optional[Dict[str, str]] = None,
**kwargs: Any,
) -> List[Document]:
"""Return docs most similar to embedding vector.
Args:
embedding: Embedding to look up documents similar to.
k: Number of Doc... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/chroma.html |
8e600b6b42bd-4 | )
return _results_to_docs_and_scores(results)
[docs] def max_marginal_relevance_search_by_vector(
self,
embedding: List[float],
k: int = 4,
fetch_k: int = 20,
filter: Optional[Dict[str, str]] = None,
) -> List[Document]:
"""Return docs selected using the ma... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/chroma.html |
8e600b6b42bd-5 | ) -> 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: Text to look up documents similar to.
k: Number of Documents to ret... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/chroma.html |
8e600b6b42bd-6 | ids: Optional[List[str]] = None,
collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,
persist_directory: Optional[str] = None,
client_settings: Optional[chromadb.config.Settings] = None,
**kwargs: Any,
) -> Chroma:
"""Create a Chroma vectorstore from a raw documents.
... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/chroma.html |
8e600b6b42bd-7 | persist_directory: Optional[str] = None,
client_settings: Optional[chromadb.config.Settings] = None,
**kwargs: Any,
) -> Chroma:
"""Create a Chroma vectorstore from a list of documents.
If a persist_directory is specified, the collection will be persisted there.
Otherwise, th... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/chroma.html |
fb8e1e3d27ac-0 | Source code for langchain.vectorstores.deeplake
"""Wrapper around Activeloop Deep Lake."""
from __future__ import annotations
import logging
import uuid
from functools import partial
from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple
import numpy as np
from langchain.docstore.document imp... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/deeplake.html |
fb8e1e3d27ac-1 | returns:
nearest_indices: List, indices of nearest neighbors
"""
# Calculate the distance between the query_vector and all data_vectors
distances = distance_metric_map[distance_metric](query_embedding, data_vectors)
nearest_indices = np.argsort(distances)
nearest_indices = (
nearest_... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/deeplake.html |
fb8e1e3d27ac-2 | vectorstore = DeepLake("langchain_store", embeddings.embed_query)
"""
_LANGCHAIN_DEFAULT_DEEPLAKE_PATH = "mem://langchain"
def __init__(
self,
dataset_path: str = _LANGCHAIN_DEFAULT_DEEPLAKE_PATH,
token: Optional[str] = None,
embedding_function: Optional[Embeddings] = None,
... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/deeplake.html |
fb8e1e3d27ac-3 | )
self.ds.create_tensor(
"metadata",
htype="json",
create_id_tensor=False,
create_sample_info_tensor=False,
create_shape_tensor=False,
chunk_compression="lz4",
)
... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/deeplake.html |
fb8e1e3d27ac-4 | elements = list(zip(text_list, metadatas, ids))
@self._deeplake.compute
def ingest(sample_in: list, sample_out: list) -> None:
text_list = [s[0] for s in sample_in]
embeds: Sequence[Optional[np.ndarray]] = []
if self._embedding_function is not None:
em... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/deeplake.html |
fb8e1e3d27ac-5 | fetch_k: Optional[int] = 20,
filter: Optional[Any[Dict[str, str], Callable, str]] = None,
return_score: Optional[bool] = False,
**kwargs: Any,
) -> Any[List[Document], List[Tuple[Document, float]]]:
"""Return docs most similar to query.
Args:
query: Text to look u... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/deeplake.html |
fb8e1e3d27ac-6 | if len(view) == 0:
return []
if self._embedding_function is None:
view = view.filter(lambda x: query in x["text"].data()["value"])
scores = [1.0] * len(view)
if use_maximal_marginal_relevance:
raise ValueError(
"For MMR sear... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/deeplake.html |
fb8e1e3d27ac-7 | """Return docs most similar to query.
Args:
query: text to embed and run the query on.
k: Number of Documents to return.
Defaults to 4.
query: Text to look up documents similar to.
embedding: Embedding function to use.
Defaults to N... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/deeplake.html |
fb8e1e3d27ac-8 | self,
query: str,
distance_metric: str = "L2",
k: int = 4,
filter: Optional[Dict[str, str]] = None,
) -> List[Tuple[Document, float]]:
"""Run similarity search with Deep Lake with distance returned.
Args:
query (str): Query text to search for.
... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/deeplake.html |
fb8e1e3d27ac-9 | List of Documents selected by maximal marginal relevance.
"""
return self.search(
embedding=embedding,
k=k,
fetch_k=fetch_k,
use_maximal_marginal_relevance=True,
)
[docs] def max_marginal_relevance_search(
self, query: str, k: int = 4, f... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/deeplake.html |
fb8e1e3d27ac-10 | Otherwise, the data will be ephemeral in-memory.
Args:
path (str, pathlib.Path): - The full path to the dataset. Can be:
- Deep Lake cloud path of the form ``hub://username/dataset_name``.
To write to Deep Lake cloud datasets,
ensure that you a... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/deeplake.html |
fb8e1e3d27ac-11 | return deeplake_dataset
[docs] def delete(
self,
ids: Any[List[str], None] = None,
filter: Any[Dict[str, str], None] = None,
delete_all: Any[bool, None] = None,
) -> bool:
"""Delete the entities in the dataset
Args:
ids (Optional[List[str]], optional): ... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/vectorstores/deeplake.html |
b034299e36a3-0 | Source code for langchain.prompts.base
"""BasePrompt schema definition."""
from __future__ import annotations
import json
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Any, Callable, Dict, List, Mapping, Optional, Union
import yaml
from pydantic import BaseModel, Extra, Field, root_val... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/prompts/base.html |
b034299e36a3-1 | except KeyError as e:
raise ValueError(
"Invalid prompt schema; check for mismatched or missing input parameters. "
+ str(e)
)
class StringPromptValue(PromptValue):
text: str
def to_string(self) -> str:
"""Return prompt as string."""
return self.text
d... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/prompts/base.html |
b034299e36a3-2 | "internally, please rename."
)
overall = set(values["input_variables"]).intersection(
values["partial_variables"]
)
if overall:
raise ValueError(
f"Found overlapping input and partial variables: {overall}"
)
return values
[d... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/prompts/base.html |
b034299e36a3-3 | prompt_dict["_type"] = self._prompt_type
return prompt_dict
[docs] def save(self, file_path: Union[Path, str]) -> None:
"""Save the prompt.
Args:
file_path: Path to directory to save prompt to.
Example:
.. code-block:: python
prompt.save(file_path="path... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/prompts/base.html |
fa9c5a0219de-0 | Source code for langchain.prompts.loading
"""Load prompts from disk."""
import importlib
import json
import logging
from pathlib import Path
from typing import Union
import yaml
from langchain.output_parsers.regex import RegexParser
from langchain.prompts.base import BasePromptTemplate
from langchain.prompts.few_shot i... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/prompts/loading.html |
fa9c5a0219de-1 | with open(template_path) as f:
template = f.read()
else:
raise ValueError
# Set the template variable to the extracted variable.
config[var_name] = template
return config
def _load_examples(config: dict) -> dict:
"""Load examples if necessary."""
if isinst... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/prompts/loading.html |
fa9c5a0219de-2 | config = _load_template("prefix", config)
# Load the example prompt.
if "example_prompt_path" in config:
if "example_prompt" in config:
raise ValueError(
"Only one of example_prompt and example_prompt_path should "
"be specified."
)
config[... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/prompts/loading.html |
fa9c5a0219de-3 | with open(file_path) as f:
config = json.load(f)
elif file_path.suffix == ".yaml":
with open(file_path, "r") as f:
config = yaml.safe_load(f)
elif file_path.suffix == ".py":
spec = importlib.util.spec_from_loader(
"prompt", loader=None, origin=str(file_path)
... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/prompts/loading.html |
9e9314483790-0 | Source code for langchain.prompts.chat
"""Chat prompt template."""
from __future__ import annotations
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Any, Callable, List, Sequence, Tuple, Type, Union
from pydantic import BaseModel, Field
from langchain.memory.buffer import get_buffer_str... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/prompts/chat.html |
9e9314483790-1 | """Input variables for this prompt template."""
return [self.variable_name]
class BaseStringMessagePromptTemplate(BaseMessagePromptTemplate, ABC):
prompt: StringPromptTemplate
additional_kwargs: dict = Field(default_factory=dict)
@classmethod
def from_template(cls, template: str, **kwargs: Any) ... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/prompts/chat.html |
9e9314483790-2 | return SystemMessage(content=text, additional_kwargs=self.additional_kwargs)
class ChatPromptValue(PromptValue):
messages: List[BaseMessage]
def to_string(self) -> str:
"""Return prompt as string."""
return get_buffer_string(self.messages)
def to_messages(self) -> List[BaseMessage]:
... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/prompts/chat.html |
9e9314483790-3 | for role, template in string_messages
]
return cls.from_messages(messages)
@classmethod
def from_messages(
cls, messages: Sequence[Union[BaseMessagePromptTemplate, BaseMessage]]
) -> ChatPromptTemplate:
input_vars = set()
for message in messages:
if isinst... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/prompts/chat.html |
f36a562ad443-0 | Source code for langchain.prompts.prompt
"""Prompt schema definition."""
from __future__ import annotations
from pathlib import Path
from string import Formatter
from typing import Any, Dict, List, Union
from pydantic import Extra, root_validator
from langchain.prompts.base import (
DEFAULT_FORMATTER_MAPPING,
S... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/prompts/prompt.html |
f36a562ad443-1 | return DEFAULT_FORMATTER_MAPPING[self.template_format](self.template, **kwargs)
@root_validator()
def template_is_valid(cls, values: Dict) -> Dict:
"""Check that template and input variables are consistent."""
if values["validate_template"]:
all_inputs = values["input_variables"] + l... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/prompts/prompt.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.