Tony20100/langchain_full huggingface dataset:
.. code-block:: python
from langchain_community.vectorstores import SingleStoreDB
from langchain_openai import OpenAIEmbeddings
s2 = SingleStoreDB.from_documents(docs,
OpenAIEmbeddings(),
host=”username:password@localhost:3306/database”,
use_full_text_search=True,
use_vector_index=True,
)
results = s2.similarity_search(“query text”, 1,
search_strategy=SingleStoreDB.SearchStrategy.FILTER_BY_TEXT,
filter_threshold=0.5)
Weighted Sum Search Strategy:
.. code-block:: python
from langchain_community.vectorstores import SingleStoreDB
from langchain_openai import OpenAIEmbeddings
s2 = SingleStoreDB.from_documents(docs,
OpenAIEmbeddings(),
host=”username:password@localhost:3306/database”,
use_full_text_search=True,
use_vector_index=True,
)
results = s2.similarity_search(“query text”, 1,
search_strategy=SingleStoreDB.SearchStrategy.WEIGHTED_SUM,
text_weight=0.3,
vector_weight=0.7)
similarity_search_by_vector(embedding: List[float], k: int = 4, **kwargs: Any) → List[Document]¶
Return docs most similar to embedding vector.
Parameters
embedding (List[float]) – Embedding to look up documents similar to.
k (int) – Number of Documents to return. Defaults to 4.
kwargs (Any) – 
Returns
List of Documents most similar to the query vector.
Return type
List[Document]
similarity_search_with_relevance_scores(query: str, k: int = 4, **kwargs: Any) → List[Tuple[Document, float]]¶
Return docs and relevance scores in the range [0, 1].
Return docs and relevance scores in the range [0, 1].
0 is dissimilar, 1 is most similar.
Parameters
query (str) – Input text.
k (int) – Number of Documents to return. Defaults to 4.
**kwargs (Any) – kwargs to be passed to similarity search. Should include:
score_threshold: Optional, a floating point value between 0 to 1 to
filter the resulting set of retrieved docs
Returns
List of Tuples of (doc, similarity_score)
Return type
List[Tuple[Document, float]]
similarity_search_with_score(query: str, k: int = 4, filter: Optional[dict] = None, search_strategy: SearchStrategy = SearchStrategy.VECTOR_ONLY, filter_threshold: float = 1, text_weight: float = 0.5, vector_weight: float = 0.5, vector_select_count_multiplier: int = 10, **kwargs: Any) → List[Tuple[Document, float]][source]¶
Return docs most similar to query. Uses cosine similarity.
Parameters
query (str) – Text to look up documents similar to.
k (int) – Number of Documents to return. Defaults to 4.
filter (Optional[dict]) – A dictionary of metadata fields and values to filter by.
Defaults to None.
search_strategy (SearchStrategy) – The search strategy to use.
Default is SearchStrategy.VECTOR_ONLY.
Available options are:
- SearchStrategy.VECTOR_ONLY: Searches only by vector similarity.
- SearchStrategy.TEXT_ONLY: Searches only by text similarity. This
option is only available if use_full_text_search is True.
SearchStrategy.FILTER_BY_TEXT: Filters by text similarity andsearches by vector similarity. This option is only available if
use_full_text_search is True.
use_full_text_search is True.
SearchStrategy.FILTER_BY_VECTOR: Filters by vector similarity andsearches by text similarity. This option is only available if
use_full_text_search is True.
SearchStrategy.WEIGHTED_SUM: Searches by a weighted sum of text andvector similarity. This option is only available if
use_full_text_search is True and distance_strategy is DOT_PRODUCT.
filter_threshold (float) – The threshold for filtering by text or vector
similarity. Default is 0. This option has effect only if search_strategy
is SearchStrategy.FILTER_BY_TEXT or SearchStrategy.FILTER_BY_VECTOR.
text_weight (float) – The weight of text similarity in the weighted sum
search strategy. Default is 0.5. This option has effect only if
search_strategy is SearchStrategy.WEIGHTED_SUM.
vector_weight (float) – The weight of vector similarity in the weighted sum
search strategy. Default is 0.5. This option has effect only if
search_strategy is SearchStrategy.WEIGHTED_SUM.
vector_select_count_multiplier (int) – The multiplier for the number of
vectors to select when using the vector index. Default is 10.
This parameter has effect only if use_vector_index is True and
search_strategy is SearchStrategy.WEIGHTED_SUM or
SearchStrategy.FILTER_BY_TEXT.
The number of vectors selected will
be k * vector_select_count_multiplier.
This is needed due to the limitations of the vector index.
kwargs (Any) – 
Returns
List of Documents most similar to the query and score for each
document.
Raises
ValueError – If the search strategy is not supported with the
    distance strategy.
