id stringlengths 14 15 | text stringlengths 35 2.51k | source stringlengths 61 154 |
|---|---|---|
675f4da9e1d4-2 | def __init__(
self,
embedding: Embeddings,
config: AlibabaCloudOpenSearchSettings,
**kwargs: Any,
) -> None:
try:
from alibabacloud_ha3engine import client, models
from alibabacloud_tea_util import models as util_models
except ImportError:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
675f4da9e1d4-3 | self.config.datasource_name, field_name_map["id"], push_request
)
json_response = json.loads(push_response.body)
if json_response["status"] == "OK":
return [
push_doc["fields"][field_name_map["id"]]
for p... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
675f4da9e1d4-4 | )
if metadata is not None:
for md_key, md_value in metadata.items():
add_doc_fields.__setitem__(
field_name_map[md_key].split(",")[0], md_value
)
add_doc.__setitem__("fields", add_doc_fields)
add_doc.__se... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
675f4da9e1d4-5 | embedding=embedding, search_filter=search_filter, k=k
)
)
[docs] def inner_embedding_query(
self,
embedding: List[float],
search_filter: Optional[Dict[str, Any]] = None,
k: int = 4,
) -> Dict[str, Any]:
def generate_embedding_query() -> str:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
675f4da9e1d4-6 | md_filter_operator = expr[1].strip()
if isinstance(md_value, numbers.Number):
return f"{md_filter_key} {md_filter_operator} {md_value}"
return f'{md_filter_key}{md_filter_operator}"{md_value}"'
def search_data(single_query_str: str) -> Dict[str, Any]:
search_q... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
675f4da9e1d4-7 | self, json_result: Dict[str, Any]
) -> List[Tuple[Document, float]]:
items = json_result["result"]["items"]
query_result_list: List[Tuple[Document, float]] = []
for item in items:
fields = item["fields"]
query_result_list.append(
(
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
675f4da9e1d4-8 | return cls.from_texts(
texts=texts,
embedding=embedding,
metadatas=metadatas,
config=config,
**kwargs,
) | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/alibabacloud_opensearch.html |
ab4b4b0155da-0 | Source code for langchain.vectorstores.base
"""Interface for vector stores."""
from __future__ import annotations
import asyncio
import warnings
from abc import ABC, abstractmethod
from functools import partial
from typing import (
Any,
ClassVar,
Collection,
Dict,
Iterable,
List,
Optional,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
ab4b4b0155da-1 | False otherwise, None if not implemented.
"""
raise NotImplementedError(
"delete_by_id method must be implemented by subclass."
)
[docs] async def aadd_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
**kwargs: Any,
) -... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
ab4b4b0155da-2 | return await self.aadd_texts(texts, metadatas, **kwargs)
[docs] def search(self, query: str, search_type: str, **kwargs: Any) -> List[Document]:
"""Return docs most similar to query using specified search type."""
if search_type == "similarity":
return self.similarity_search(query, **kwar... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
ab4b4b0155da-3 | k: int = 4,
**kwargs: Any,
) -> List[Tuple[Document, float]]:
"""Return docs and relevance scores in the range [0, 1].
0 is dissimilar, 1 is most similar.
Args:
query: input text
k: Number of Documents to return. Defaults to 4.
**kwargs: kwargs to ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
ab4b4b0155da-4 | 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.
"""
raise NotImplementedError
[docs] async def asimilarity_search_with_relevance_scores(
self, ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
ab4b4b0155da-5 | Args:
embedding: Embedding to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
Returns:
List of Documents most similar to the query vector.
"""
raise NotImplementedError
[docs] async def asimilarity_search_by_vector(
se... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
ab4b4b0155da-6 | 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,
lambda_mult: float = 0.5,
**kwargs: Any,
) -> List[Document]:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
ab4b4b0155da-7 | Defaults to 0.5.
Returns:
List of Documents selected by maximal marginal relevance.
"""
raise NotImplementedError
[docs] async def amax_marginal_relevance_search_by_vector(
self,
embedding: List[float],
k: int = 4,
fetch_k: int = 20,
lambda_... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
ab4b4b0155da-8 | texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
**kwargs: Any,
) -> VST:
"""Return VectorStore initialized from texts and embeddings."""
[docs] @classmethod
async def afrom_texts(
cls: Type[VST],
texts: List[str],
embedd... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
ab4b4b0155da-9 | score_threshold = values["search_kwargs"].get("score_threshold")
if (score_threshold is None) or (not isinstance(score_threshold, float)):
raise ValueError(
"`score_threshold` is not specified with a float value(0~1) "
"in `search_kwargs`."
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
ab4b4b0155da-10 | docs_and_similarities = (
await self.vectorstore.asimilarity_search_with_relevance_scores(
query, **self.search_kwargs
)
)
docs = [doc for doc, _ in docs_and_similarities]
elif self.search_type == "mmr":
docs = await self.ve... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html |
660b0473f249-0 | Source code for langchain.vectorstores.clarifai
from __future__ import annotations
import logging
import os
import traceback
from typing import Any, Iterable, List, Optional, Tuple
import requests
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings
from langchain.vectorstor... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html |
660b0473f249-1 | """
try:
from clarifai.auth.helper import DEFAULT_BASE, ClarifaiAuthHelper
from clarifai.client import create_stub
except ImportError:
raise ValueError(
"Could not import clarifai python package. "
"Please install it with `pip install c... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html |
660b0473f249-2 | Args:
text (str): Text to post.
metadata (dict): Metadata to post.
Returns:
str: ID of the input.
"""
try:
from clarifai_grpc.grpc.api import resources_pb2, service_pb2
from clarifai_grpc.grpc.api.status import status_code_pb2
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html |
660b0473f249-3 | to a Clarifai application.
Application use base workflow that create and store embedding for each text.
Make sure you are using a base workflow that is compatible with text
(such as Language Understanding).
Args:
texts (Iterable[str]): Texts to add to the vectorstore.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html |
660b0473f249-4 | Args:
query (str): Query text to search for.
k (int): Number of results to return. Defaults to 4.
filter (Optional[Dict[str, str]]): Filter by metadata.
Defaults to None.
Returns:
List[Document]: List of documents most simmilar to the query text.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html |
660b0473f249-5 | "Post searches failed, status: "
+ post_annotations_searches_response.status.description
)
# Retrieve hits
hits = post_annotations_searches_response.hits
docs_and_scores = []
# Iterate over hits and retrieve metadata and text
for hit in hits:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html |
660b0473f249-6 | user_id: Optional[str] = None,
app_id: Optional[str] = None,
pat: Optional[str] = None,
number_of_docs: Optional[int] = None,
api_base: Optional[str] = None,
**kwargs: Any,
) -> Clarifai:
"""Create a Clarifai vectorstore from a list of texts.
Args:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html |
660b0473f249-7 | api_base: Optional[str] = None,
**kwargs: Any,
) -> Clarifai:
"""Create a Clarifai vectorstore from a list of documents.
Args:
user_id (str): User ID.
app_id (str): App ID.
documents (List[Document]): List of documents to add.
pat (Optional[str... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clarifai.html |
ff094dd4a288-0 | Source code for langchain.vectorstores.cassandra
"""Wrapper around Cassandra vector-store capabilities, based on cassIO."""
from __future__ import annotations
import hashlib
import typing
from typing import Any, Iterable, List, Optional, Tuple, Type, TypeVar
import numpy as np
if typing.TYPE_CHECKING:
from cassandr... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
ff094dd4a288-1 | )
return self._embedding_dimension
def __init__(
self,
embedding: Embeddings,
session: Session,
keyspace: str,
table_name: str,
ttl_seconds: int | None = CASSANDRA_VECTORSTORE_DEFAULT_TTL_SECONDS,
) -> None:
try:
from cassio.vector impo... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
ff094dd4a288-2 | ids: Optional[List[str]] = None,
**kwargs: Any,
) -> List[str]:
"""Run more texts through the embeddings and add to the vectorstore.
Args:
texts (Iterable[str]): Texts to add to the vectorstore.
metadatas (Optional[List[dict]], optional): Optional list of metadatas.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
ff094dd4a288-3 | """Return docs most similar to embedding vector.
No support for `filter` query (on metadata) along with vector search.
Args:
embedding (str): Embedding to look up documents similar to.
k (int): Number of Documents to return. Defaults to 4.
Returns:
List of (Do... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
ff094dd4a288-4 | """Return docs most similar to embedding vector.
No support for `filter` query (on metadata) along with vector search.
Args:
embedding (str): Embedding to look up documents similar to.
k (int): Number of Documents to return. Defaults to 4.
Returns:
List of (Do... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
ff094dd4a288-5 | embedding_vector,
k,
)
# Even though this is a `_`-method,
# it is apparently used by VectorSearch parent class
# in an exposed method (`similarity_search_with_relevance_scores`).
# So we implement it (hmm).
def _similarity_search_with_relevance_scores(
self,
quer... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
ff094dd4a288-6 | metric="cos",
metric_threshold=None,
)
# let the mmr utility pick the *indices* in the above array
mmrChosenIndices = maximal_marginal_relevance(
np.array(embedding, dtype=np.float32),
[pfHit["embedding_vector"] for pfHit in prefetchHits],
k=k,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
ff094dd4a288-7 | return self.max_marginal_relevance_search_by_vector(
embedding_vector,
k,
fetch_k,
lambda_mult=lambda_mult,
)
[docs] @classmethod
def from_texts(
cls: Type[CVST],
texts: List[str],
embedding: Embeddings,
metadatas: Optional[L... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
ff094dd4a288-8 | return cls.from_texts(
texts=texts,
metadatas=metadatas,
embedding=embedding,
session=session,
keyspace=keyspace,
table_name=table_name,
) | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/cassandra.html |
c715afcf2ed1-0 | Source code for langchain.vectorstores.clickhouse
"""Wrapper around open source ClickHouse VectorSearch capability."""
from __future__ import annotations
import json
import logging
from hashlib import sha1
from threading import Thread
from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
from pydantic im... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
c715afcf2ed1-1 | Defaults to 'vector_table'.
metric (str) : Metric to compute distance,
supported are ('angular', 'euclidean', 'manhattan', 'hamming',
'dot'). Defaults to 'angular'.
https://github.com/spotify/annoy/blob/main/src/annoymodule.cc#L149-L169
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
c715afcf2ed1-2 | return getattr(self, item)
[docs] class Config:
env_file = ".env"
env_prefix = "clickhouse_"
env_file_encoding = "utf-8"
[docs]class Clickhouse(VectorStore):
"""Wrapper around ClickHouse vector database
You need a `clickhouse-connect` python package, and a valid account
to connect... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
c715afcf2ed1-3 | assert self.config
assert self.config.host and self.config.port
assert (
self.config.column_map
and self.config.database
and self.config.table
and self.config.metric
)
for k in ["id", "embedding", "document", "metadata", "uuid"]:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
c715afcf2ed1-4 | """
self.dim = dim
self.BS = "\\"
self.must_escape = ("\\", "'")
self.embedding_function = embedding
self.dist_order = "ASC" # Only support ConsingDistance and L2Distance
# Create a connection to clickhouse
self.client = get_client(
host=self.config.h... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
c715afcf2ed1-5 | [docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
batch_size: int = 32,
ids: Optional[Iterable[str]] = None,
**kwargs: Any,
) -> List[str]:
"""Insert more texts through the embeddings and add to the VectorStore.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
c715afcf2ed1-6 | transac.append(v)
if len(transac) == batch_size:
if t:
t.join()
t = Thread(target=self._insert, args=[transac, keys])
t.start()
transac = []
if len(transac) > 0:
if t:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
c715afcf2ed1-7 | Returns:
ClickHouse Index
"""
ctx = cls(embedding, config, **kwargs)
ctx.add_texts(texts, ids=text_ids, batch_size=batch_size, metadatas=metadatas)
return ctx
def __repr__(self) -> str:
"""Text representation for ClickHouse Vector Store, prints backends, username
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
c715afcf2ed1-8 | else:
where_str = ""
settings_strs = []
if self.config.index_query_params:
for k in self.config.index_query_params:
settings_strs.append(f"SETTING {k}={self.config.index_query_params[k]}")
q_str = f"""
SELECT {self.config.column_map['document']... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
c715afcf2ed1-9 | self,
embedding: List[float],
k: int = 4,
where_str: Optional[str] = None,
**kwargs: Any,
) -> List[Document]:
"""Perform a similarity search with ClickHouse by vectors
Args:
query (str): query string
k (int, optional): Top K neighbors to retri... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/clickhouse.html |
c715afcf2ed1-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/clickhouse.html |
40c8d5d27205-0 | Source code for langchain.vectorstores.vectara
"""Wrapper around Vectara vector database."""
from __future__ import annotations
import json
import logging
import os
from hashlib import md5
from typing import Any, Iterable, List, Optional, Tuple, Type
import requests
from pydantic import Field
from langchain.embeddings.... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
40c8d5d27205-1 | or self._vectara_api_key is None
):
logging.warning(
"Cant find Vectara credentials, customer_id or corpus_id in "
"environment."
)
else:
logging.debug(f"Using corpus id {self._vectara_corpus_id}")
self._session = requests.Sessi... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
40c8d5d27205-2 | f"{response.status_code}, reason {response.reason}, text "
f"{response.text}"
)
return False
return True
def _index_doc(self, doc: dict) -> bool:
request: dict[str, Any] = {}
request["customer_id"] = self._vectara_customer_id
request["corpus_id... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
40c8d5d27205-3 | metadatas = [{} for _ in texts]
doc = {
"document_id": doc_id,
"metadataJson": json.dumps({"source": "langchain"}),
"parts": [
{"text": text, "metadataJson": json.dumps(md)}
for text, md in zip(texts, metadatas)
],
}
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
40c8d5d27205-4 | {
"query": [
{
"query": query,
"start": 0,
"num_results": k,
"context_config": {
"sentences_before": n_sentence_context,
"sentences_... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
40c8d5d27205-5 | self,
query: str,
k: int = 5,
lambda_val: float = 0.025,
filter: Optional[str] = None,
n_sentence_context: int = 0,
**kwargs: Any,
) -> List[Document]:
"""Return Vectara documents most similar to query, along with scores.
Args:
query: Text ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
40c8d5d27205-6 | Example:
.. code-block:: python
from langchain import Vectara
vectara = Vectara.from_texts(
texts,
vectara_customer_id=customer_id,
vectara_corpus_id=corpus_id,
vectara_api_key=api_key,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
40c8d5d27205-7 | ) -> None:
"""Add text to the Vectara vectorstore.
Args:
texts (List[str]): The text
metadatas (List[dict]): Metadata dicts, must line up with existing store
"""
self.vectorstore.add_texts(texts, metadatas) | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html |
281ddf2b554a-0 | Source code for langchain.vectorstores.lancedb
"""Wrapper around LanceDB vector database"""
from __future__ import annotations
import uuid
from typing import Any, Iterable, List, Optional
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings
from langchain.vectorstores.base i... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html |
281ddf2b554a-1 | self._id_key = id_key
self._text_key = text_key
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
**kwargs: Any,
) -> List[str]:
"""Turn texts into embedding and add it to the database... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html |
281ddf2b554a-2 | """
embedding = self._embedding.embed_query(query)
docs = self._connection.search(embedding).limit(k).to_df()
return [
Document(
page_content=row[self._text_key],
metadata=row[docs.columns != self._text_key],
)
for _, row in doc... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html |
010488e7d439-0 | Source code for langchain.vectorstores.azuresearch
"""Wrapper around Azure Cognitive Search."""
from __future__ import annotations
import base64
import json
import logging
import uuid
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
Optional,
Tuple,
Type,
)
im... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
010488e7d439-1 | key: str,
index_name: str,
embedding_function: Callable,
semantic_configuration_name: Optional[str] = None,
) -> SearchClient:
from azure.core.credentials import AzureKeyCredential
from azure.core.exceptions import ResourceNotFoundError
from azure.identity import DefaultAzureCredential
from ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
010488e7d439-2 | type=SearchFieldDataType.String,
searchable=True,
retrievable=True,
),
]
# Vector search configuration
vector_search = VectorSearch(
algorithm_configurations=[
VectorSearchAlgorithmConfiguration(
name="de... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
010488e7d439-3 | **kwargs: Any,
):
"""Initialize with necessary components."""
# Initialize base class
self.embedding_function = embedding_function
self.client = _get_search_client(
azure_search_endpoint,
azure_search_key,
index_name,
embedding_function... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
010488e7d439-4 | # Check if all documents were successfully uploaded
if not all([r.succeeded for r in response]):
raise Exception(response)
# Reset data
data = []
# Considering case where data is an exact multiple of batch-size entries
if len(data) == 0... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
010488e7d439-5 | """
docs_and_scores = self.vector_search_with_score(
query, k=k, filters=kwargs.get("filters", None)
)
return [doc for doc, _ in docs_and_scores]
[docs] def vector_search_with_score(
self, query: str, k: int = 4, filters: Optional[str] = None
) -> List[Tuple[Document, ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
010488e7d439-6 | 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.
"""
docs_and_scores = self.hybrid_search_with_score(
query, k=k, filters=kwargs.get("filters", None)
)
return [d... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
010488e7d439-7 | self, query: str, k: int = 4, **kwargs: Any
) -> List[Document]:
"""
Returns the most similar indexed documents to the query text.
Args:
query (str): The query text for which to find similar documents.
k (int): The number of documents to return. Default is 4.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
010488e7d439-8 | query_language=self.semantic_query_language,
semantic_configuration_name=self.semantic_configuration_name,
query_caption="extractive",
query_answer="extractive",
top=k,
)
# Get Semantic Answers
semantic_answers = results.get_answers()
seman... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
010488e7d439-9 | # Creating a new Azure Search instance
azure_search = cls(
azure_search_endpoint,
azure_search_key,
index_name,
embedding.embed_query,
)
azure_search.add_texts(texts, metadatas, **kwargs)
return azure_search
[docs]class AzureSearchVectorSto... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
010488e7d439-10 | async def _aget_relevant_documents(
self,
query: str,
run_manager: AsyncCallbackManagerForRetrieverRun,
**kwargs: Any,
) -> List[Document]:
raise NotImplementedError(
"AzureSearchVectorStoreRetriever does not support async"
) | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/azuresearch.html |
594b73c834ec-0 | Source code for langchain.vectorstores.docarray.in_memory
"""Wrapper around in-memory storage."""
from __future__ import annotations
from typing import Any, Dict, List, Literal, Optional
from langchain.embeddings.base import Embeddings
from langchain.vectorstores.docarray.base import (
DocArrayIndex,
_check_doc... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/in_memory.html |
594b73c834ec-1 | [docs] @classmethod
def from_texts(
cls,
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[Dict[Any, Any]]] = None,
**kwargs: Any,
) -> DocArrayInMemorySearch:
"""Create an DocArrayInMemorySearch store and insert data.
Args:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/in_memory.html |
05e168b68300-0 | Source code for langchain.vectorstores.docarray.base
from abc import ABC
from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple, Type
import numpy as np
from pydantic import Field
from langchain.embeddings.base import Embeddings
from langchain.schema import Document
from langchain.vectorstores import Ve... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/base.html |
05e168b68300-1 | from docarray import BaseDoc
from docarray.typing import NdArray
class DocArrayDoc(BaseDoc):
text: Optional[str]
embedding: Optional[NdArray] = Field(**embeddings_params)
metadata: Optional[dict]
return DocArrayDoc
@property
def doc_cls(self) -> Type["... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/base.html |
05e168b68300-2 | Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
Returns:
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/docarray/base.html |
05e168b68300-3 | """
raise NotImplementedError
[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 documents similar to.
k... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/base.html |
05e168b68300-4 | Returns:
List of Documents selected by maximal marginal relevance.
"""
query_embedding = self.embedding.embed_query(query)
query_doc = self.doc_cls(embedding=query_embedding) # type: ignore
docs = self.doc_index.find(
query_doc, search_field="embedding", limit=fe... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/base.html |
381e6a7d90b6-0 | Source code for langchain.vectorstores.docarray.hnsw
"""Wrapper around Hnswlib store."""
from __future__ import annotations
from typing import Any, List, Literal, Optional
from langchain.embeddings.base import Embeddings
from langchain.vectorstores.docarray.base import (
DocArrayIndex,
_check_docarray_import,
)... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html |
381e6a7d90b6-1 | "cosine", "ip", and "l2". Defaults to "cosine".
max_elements (int): Maximum number of vectors that can be stored.
Defaults to 1024.
index (bool): Whether an index should be built for this field.
Defaults to True.
ef_construction (int): defines a constr... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html |
381e6a7d90b6-2 | work_dir: Optional[str] = None,
n_dim: Optional[int] = None,
**kwargs: Any,
) -> DocArrayHnswSearch:
"""Create an DocArrayHnswSearch store and insert data.
Args:
texts (List[str]): Text data.
embedding (Embeddings): Embedding function.
metadatas (O... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html |
40d5acbcf29d-0 | Source code for langchain.agents.utils
from typing import Sequence
from langchain.tools.base import BaseTool
[docs]def validate_tools_single_input(class_name: str, tools: Sequence[BaseTool]) -> None:
"""Validate tools for single input."""
for tool in tools:
if not tool.is_single_input:
raise... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/utils.html |
eed6ad48794e-0 | Source code for langchain.agents.agent_types
from enum import Enum
[docs]class AgentType(str, Enum):
"""Enumerator with the Agent types."""
ZERO_SHOT_REACT_DESCRIPTION = "zero-shot-react-description"
REACT_DOCSTORE = "react-docstore"
SELF_ASK_WITH_SEARCH = "self-ask-with-search"
CONVERSATIONAL_REACT... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_types.html |
b894101ad5e8-0 | Source code for langchain.agents.initialize
"""Load agent."""
from typing import Any, Optional, Sequence
from langchain.agents.agent import AgentExecutor
from langchain.agents.agent_types import AgentType
from langchain.agents.loading import AGENT_TO_CLASS, load_agent
from langchain.base_language import BaseLanguageMod... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/initialize.html |
b894101ad5e8-1 | agent = AgentType.ZERO_SHOT_REACT_DESCRIPTION
if agent is not None and agent_path is not None:
raise ValueError(
"Both `agent` and `agent_path` are specified, "
"but at most only one should be."
)
if agent is not None:
if agent not in AGENT_TO_CLASS:
r... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/initialize.html |
6b5de2d557db-0 | Source code for langchain.agents.agent
"""Chain that takes in an input and produces an action and action input."""
from __future__ import annotations
import asyncio
import json
import logging
import time
from abc import abstractmethod
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Sequ... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
6b5de2d557db-1 | return None
[docs] @abstractmethod
def plan(
self,
intermediate_steps: List[Tuple[AgentAction, str]],
callbacks: Callbacks = None,
**kwargs: Any,
) -> Union[AgentAction, AgentFinish]:
"""Given input, decided what to do.
Args:
intermediate_steps: Ste... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
6b5de2d557db-2 | # `force` just returns a constant string
return AgentFinish(
{"output": "Agent stopped due to iteration limit or time limit."}, ""
)
else:
raise ValueError(
f"Got unsupported early_stopping_method `{early_stopping_method}`"
)
[docs]... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
6b5de2d557db-3 | directory_path.mkdir(parents=True, exist_ok=True)
# Fetch dictionary to save
agent_dict = self.dict()
if save_path.suffix == ".json":
with open(file_path, "w") as f:
json.dump(agent_dict, f, indent=4)
elif save_path.suffix == ".yaml":
with open(fil... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
6b5de2d557db-4 | **kwargs: Any,
) -> Union[List[AgentAction], AgentFinish]:
"""Given input, decided what to do.
Args:
intermediate_steps: Steps the LLM has taken to date,
along with observations
callbacks: Callbacks to run.
**kwargs: User inputs.
Returns:
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
6b5de2d557db-5 | Example:
.. code-block:: python
# If working with agent executor
agent.agent.save(file_path="path/agent.yaml")
"""
# Convert file to Path object.
if isinstance(file_path, str):
save_path = Path(file_path)
else:
save_path = file_path... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
6b5de2d557db-6 | return _dict
[docs] def plan(
self,
intermediate_steps: List[Tuple[AgentAction, str]],
callbacks: Callbacks = None,
**kwargs: Any,
) -> Union[AgentAction, AgentFinish]:
"""Given input, decided what to do.
Args:
intermediate_steps: Steps the LLM has take... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
6b5de2d557db-7 | }
[docs]class Agent(BaseSingleActionAgent):
"""Class responsible for calling the language model and deciding the action.
This is driven by an LLMChain. The prompt in the LLMChain MUST include
a variable called "agent_scratchpad" where the agent can put its
intermediary work.
"""
llm_chain: LLMCh... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
6b5de2d557db-8 | return thoughts
[docs] def plan(
self,
intermediate_steps: List[Tuple[AgentAction, str]],
callbacks: Callbacks = None,
**kwargs: Any,
) -> Union[AgentAction, AgentFinish]:
"""Given input, decided what to do.
Args:
intermediate_steps: Steps the LLM has t... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
6b5de2d557db-9 | """Create the full inputs for the LLMChain from intermediate steps."""
thoughts = self._construct_scratchpad(intermediate_steps)
new_inputs = {"agent_scratchpad": thoughts, "stop": self._stop}
full_inputs = {**kwargs, **new_inputs}
return full_inputs
@property
def input_keys(self... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
6b5de2d557db-10 | """Create a prompt for this class."""
@classmethod
def _validate_tools(cls, tools: Sequence[BaseTool]) -> None:
"""Validate that appropriate tools are passed in."""
pass
@classmethod
@abstractmethod
def _get_default_output_parser(cls, **kwargs: Any) -> AgentOutputParser:
"""G... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
6b5de2d557db-11 | # `force` just returns a constant string
return AgentFinish(
{"output": "Agent stopped due to iteration limit or time limit."}, ""
)
elif early_stopping_method == "generate":
# Generate does one final forward pass
thoughts = ""
for acti... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
6b5de2d557db-12 | }
[docs]class ExceptionTool(BaseTool):
name = "_Exception"
description = "Exception tool"
def _run(
self,
query: str,
run_manager: Optional[CallbackManagerForToolRun] = None,
) -> str:
return query
async def _arun(
self,
query: str,
run_manager... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
6b5de2d557db-13 | `"generate"` calls the agent's LLM Chain one final time to generate
a final answer based on the previous steps.
"""
handle_parsing_errors: Union[
bool, str, Callable[[OutputParserException], str]
] = False
"""How to handle errors raised by the agent's output parser.
Defaults to `Fals... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
6b5de2d557db-14 | raise ValueError(
f"Allowed tools ({allowed_tools}) different than "
f"provided tools ({[tool.name for tool in tools]})"
)
return values
[docs] @root_validator()
def validate_return_direct_tool(cls, values: Dict) -> Dict:
"""Validate that to... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
6b5de2d557db-15 | [docs] def lookup_tool(self, name: str) -> BaseTool:
"""Lookup tool by name."""
return {tool.name: tool for tool in self.tools}[name]
def _should_continue(self, iterations: int, time_elapsed: float) -> bool:
if self.max_iterations is not None and iterations >= self.max_iterations:
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
6b5de2d557db-16 | intermediate_steps: List[Tuple[AgentAction, str]],
run_manager: Optional[CallbackManagerForChainRun] = None,
) -> Union[AgentFinish, List[Tuple[AgentAction, str]]]:
"""Take a single step in the thought-action-observation loop.
Override this to take control of how the agent makes and acts on ... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
6b5de2d557db-17 | color=None,
callbacks=run_manager.get_child() if run_manager else None,
**tool_run_kwargs,
)
return [(output, observation)]
# If the tool chosen is the finishing tool, then we end and return.
if isinstance(output, AgentFinish):
return o... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.