id stringlengths 14 16 | text stringlengths 36 2.73k | source stringlengths 49 117 |
|---|---|---|
0e81fc1d074e-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
0e81fc1d074e-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
0e81fc1d074e-2 | f"{response.text}"
)
return False
return True
def _index_doc(self, doc_id: str, text: str, metadata: dict) -> bool:
request: dict[str, Any] = {}
request["customer_id"] = self._vectara_customer_id
request["corpus_id"] = self._vectara_corpus_id
request["... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
0e81fc1d074e-3 | ids = [md5(text.encode("utf-8")).hexdigest() for text in texts]
for i, doc in enumerate(texts):
doc_id = ids[i]
metadata = metadatas[i] if metadatas else {}
succeeded = self._index_doc(doc_id, doc, metadata)
if not succeeded:
self._delete_doc(doc_i... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
0e81fc1d074e-4 | "start": 0,
"num_results": k,
"context_config": {
"sentences_before": 3,
"sentences_after": 3,
},
"corpus_key": [
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
0e81fc1d074e-5 | """Return Vectara 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 5.
filter: Dictionary of argument(s) to filter on metadata. For example a
filter can be "doc.... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
0e81fc1d074e-6 | vectara.add_texts(texts, metadatas)
return vectara
[docs] def as_retriever(self, **kwargs: Any) -> VectaraRetriever:
return VectaraRetriever(vectorstore=self, **kwargs)
class VectaraRetriever(VectorStoreRetriever):
vectorstore: Vectara
search_kwargs: dict = Field(default_factory=lambda: {"alp... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
3f32824058ea-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
3f32824058ea-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
3f32824058ea-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
3f32824058ea-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
3f32824058ea-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
3f32824058ea-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
3f32824058ea-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
3f32824058ea-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html |
e2ce3753dca8-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
e2ce3753dca8-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
e2ce3753dca8-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
e2ce3753dca8-3 | class_name=self._index_name,
uuid=_id,
vector=vector,
)
ids.append(_id)
return ids
[docs] def similarity_search(
self, query: str, k: int = 4, **kwargs: Any
) -> List[Document]:
"""Return docs most similar to query.
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
e2ce3753dca8-4 | if kwargs.get("where_filter"):
query_obj = query_obj.with_where(kwargs.get("where_filter"))
if kwargs.get("additional"):
query_obj = query_obj.with_additional(kwargs.get("additional"))
result = query_obj.with_near_text(content).with_limit(k).do()
if "errors" in result:
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
e2ce3753dca8-5 | k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
Args... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
e2ce3753dca8-6 | 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.
lambda_mult: Number between 0 and 1 that determines the degree
of diversity... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
e2ce3753dca8-7 | raise ValueError(
"_embedding cannot be None for similarity_search_with_score"
)
content: Dict[str, Any] = {"concepts": [query]}
if kwargs.get("search_distance"):
content["certainty"] = kwargs.get("search_distance")
query_obj = self._client.query.get(self.... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
e2ce3753dca8-8 | """
if self._relevance_score_fn is None:
raise ValueError(
"relevance_score_fn must be provided to"
" Weaviate constructor to normalize scores"
)
docs_and_scores = self.similarity_search_with_score(query, k=k, **kwargs)
return [
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
e2ce3753dca8-9 | text_key = "text"
schema = _default_schema(index_name)
attributes = list(metadatas[0].keys()) if metadatas else None
# check whether the index already exists
if not client.schema.contains(schema):
client.schema.create_class(schema)
with client.batch as batch:
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
e2ce3753dca8-10 | relevance_score_fn=relevance_score_fn,
by_text=by_text,
)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html |
6a24d1389937-0 | Source code for langchain.vectorstores.opensearch_vector_search
"""Wrapper around OpenSearch vector database."""
from __future__ import annotations
import uuid
from typing import Any, Dict, Iterable, List, Optional, Tuple
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
6a24d1389937-1 | try:
opensearch = _import_opensearch()
client = opensearch(opensearch_url, **kwargs)
except ValueError as e:
raise ValueError(
f"OpenSearch client string provided is not in proper format. "
f"Got error: {e} "
)
return client
def _validate_embeddings_and_bu... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
6a24d1389937-2 | request = {
"_op_type": "index",
"_index": index_name,
vector_field: embeddings[i],
text_field: text,
"metadata": metadata,
"_id": _id,
}
requests.append(request)
ids.append(_id)
bulk(client, requests)
client.indices... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
6a24d1389937-3 | "parameters": {"ef_construction": ef_construction, "m": m},
},
}
}
},
}
def _default_approximate_search_query(
query_vector: List[float],
k: int = 4,
vector_field: str = "vector_field",
) -> Dict:
"""For Approximate k-NN Search, this is the def... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
6a24d1389937-4 | return search_query
def _default_script_query(
query_vector: List[float],
space_type: str = "l2",
pre_filter: Dict = MATCH_ALL_QUERY,
vector_field: str = "vector_field",
) -> Dict:
"""For Script Scoring Search, this is the default query."""
return {
"query": {
"script_score":... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
6a24d1389937-5 | source = __get_painless_scripting_source(space_type, query_vector)
return {
"query": {
"script_score": {
"query": pre_filter,
"script": {
"source": source,
"params": {
"field": vector_field,
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
6a24d1389937-6 | """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.
bulk_size: Bulk API request count; Default: 500
Returns:
List ... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
6a24d1389937-7 | text_field,
mapping,
)
[docs] def similarity_search(
self, query: str, k: int = 4, **kwargs: Any
) -> List[Document]:
"""Return docs most similar to query.
By default supports Approximate Search.
Also supports Script Scoring and Painless Scripting.
Args... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
6a24d1389937-8 | pre_filter: script_score query to pre-filter documents before identifying
nearest neighbors; default: {"match_all": {}}
Optional Args for Painless Scripting Search:
search_type: "painless_scripting"; default: "approximate_search"
space_type: "l2Squared", "l1Norm", "cosineSimi... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
6a24d1389937-9 | if search_type == "approximate_search":
boolean_filter = _get_kwargs_value(kwargs, "boolean_filter", {})
subquery_clause = _get_kwargs_value(kwargs, "subquery_clause", "must")
lucene_filter = _get_kwargs_value(kwargs, "lucene_filter", {})
if boolean_filter != {} and lucen... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
6a24d1389937-10 | embedding, space_type, pre_filter, vector_field
)
else:
raise ValueError("Invalid `search_type` provided as an argument")
response = self.client.search(index=self.index_name, body=search_query)
hits = [hit for hit in response["hits"]["hits"][:k]]
documents_with_sc... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
6a24d1389937-11 | vector_field: Document field embeddings are stored in. Defaults to
"vector_field".
text_field: Document field the text of the document is stored in. Defaults
to "text".
Optional Keyword Args for Approximate Search:
engine: "nmslib", "faiss", "lucene"; default: "nm... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
6a24d1389937-12 | _validate_embeddings_and_bulk_size(len(embeddings), bulk_size)
dim = len(embeddings[0])
# Get the index name from either from kwargs or ENV Variable
# before falling back to random generation
index_name = get_from_dict_or_env(
kwargs, "index_name", "OPENSEARCH_INDEX_NAME", de... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
6a24d1389937-13 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html |
55ceecff6475-0 | Source code for langchain.vectorstores.qdrant
"""Wrapper around Qdrant vector database."""
from __future__ import annotations
import uuid
import warnings
from hashlib import md5
from operator import itemgetter
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
Optional,... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
55ceecff6475-1 | """Initialize with necessary components."""
try:
import qdrant_client
except ImportError:
raise ValueError(
"Could not import qdrant-client python package. "
"Please install it with `pip install qdrant-client`."
)
if not isinsta... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
55ceecff6475-2 | )
self._embeddings_function = embeddings
self.embeddings = None
def _embed_query(self, query: str) -> List[float]:
"""Embed query text.
Used to provide backward compatibility with `embedding_function` argument.
Args:
query: Query text.
Returns:
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
55ceecff6475-3 | metadatas: Optional[List[dict]] = None,
**kwargs: Any,
) -> List[str]:
"""Run more texts through the embeddings and add to the vectorstore.
Args:
texts: Iterable of strings to add to the vectorstore.
metadatas: Optional list of metadatas associated with the texts.
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
55ceecff6475-4 | return list(map(itemgetter(0), results))
[docs] def similarity_search_with_score(
self, query: str, k: int = 4, filter: Optional[MetadataFilter] = None
) -> List[Tuple[Document, float]]:
"""Return docs most similar to query.
Args:
query: Text to look up documents similar to.
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
55ceecff6475-5 | Defaults to 20.
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 Do... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
55ceecff6475-6 | 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,
) -> Qdrant:
"""Construct Qdrant wrapper from a list of texts.
Ar... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
55ceecff6475-7 | Default: None
timeout:
Timeout for REST and gRPC API requests.
Default: 5.0 seconds for REST and unlimited for gRPC
host:
Host name of Qdrant service. If url and host are None, set to
'localhost'. Default: None
path:
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
55ceecff6475-8 | try:
import qdrant_client
except ImportError:
raise ValueError(
"Could not import qdrant-client python package. "
"Please install it with `pip install qdrant-client`."
)
from qdrant_client.http import models as rest
# Just do a ... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
55ceecff6475-9 | client=client,
collection_name=collection_name,
embeddings=embedding,
content_payload_key=content_payload_key,
metadata_payload_key=metadata_payload_key,
)
@classmethod
def _build_payloads(
cls,
texts: Iterable[str],
metadatas: Opti... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
55ceecff6475-10 | elif isinstance(value, list):
for _value in value:
if isinstance(_value, dict):
out.extend(self._build_condition(f"{key}[]", _value))
else:
out.extend(self._build_condition(f"{key}", _value))
else:
out.append(
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html |
87b9087694bf-0 | Source code for langchain.vectorstores.tair
"""Wrapper around Tair Vector."""
from __future__ import annotations
import json
import logging
import uuid
from typing import Any, Iterable, List, Optional, Type
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings
from langchain.... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
87b9087694bf-1 | data_type: str,
**kwargs: Any,
) -> bool:
index = self.client.tvs_get_index(self.index_name)
if index is not None:
logger.info("Index already exists")
return False
self.client.tvs_create_index(
self.index_name,
dim,
distance... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
87b9087694bf-2 | Args:
query (str): The query text for which to find similar documents.
k (int): The number of documents to return. Default is 4.
Returns:
List[Document]: A list of documents that are most similar to the query text.
"""
# Creates embedding vector from user quer... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
87b9087694bf-3 | if "tair_url" in kwargs:
kwargs.pop("tair_url")
distance_type = tairvector.DistanceMetric.InnerProduct
if "distance_type" in kwargs:
distance_type = kwargs.pop("distance_typ")
index_type = tairvector.IndexType.HNSW
if "index_type" in kwargs:
index_type... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
87b9087694bf-4 | cls,
documents: List[Document],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
index_name: str = "langchain",
content_key: str = "content",
metadata_key: str = "metadata",
**kwargs: Any,
) -> Tair:
texts = [d.page_content for d in docum... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
87b9087694bf-5 | # index not exist
logger.info("Index does not exist")
return False
return True
[docs] @classmethod
def from_existing_index(
cls,
embedding: Embeddings,
index_name: str = "langchain",
content_key: str = "content",
metadata_key: str = "metadat... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html |
e9617b158892-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, Tuple
from langchain.docstore.document import Document
from langchain.embeddings.bas... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
e9617b158892-1 | # and attributes.
[docs]class ElasticVectorSearch(VectorStore, ABC):
"""Wrapper around Elasticsearch as a vector database.
To connect to an Elasticsearch instance that does not require
login credentials, pass the Elasticsearch URL and index name along with the
embedding object to the constructor.
Ex... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
e9617b158892-2 | Example:
.. code-block:: python
from langchain import ElasticVectorSearch
from langchain.embeddings import OpenAIEmbeddings
embedding = OpenAIEmbeddings()
elastic_host = "cluster_id.region_id.gcp.cloud.es.io"
elasticsearch_url = f"https://username:pass... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
e9617b158892-3 | except ValueError as e:
raise ValueError(
f"Your elasticsearch client string is mis-formatted. Got error: {e} "
)
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
refresh_indices: bool = True,
**k... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
e9617b158892-4 | request = {
"_op_type": "index",
"_index": self.index_name,
"vector": embeddings[i],
"text": text,
"metadata": metadata,
"_id": _id,
}
ids.append(_id)
requests.append(request)
bulk... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
e9617b158892-5 | response = self.client.search(index=self.index_name, query=script_query, size=k)
hits = [hit for hit in response["hits"]["hits"]]
docs_and_scores = [
(
Document(
page_content=hit["_source"]["text"],
metadata=hit["_source"]["metadata"],
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
e9617b158892-6 | )
index_name = index_name or uuid.uuid4().hex
vectorsearch = cls(elasticsearch_url, index_name, embedding, **kwargs)
vectorsearch.add_texts(
texts, metadatas=metadatas, refresh_indices=refresh_indices
)
return vectorsearch
By Harrison Chase
© Copyright 2023... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html |
ba4cfc28c63a-0 | Source code for langchain.vectorstores.annoy
"""Wrapper around Annoy vector database."""
from __future__ import annotations
import os
import pickle
import uuid
from configparser import ConfigParser
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple
import numpy as np
from l... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
ba4cfc28c63a-1 | ):
"""Initialize with necessary components."""
self.embedding_function = embedding_function
self.index = index
self.metric = metric
self.docstore = docstore
self.index_to_docstore_id = index_to_docstore_id
[docs] def add_texts(
self,
texts: Iterable[str... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
ba4cfc28c63a-2 | Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
search_k: inspect up to search_k nodes which defaults
to n_trees * n if not provided
Returns:
List of Documents most similar to the query and score ... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
ba4cfc28c63a-3 | k: Number of Documents to return. Defaults to 4.
search_k: inspect up to search_k nodes which defaults
to n_trees * n if not provided
Returns:
List of Documents most similar to the query and score for each
"""
embedding = self.embedding_function(query)
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
ba4cfc28c63a-4 | Returns:
List of Documents most similar to the embedding.
"""
docs_and_scores = self.similarity_search_with_score_by_index(
docstore_index, k, search_k
)
return [doc for doc, _ in docs_and_scores]
[docs] def similarity_search(
self, query: str, k: int =... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
ba4cfc28c63a-5 | 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 marginal relevance.
"""
idxs = self.index.get_nns_by_vector(
... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
ba4cfc28c63a-6 | 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://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
ba4cfc28c63a-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
ba4cfc28c63a-8 | from langchain import Annoy
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
index = Annoy.from_texts(texts, embeddings)
"""
embeddings = embedding.embed_documents(texts)
return cls.__from(
texts, embedd... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
ba4cfc28c63a-9 | embeddings = OpenAIEmbeddings()
text_embeddings = embeddings.embed_documents(texts)
text_embedding_pairs = list(zip(texts, text_embeddings))
db = Annoy.from_embeddings(text_embedding_pairs, embeddings)
"""
texts = [t[0] for t in text_embeddings]
em... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
ba4cfc28c63a-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
6f1b68c5ab20-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
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
6f1b68c5ab20-1 | 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: Iterable[str],
metadatas: Optional[List[dict]] = None,
ids: Opt... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
6f1b68c5ab20-2 | 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.
k: Number of Documents to r... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
6f1b68c5ab20-3 | 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 in '' namespace.
Returns:
List of Documen... | https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
6f1b68c5ab20-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
6f1b68c5ab20-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html |
2d9fbfd31753-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/in_memory.html |
2d9fbfd31753-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/in_memory.html |
751e2507037c-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html |
751e2507037c-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html |
751e2507037c-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://python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html |
45ca5159bb39-0 | Source code for langchain.output_parsers.structured
from __future__ import annotations
from typing import Any, List
from pydantic import BaseModel
from langchain.output_parsers.format_instructions import STRUCTURED_FORMAT_INSTRUCTIONS
from langchain.output_parsers.json import parse_and_check_json_markdown
from langchai... | https://python.langchain.com/en/latest/_modules/langchain/output_parsers/structured.html |
c1eb1ac874fb-0 | Source code for langchain.output_parsers.pydantic
import json
import re
from typing import Type, TypeVar
from pydantic import BaseModel, ValidationError
from langchain.output_parsers.format_instructions import PYDANTIC_FORMAT_INSTRUCTIONS
from langchain.schema import BaseOutputParser, OutputParserException
T = TypeVar(... | https://python.langchain.com/en/latest/_modules/langchain/output_parsers/pydantic.html |
c1eb1ac874fb-1 | @property
def _type(self) -> str:
return "pydantic"
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/output_parsers/pydantic.html |
efdfb385e931-0 | Source code for langchain.output_parsers.regex_dict
from __future__ import annotations
import re
from typing import Dict, Optional
from langchain.schema import BaseOutputParser
[docs]class RegexDictParser(BaseOutputParser):
"""Class to parse the output into a dictionary."""
regex_pattern: str = r"{}:\s?([^.'\n'... | https://python.langchain.com/en/latest/_modules/langchain/output_parsers/regex_dict.html |
674c179876a8-0 | Source code for langchain.output_parsers.fix
from __future__ import annotations
from typing import TypeVar
from langchain.base_language import BaseLanguageModel
from langchain.chains.llm import LLMChain
from langchain.output_parsers.prompts import NAIVE_FIX_PROMPT
from langchain.prompts.base import BasePromptTemplate
f... | https://python.langchain.com/en/latest/_modules/langchain/output_parsers/fix.html |
f7a6b32c062b-0 | Source code for langchain.output_parsers.list
from __future__ import annotations
from abc import abstractmethod
from typing import List
from langchain.schema import BaseOutputParser
[docs]class ListOutputParser(BaseOutputParser):
"""Class to parse the output of an LLM call to a list."""
@property
def _type(... | https://python.langchain.com/en/latest/_modules/langchain/output_parsers/list.html |
123677289dc7-0 | Source code for langchain.output_parsers.rail_parser
from __future__ import annotations
from typing import Any, Dict
from langchain.schema import BaseOutputParser
[docs]class GuardrailsOutputParser(BaseOutputParser):
guard: Any
@property
def _type(self) -> str:
return "guardrails"
[docs] @classme... | https://python.langchain.com/en/latest/_modules/langchain/output_parsers/rail_parser.html |
e4b1e1de5191-0 | Source code for langchain.output_parsers.retry
from __future__ import annotations
from typing import TypeVar
from langchain.base_language import BaseLanguageModel
from langchain.chains.llm import LLMChain
from langchain.prompts.base import BasePromptTemplate
from langchain.prompts.prompt import PromptTemplate
from lang... | https://python.langchain.com/en/latest/_modules/langchain/output_parsers/retry.html |
e4b1e1de5191-1 | chain = LLMChain(llm=llm, prompt=prompt)
return cls(parser=parser, retry_chain=chain)
[docs] def parse_with_prompt(self, completion: str, prompt_value: PromptValue) -> T:
try:
parsed_completion = self.parser.parse(completion)
except OutputParserException:
new_completio... | https://python.langchain.com/en/latest/_modules/langchain/output_parsers/retry.html |
e4b1e1de5191-2 | ) -> RetryWithErrorOutputParser[T]:
chain = LLMChain(llm=llm, prompt=prompt)
return cls(parser=parser, retry_chain=chain)
[docs] def parse_with_prompt(self, completion: str, prompt_value: PromptValue) -> T:
try:
parsed_completion = self.parser.parse(completion)
except Outp... | https://python.langchain.com/en/latest/_modules/langchain/output_parsers/retry.html |
87a1ba4aad8d-0 | Source code for langchain.output_parsers.regex
from __future__ import annotations
import re
from typing import Dict, List, Optional
from langchain.schema import BaseOutputParser
[docs]class RegexParser(BaseOutputParser):
"""Class to parse the output into a dictionary."""
regex: str
output_keys: List[str]
... | https://python.langchain.com/en/latest/_modules/langchain/output_parsers/regex.html |
aba4401dbbbd-0 | Source code for langchain.retrievers.zep
from __future__ import annotations
from typing import TYPE_CHECKING, List, Optional
from langchain.schema import BaseRetriever, Document
if TYPE_CHECKING:
from zep_python import SearchResult
[docs]class ZepRetriever(BaseRetriever):
"""A Retriever implementation for the Z... | https://python.langchain.com/en/latest/_modules/langchain/retrievers/zep.html |
aba4401dbbbd-1 | )
for r in results
if r.message
]
[docs] def get_relevant_documents(self, query: str) -> List[Document]:
from zep_python import SearchPayload
payload: SearchPayload = SearchPayload(text=query)
results: List[SearchResult] = self.zep_client.search_memory(
... | https://python.langchain.com/en/latest/_modules/langchain/retrievers/zep.html |
721f606eb7b8-0 | Source code for langchain.retrievers.azure_cognitive_search
"""Retriever wrapper for Azure Cognitive Search."""
from __future__ import annotations
import json
from typing import Dict, List, Optional
import aiohttp
import requests
from pydantic import BaseModel, Extra, root_validator
from langchain.schema import BaseRet... | https://python.langchain.com/en/latest/_modules/langchain/retrievers/azure_cognitive_search.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.