Return type
List[Tuple[Document, float]]
Examples
Basic Usage:
.. code-block:: python
from langchain_community.vectorstores import SingleStoreDB
.. code-block:: python
from langchain_community.vectorstores import SingleStoreDB
from langchain_openai import OpenAIEmbeddings
s2 = SingleStoreDB.from_documents(docs,
OpenAIEmbeddings(),
host=”username:password@localhost:3306/database”
)
results = s2.similarity_search_with_score(“query text”, 1,
{“metadata_field”: “metadata_value”})
Different Search Strategies:
from langchain_community.vectorstores import SingleStoreDB
from langchain_openai import OpenAIEmbeddings
s2 = SingleStoreDB.from_documents(
    docs,
    OpenAIEmbeddings(),
    host="username:password@localhost:3306/database",
    use_full_text_search=True,
    use_vector_index=True,
)
results = s2.similarity_search_with_score("query text", 1,
        search_strategy=SingleStoreDB.SearchStrategy.FILTER_BY_VECTOR,
        filter_threshold=0.5)
Weighted Sum Search Strategy:
.. code-block:: python
from langchain_community.vectorstores import SingleStoreDB
from langchain_openai import OpenAIEmbeddings
s2 = SingleStoreDB.from_documents(docs,
OpenAIEmbeddings(),
host=”username:password@localhost:3306/database”,
use_full_text_search=True,
use_vector_index=True,
)
results = s2.similarity_search_with_score(“query text”, 1,
search_strategy=SingleStoreDB.SearchStrategy.WEIGHTED_SUM,
text_weight=0.3,
vector_weight=0.7)
Examples using SingleStoreDB¶
SingleStoreDB
langchain_community.vectorstores.llm_rails.LLMRailsRetriever¶
class langchain_community.vectorstores.llm_rails.LLMRailsRetriever[source]¶
Bases: VectorStoreRetriever
Retriever for LLMRails.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param metadata: Optional[Dict[str, Any]] = None¶
Optional metadata associated with the retriever. Defaults to None
This metadata will be associated with each call to this retriever,
and passed as arguments to the handlers defined in callbacks.
You can use these to eg identify a specific instance of a retriever with its
use case.
param search_kwargs: dict [Optional]¶
Search params.
k: Number of Documents to return. Defaults to 5.
alpha: parameter for hybrid search .
param search_type: str = 'similarity'¶
Type of search to perform. Defaults to “similarity”.
param tags: Optional[List[str]] = None¶
Optional list of tags associated with the retriever. Defaults to None
These tags will be associated with each call to this retriever,
and passed as arguments to the handlers defined in callbacks.
You can use these to eg identify a specific instance of a retriever with its
use case.
param vectorstore: LLMRails [Required]¶
VectorStore to use for retrieval.
async aadd_documents(documents: List[Document], **kwargs: Any) → List[str]¶
Add documents to the vectorstore.
Parameters
documents (List[Document]) – Documents to add to the vectorstore.
kwargs (Any) – 
Returns
List of IDs of the added texts.
Return type
List[str]
Returns
List of IDs of the added texts.
Return type
List[str]
async abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) → List[Output]¶
Default implementation runs ainvoke in parallel using asyncio.gather.
The default implementation of batch works well for IO bound runnables.
Subclasses should override this method if they can batch more efficiently;
e.g., if the underlying runnable uses an API which supports a batch mode.
Parameters
inputs (List[Input]) – 
config (Optional[Union[RunnableConfig, List[RunnableConfig]]]) – 
return_exceptions (bool) – 
kwargs (Optional[Any]) – 
Return type
List[Output]
async abatch_as_completed(inputs: Sequence[Input], config: Optional[Union[RunnableConfig, Sequence[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) → AsyncIterator[Tuple[int, Union[Output, Exception]]]¶
Run ainvoke in parallel on a list of inputs,
yielding results as they complete.
Parameters
inputs (Sequence[Input]) – 
config (Optional[Union[RunnableConfig, Sequence[RunnableConfig]]]) – 
return_exceptions (bool) – 
kwargs (Optional[Any]) – 
Return type
AsyncIterator[Tuple[int, Union[Output, Exception]]]
add_documents(documents: List[Document], **kwargs: Any) → List[str]¶
Add documents to the vectorstore.
Parameters
documents (List[Document]) – Documents to add to the vectorstore.
kwargs (Any) – 
Returns
List of IDs of the added texts.
Return type
List[str]
Returns
List of IDs of the added texts.
Return type
List[str]
add_texts(texts: List[str]) → None[source]¶
Add text to the datastore.
Parameters
texts (List[str]) – The text
Return type
None
async aget_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) → List[Document]¶
[Deprecated] Asynchronously get documents relevant to a query.
Users should favor using .ainvoke or .abatch rather than
aget_relevant_documents directly.
Parameters
query (str) – string to find relevant documents for
callbacks (Callbacks) – Callback manager or list of callbacks
tags (Optional[List[str]]) – Optional list of tags associated with the retriever. Defaults to None
These tags will be associated with each call to this retriever,
and passed as arguments to the handlers defined in callbacks.
metadata (Optional[Dict[str, Any]]) – Optional metadata associated with the retriever. Defaults to None
This metadata will be associated with each call to this retriever,
and passed as arguments to the handlers defined in callbacks.
run_name (Optional[str]) – Optional name for the run.
kwargs (Any) – 
Returns
List of relevant documents
Return type
List[Document]
Notes
Deprecated since version langchain-core==0.1.46: Use ainvoke instead.
async ainvoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Any) → List[Document]¶
Asynchronously invoke the retriever to get relevant documents.
Main entry point for asynchronous retriever invocations.
Parameters
input (str) – The query string
Parameters
input (str) – The query string
config (Optional[RunnableConfig]) – Configuration for the retriever
**kwargs (Any) – Additional arguments to pass to the retriever
Returns
List of relevant documents
Return type
List[Document]
Examples:
await retriever.ainvoke("query")
assign(**kwargs: Union[Runnable[Dict[str, Any], Any], Callable[[Dict[str, Any]], Any], Mapping[str, Union[Runnable[Dict[str, Any], Any], Callable[[Dict[str, Any]], Any]]]]) → RunnableSerializable[Any, Any]¶
Assigns new fields to the dict output of this runnable.
Returns a new runnable.
from langchain_community.llms.fake import FakeStreamingListLLM
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import SystemMessagePromptTemplate
from langchain_core.runnables import Runnable
from operator import itemgetter
prompt = (
    SystemMessagePromptTemplate.from_template("You are a nice assistant.")
    + "{question}"
)
llm = FakeStreamingListLLM(responses=["foo-lish"])
chain: Runnable = prompt | llm | {"str": StrOutputParser()}
chain_with_assign = chain.assign(hello=itemgetter("str") | llm)
print(chain_with_assign.input_schema.schema())
# {'title': 'PromptInput', 'type': 'object', 'properties':
{'question': {'title': 'Question', 'type': 'string'}}}
print(chain_with_assign.output_schema.schema()) #
{'title': 'RunnableSequenceOutput', 'type': 'object', 'properties':
{'str': {'title': 'Str',
'type': 'string'}, 'hello': {'title': 'Hello', 'type': 'string'}}}
Parameters
exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – fields to exclude from new model, as with values this takes precedence over include
update (Optional[DictStrAny]) – values to change/add in the new model. Note: the data is not validated before creating
the new model: you should trust this data
deep (bool) – set to True to make a deep copy of the model
self (Model) – 
Returns
new model instance
Return type
Model
dict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) → DictStrAny¶
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
Parameters
include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – 
exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – 
by_alias (bool) – 
skip_defaults (Optional[bool]) – 
exclude_unset (bool) – 
exclude_defaults (bool) – 
exclude_none (bool) – 
Return type
DictStrAny
classmethod from_orm(obj: Any) → Model¶
Parameters
obj (Any) – 
Return type
Model
get_graph(config: Optional[RunnableConfig] = None) → Graph¶
Return a graph representation of this runnable.
Parameters
config (Optional[RunnableConfig]) – 
Return type
Graph
get_input_schema(config: Optional[RunnableConfig] = None) → Type[BaseModel]¶
Get a pydantic model that can be used to validate input to the runnable.
Runnables that leverage the configurable_fields and configurable_alternatives
methods will have a dynamic input schema that depends on which
configuration the runnable is invoked with.
This method allows to get an input schema for a specific configuration.
Parameters
config (Optional[RunnableConfig]) – A config to use when generating the schema.
Returns
A pydantic model that can be used to validate input.
Return type
Type[BaseModel]
classmethod get_lc_namespace() → List[str]¶
Get the namespace of the langchain object.
For example, if the class is langchain.llms.openai.OpenAI, then the
namespace is [“langchain”, “llms”, “openai”]
Return type
List[str]
get_name(suffix: Optional[str] = None, *, name: Optional[str] = None) → str¶
Get the name of the runnable.
Parameters
suffix (Optional[str]) – 
name (Optional[str]) – 
Return type
str
get_output_schema(config: Optional[RunnableConfig] = None) → Type[BaseModel]¶
Get a pydantic model that can be used to validate output to the runnable.
Runnables that leverage the configurable_fields and configurable_alternatives
methods will have a dynamic output schema that depends on which
configuration the runnable is invoked with.
This method allows to get an output schema for a specific configuration.
Parameters
config (Optional[RunnableConfig]) – A config to use when generating the schema.
Returns
A pydantic model that can be used to validate output.
Return type
Type[BaseModel]
get_prompts(config: Optional[RunnableConfig] = None) → List[BasePromptTemplate]¶
Parameters
config (Optional[RunnableConfig]) – 
Return type
Parameters
config (Optional[RunnableConfig]) – 
Return type
List[BasePromptTemplate]
get_relevant_documents(query: str, *, callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any) → List[Document]¶
[Deprecated] Retrieve documents relevant to a query.
Users should favor using .invoke or .batch rather than
get_relevant_documents directly.
Parameters
query (str) – string to find relevant documents for
callbacks (Callbacks) – Callback manager or list of callbacks
tags (Optional[List[str]]) – Optional list of tags associated with the retriever. Defaults to None
These tags will be associated with each call to this retriever,
and passed as arguments to the handlers defined in callbacks.
metadata (Optional[Dict[str, Any]]) – Optional metadata associated with the retriever. Defaults to None
This metadata will be associated with each call to this retriever,
and passed as arguments to the handlers defined in callbacks.
run_name (Optional[str]) – Optional name for the run.
kwargs (Any) – 
Returns
List of relevant documents
Return type
List[Document]
Notes
Deprecated since version langchain-core==0.1.46: Use invoke instead.
invoke(input: str, config: Optional[RunnableConfig] = None, **kwargs: Any) → List[Document]¶
Invoke the retriever to get relevant documents.
Main entry point for synchronous retriever invocations.
Parameters
input (str) – The query string
config (Optional[RunnableConfig]) – Configuration for the retriever
**kwargs (Any) – Additional arguments to pass to the retriever
Returns
List of relevant documents
Return type
List[Document]
Examples:
Returns
List of relevant documents
Return type
List[Document]
Examples:
retriever.invoke("query")
classmethod is_lc_serializable() → bool¶
Is this class serializable?
Return type
bool
json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) → unicode¶
Generate a JSON representation of the model, include and exclude arguments as per dict().
encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().
Parameters
include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – 
exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – 
by_alias (bool) – 
skip_defaults (Optional[bool]) – 
exclude_unset (bool) – 
exclude_defaults (bool) – 
exclude_none (bool) – 
encoder (Optional[Callable[[Any], Any]]) – 
models_as_dict (bool) – 
dumps_kwargs (Any) – 
Return type
unicode
classmethod lc_id() → List[str]¶
A unique identifier for this class for serialization purposes.
The unique identifier is a list of strings that describes the path
to the object.
Return type
List[str]
map() → Runnable[List[Input], List[Output]]¶
Return a new Runnable that maps a list of inputs to a list of outputs,
Return a new Runnable that maps a list of inputs to a list of outputs,
by calling invoke() with each input.
Example
from langchain_core.runnables import RunnableLambda
def _lambda(x: int) -> int:
    return x + 1
runnable = RunnableLambda(_lambda)
print(runnable.map().invoke([1, 2, 3])) # [2, 3, 4]
Return type
Runnable[List[Input], List[Output]]
classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶
Parameters
path (Union[str, Path]) – 
content_type (unicode) – 
encoding (unicode) – 
proto (Protocol) – 
allow_pickle (bool) – 
Return type
Model
classmethod parse_obj(obj: Any) → Model¶
Parameters
obj (Any) – 
Return type
Model
classmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶
Parameters
b (Union[str, bytes]) – 
content_type (unicode) – 
encoding (unicode) – 
proto (Protocol) – 
allow_pickle (bool) – 
Return type
Model
pick(keys: Union[str, List[str]]) → RunnableSerializable[Any, Any]¶
Pick keys from the dict output of this runnable.
Pick single key:import json
from langchain_core.runnables import RunnableLambda, RunnableMap
as_str = RunnableLambda(str)
as_json = RunnableLambda(json.loads)
chain = RunnableMap(str=as_str, json=as_json)
Example
from langchain_core.runnables import RunnableLambda
def add_one(x: int) -> int:
    return x + 1
def mul_two(x: int) -> int:
    return x * 2
runnable_1 = RunnableLambda(add_one)
runnable_2 = RunnableLambda(mul_two)
sequence = runnable_1.pipe(runnable_2)
# Or equivalently:
# sequence = runnable_1 | runnable_2
# sequence = RunnableSequence(first=runnable_1, last=runnable_2)
sequence.invoke(1)
await sequence.ainvoke(1)
# -> 4
sequence.batch([1, 2, 3])
await sequence.abatch([1, 2, 3])
# -> [4, 6, 8]
Parameters
others (Union[Runnable[Any, Other], Callable[[Any], Other]]) – 
name (Optional[str]) – 
Return type
RunnableSerializable[Input, Other]
classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') → DictStrAny¶
Parameters
by_alias (bool) – 
ref_template (unicode) – 
Return type
DictStrAny
classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) → unicode¶
Parameters
by_alias (bool) – 
ref_template (unicode) – 
dumps_kwargs (Any) – 
Return type
unicode
stream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → Iterator[Output]¶
Default implementation of stream, which calls invoke.
Subclasses should override this method if they support streaming output.
Parameters
input (Input) –
stop_after_attempt (int) – The maximum number of attempts to make before giving up
Returns
A new Runnable that retries the original runnable on exceptions.
Return type
Runnable[Input, Output]
with_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) → Runnable[Input, Output]¶
Bind input and output types to a Runnable, returning a new Runnable.
Parameters
input_type (Optional[Type[Input]]) – 
output_type (Optional[Type[Output]]) – 
Return type
Runnable[Input, Output]
property InputType: Type[Input]¶
The type of input this runnable accepts specified as a type annotation.
property OutputType: Type[Output]¶
The type of output this runnable produces specified as a type annotation.
allowed_search_types: ClassVar[Collection[str]] = ('similarity', 'similarity_score_threshold', 'mmr')¶
property config_specs: List[ConfigurableFieldSpec]¶
List configurable fields for this runnable.
property input_schema: Type[BaseModel]¶
The type of input this runnable accepts specified as a pydantic model.
property lc_attributes: Dict¶
List of attribute names that should be included in the serialized kwargs.
These attributes must be accepted by the constructor.
property lc_secrets: Dict[str, str]¶
A map of constructor argument names to secret ids.
For example,{“openai_api_key”: “OPENAI_API_KEY”}
name: Optional[str] = None¶
The name of the runnable. Used for debugging and tracing.
property output_schema: Type[BaseModel]¶
The type of output this runnable produces specified as a pydantic model.
langchain_community.vectorstores.tencentvectordb.IndexParams¶
class langchain_community.vectorstores.tencentvectordb.IndexParams(dimension: int, shard: int = 1, replicas: int = 2, index_type: str = 'HNSW', metric_type: str = 'L2', params: Optional[Dict] = None)[source]¶
Tencent vector DB Index params.
See the following documentation for details:
https://cloud.tencent.com/document/product/1709/95826
Methods
__init__(dimension[, shard, replicas, ...])
Parameters
dimension (int) – 
shard (int) – 
replicas (int) – 
index_type (str) – 
metric_type (str) – 
params (Optional[Dict]) – 
__init__(dimension: int, shard: int = 1, replicas: int = 2, index_type: str = 'HNSW', metric_type: str = 'L2', params: Optional[Dict] = None)[source]¶
Parameters
dimension (int) – 
shard (int) – 
replicas (int) – 
index_type (str) – 
metric_type (str) – 
params (Optional[Dict]) –