id
stringlengths 14
16
| text
stringlengths 31
2.41k
| source
stringlengths 54
121
|
|---|---|---|
c018b0edb28a-91
|
Return pinecone documents most similar to query, along with scores.
Parameters
query (str) β Text to look up documents similar to.
k (int) β Number of Documents to return. Defaults to 4.
filter (Optional[dict]) β Dictionary of argument(s) to filter on metadata
namespace (Optional[str]) β Namespace to search in. Default will search in ββ namespace.
Returns
List of Documents most similar to the query and score for each
Return type
List[Tuple[langchain.schema.Document, float]]
similarity_search(query, k=4, filter=None, namespace=None, **kwargs)[source]ο
Return pinecone documents most similar to query.
Parameters
query (str) β Text to look up documents similar to.
k (int) β Number of Documents to return. Defaults to 4.
filter (Optional[dict]) β Dictionary of argument(s) to filter on metadata
namespace (Optional[str]) β Namespace to search in. Default will search in ββ namespace.
kwargs (Any) β
Returns
List of Documents most similar to the query and score for each
Return type
List[langchain.schema.Document]
max_marginal_relevance_search_by_vector(embedding, k=4, fetch_k=20, lambda_mult=0.5, filter=None, namespace=None, **kwargs)[source]ο
Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
Parameters
embedding (List[float]) β Embedding to look up documents similar to.
k (int) β Number of Documents to return. Defaults to 4.
fetch_k (int) β Number of Documents to fetch to pass to MMR algorithm.
lambda_mult (float) β Number between 0 and 1 that determines the degree
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-92
|
lambda_mult (float) β 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.
filter (Optional[dict]) β
namespace (Optional[str]) β
kwargs (Any) β
Returns
List of Documents selected by maximal marginal relevance.
Return type
List[langchain.schema.Document]
max_marginal_relevance_search(query, k=4, fetch_k=20, lambda_mult=0.5, filter=None, namespace=None, **kwargs)[source]ο
Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
Parameters
query (str) β Text to look up documents similar to.
k (int) β Number of Documents to return. Defaults to 4.
fetch_k (int) β Number of Documents to fetch to pass to MMR algorithm.
lambda_mult (float) β 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.
filter (Optional[dict]) β
namespace (Optional[str]) β
kwargs (Any) β
Returns
List of Documents selected by maximal marginal relevance.
Return type
List[langchain.schema.Document]
classmethod from_texts(texts, embedding, metadatas=None, ids=None, batch_size=32, text_key='text', index_name=None, namespace=None, **kwargs)[source]ο
Construct Pinecone wrapper from raw documents.
This is a user friendly interface that:
Embeds documents.
Adds the documents to a provided Pinecone index
This is intended to be a quick way to get started.
Example
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-93
|
This is intended to be a quick way to get started.
Example
from langchain import Pinecone
from langchain.embeddings import OpenAIEmbeddings
import pinecone
# The environment should be the one specified next to the API key
# in your Pinecone console
pinecone.init(api_key="***", environment="...")
embeddings = OpenAIEmbeddings()
pinecone = Pinecone.from_texts(
texts,
embeddings,
index_name="langchain-demo"
)
Parameters
texts (List[str]) β
embedding (langchain.embeddings.base.Embeddings) β
metadatas (Optional[List[dict]]) β
ids (Optional[List[str]]) β
batch_size (int) β
text_key (str) β
index_name (Optional[str]) β
namespace (Optional[str]) β
kwargs (Any) β
Return type
langchain.vectorstores.pinecone.Pinecone
classmethod from_existing_index(index_name, embedding, text_key='text', namespace=None)[source]ο
Load pinecone vectorstore from index name.
Parameters
index_name (str) β
embedding (langchain.embeddings.base.Embeddings) β
text_key (str) β
namespace (Optional[str]) β
Return type
langchain.vectorstores.pinecone.Pinecone
delete(ids)[source]ο
Delete by vector IDs.
Parameters
ids (List[str]) β List of ids to delete.
Return type
None
class langchain.vectorstores.Qdrant(client, collection_name, embeddings=None, content_payload_key='page_content', metadata_payload_key='metadata', embedding_function=None)[source]ο
Bases: langchain.vectorstores.base.VectorStore
Wrapper around Qdrant vector database.
To use you should have the qdrant-client package installed.
Example
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-94
|
To use you should have the qdrant-client package installed.
Example
from qdrant_client import QdrantClient
from langchain import Qdrant
client = QdrantClient()
collection_name = "MyCollection"
qdrant = Qdrant(client, collection_name, embedding_function)
Parameters
client (Any) β
collection_name (str) β
embeddings (Optional[Embeddings]) β
content_payload_key (str) β
metadata_payload_key (str) β
embedding_function (Optional[Callable]) β
CONTENT_KEY = 'page_content'ο
METADATA_KEY = 'metadata'ο
add_texts(texts, metadatas=None, ids=None, batch_size=64, **kwargs)[source]ο
Run more texts through the embeddings and add to the vectorstore.
Parameters
texts (Iterable[str]) β Iterable of strings to add to the vectorstore.
metadatas (Optional[List[dict]]) β Optional list of metadatas associated with the texts.
ids (Optional[Sequence[str]]) β Optional list of ids to associate with the texts. Ids have to be
uuid-like strings.
batch_size (int) β How many vectors upload per-request.
Default: 64
kwargs (Any) β
Returns
List of ids from adding the texts into the vectorstore.
Return type
List[str]
similarity_search(query, k=4, filter=None, search_params=None, offset=0, score_threshold=None, consistency=None, **kwargs)[source]ο
Return docs most similar to query.
Parameters
query (str) β Text to look up documents similar to.
k (int) β Number of Documents to return. Defaults to 4.
filter (Optional[MetadataFilter]) β Filter by metadata. Defaults to None.
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-95
|
filter (Optional[MetadataFilter]) β Filter by metadata. Defaults to None.
search_params (Optional[common_types.SearchParams]) β Additional search params
offset (int) β Offset of the first result to return.
May be used to paginate results.
Note: large offset values may cause performance issues.
score_threshold (Optional[float]) β Define a minimal score threshold for the result.
If defined, less similar results will not be returned.
Score of the returned result might be higher or smaller than the
threshold depending on the Distance function used.
E.g. for cosine similarity only higher scores will be returned.
consistency (Optional[common_types.ReadConsistency]) β Read consistency of the search. Defines how many replicas should be
queried before returning the result.
Values:
- int - number of replicas to query, values should present in all
queried replicas
βmajorityβ - query all replicas, but return values present in themajority of replicas
βquorumβ - query the majority of replicas, return values present inall of them
βallβ - query all replicas, and return values present in all replicas
kwargs (Any) β
Returns
List of Documents most similar to the query.
Return type
List[Document]
similarity_search_with_score(query, k=4, filter=None, search_params=None, offset=0, score_threshold=None, consistency=None, **kwargs)[source]ο
Return docs most similar to query.
Parameters
query (str) β Text to look up documents similar to.
k (int) β Number of Documents to return. Defaults to 4.
filter (Optional[MetadataFilter]) β Filter by metadata. Defaults to None.
search_params (Optional[common_types.SearchParams]) β Additional search params
offset (int) β Offset of the first result to return.
May be used to paginate results.
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-96
|
May be used to paginate results.
Note: large offset values may cause performance issues.
score_threshold (Optional[float]) β Define a minimal score threshold for the result.
If defined, less similar results will not be returned.
Score of the returned result might be higher or smaller than the
threshold depending on the Distance function used.
E.g. for cosine similarity only higher scores will be returned.
consistency (Optional[common_types.ReadConsistency]) β Read consistency of the search. Defines how many replicas should be
queried before returning the result.
Values:
- int - number of replicas to query, values should present in all
queried replicas
βmajorityβ - query all replicas, but return values present in themajority of replicas
βquorumβ - query the majority of replicas, return values present inall of them
βallβ - query all replicas, and return values present in all replicas
kwargs (Any) β
Returns
List of documents most similar to the query text and cosine
distance in float for each.
Lower score represents more similarity.
Return type
List[Tuple[Document, float]]
similarity_search_by_vector(embedding, k=4, filter=None, search_params=None, offset=0, score_threshold=None, consistency=None, **kwargs)[source]ο
Return docs most similar to embedding vector.
Parameters
embedding (List[float]) β Embedding vector to look up documents similar to.
k (int) β Number of Documents to return. Defaults to 4.
filter (Optional[MetadataFilter]) β Filter by metadata. Defaults to None.
search_params (Optional[common_types.SearchParams]) β Additional search params
offset (int) β Offset of the first result to return.
May be used to paginate results.
Note: large offset values may cause performance issues.
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-97
|
May be used to paginate results.
Note: large offset values may cause performance issues.
score_threshold (Optional[float]) β Define a minimal score threshold for the result.
If defined, less similar results will not be returned.
Score of the returned result might be higher or smaller than the
threshold depending on the Distance function used.
E.g. for cosine similarity only higher scores will be returned.
consistency (Optional[common_types.ReadConsistency]) β Read consistency of the search. Defines how many replicas should be
queried before returning the result.
Values:
- int - number of replicas to query, values should present in all
queried replicas
βmajorityβ - query all replicas, but return values present in themajority of replicas
βquorumβ - query the majority of replicas, return values present inall of them
βallβ - query all replicas, and return values present in all replicas
kwargs (Any) β
Returns
List of Documents most similar to the query.
Return type
List[Document]
similarity_search_with_score_by_vector(embedding, k=4, filter=None, search_params=None, offset=0, score_threshold=None, consistency=None, **kwargs)[source]ο
Return docs most similar to embedding vector.
Parameters
embedding (List[float]) β Embedding vector to look up documents similar to.
k (int) β Number of Documents to return. Defaults to 4.
filter (Optional[MetadataFilter]) β Filter by metadata. Defaults to None.
search_params (Optional[common_types.SearchParams]) β Additional search params
offset (int) β Offset of the first result to return.
May be used to paginate results.
Note: large offset values may cause performance issues.
score_threshold (Optional[float]) β Define a minimal score threshold for the result.
If defined, less similar results will not be returned.
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-98
|
If defined, less similar results will not be returned.
Score of the returned result might be higher or smaller than the
threshold depending on the Distance function used.
E.g. for cosine similarity only higher scores will be returned.
consistency (Optional[common_types.ReadConsistency]) β Read consistency of the search. Defines how many replicas should be
queried before returning the result.
Values:
- int - number of replicas to query, values should present in all
queried replicas
βmajorityβ - query all replicas, but return values present in themajority of replicas
βquorumβ - query the majority of replicas, return values present inall of them
βallβ - query all replicas, and return values present in all replicas
kwargs (Any) β
Returns
List of documents most similar to the query text and cosine
distance in float for each.
Lower score represents more similarity.
Return type
List[Tuple[Document, float]]
max_marginal_relevance_search(query, k=4, fetch_k=20, lambda_mult=0.5, **kwargs)[source]ο
Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
Parameters
query (str) β Text to look up documents similar to.
k (int) β Number of Documents to return. Defaults to 4.
fetch_k (int) β Number of Documents to fetch to pass to MMR algorithm.
Defaults to 20.
lambda_mult (float) β 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.
kwargs (Any) β
Returns
List of Documents selected by maximal marginal relevance.
Return type
List[langchain.schema.Document]
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-99
|
Return type
List[langchain.schema.Document]
classmethod from_texts(texts, embedding, metadatas=None, ids=None, location=None, url=None, port=6333, grpc_port=6334, prefer_grpc=False, https=None, api_key=None, prefix=None, timeout=None, host=None, path=None, collection_name=None, distance_func='Cosine', content_payload_key='page_content', metadata_payload_key='metadata', batch_size=64, shard_number=None, replication_factor=None, write_consistency_factor=None, on_disk_payload=None, hnsw_config=None, optimizers_config=None, wal_config=None, quantization_config=None, init_from=None, **kwargs)[source]ο
Construct Qdrant wrapper from a list of texts.
Parameters
texts (List[str]) β A list of texts to be indexed in Qdrant.
embedding (Embeddings) β A subclass of Embeddings, responsible for text vectorization.
metadatas (Optional[List[dict]]) β An optional list of metadata. If provided it has to be of the same
length as a list of texts.
ids (Optional[Sequence[str]]) β Optional list of ids to associate with the texts. Ids have to be
uuid-like strings.
location (Optional[str]) β If :memory: - use in-memory Qdrant instance.
If str - use it as a url parameter.
If None - fallback to relying on host and port parameters.
url (Optional[str]) β either host or str of βOptional[scheme], host, Optional[port],
Optional[prefix]β. Default: None
port (Optional[int]) β Port of the REST API interface. Default: 6333
grpc_port (int) β Port of the gRPC interface. Default: 6334
prefer_grpc (bool) β If true - use gPRC interface whenever possible in custom methods.
Default: False
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-100
|
Default: False
https (Optional[bool]) β If true - use HTTPS(SSL) protocol. Default: None
api_key (Optional[str]) β API key for authentication in Qdrant Cloud. Default: None
prefix (Optional[str]) β If not None - add prefix to the REST URL path.
Example: service/v1 will result in
http://localhost:6333/service/v1/{qdrant-endpoint} for REST API.
Default: None
timeout (Optional[float]) β Timeout for REST and gRPC API requests.
Default: 5.0 seconds for REST and unlimited for gRPC
host (Optional[str]) β Host name of Qdrant service. If url and host are None, set to
βlocalhostβ. Default: None
path (Optional[str]) β Path in which the vectors will be stored while using local mode.
Default: None
collection_name (Optional[str]) β Name of the Qdrant collection to be used. If not provided,
it will be created randomly. Default: None
distance_func (str) β Distance function. One of: βCosineβ / βEuclidβ / βDotβ.
Default: βCosineβ
content_payload_key (str) β A payload key used to store the content of the document.
Default: βpage_contentβ
metadata_payload_key (str) β A payload key used to store the metadata of the document.
Default: βmetadataβ
batch_size (int) β How many vectors upload per-request.
Default: 64
shard_number (Optional[int]) β Number of shards in collection. Default is 1, minimum is 1.
replication_factor (Optional[int]) β Replication factor for collection. Default is 1, minimum is 1.
Defines how many copies of each shard will be created.
Have effect only in distributed mode.
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-101
|
Defines how many copies of each shard will be created.
Have effect only in distributed mode.
write_consistency_factor (Optional[int]) β Write consistency factor for collection. Default is 1, minimum is 1.
Defines how many replicas should apply the operation for us to consider
it successful. Increasing this number will make the collection more
resilient to inconsistencies, but will also make it fail if not enough
replicas are available.
Does not have any performance impact.
Have effect only in distributed mode.
on_disk_payload (Optional[bool]) β If true - point`s payload will not be stored in memory.
It will be read from the disk every time it is requested.
This setting saves RAM by (slightly) increasing the response time.
Note: those payload values that are involved in filtering and are
indexed - remain in RAM.
hnsw_config (Optional[common_types.HnswConfigDiff]) β Params for HNSW index
optimizers_config (Optional[common_types.OptimizersConfigDiff]) β Params for optimizer
wal_config (Optional[common_types.WalConfigDiff]) β Params for Write-Ahead-Log
quantization_config (Optional[common_types.QuantizationConfig]) β Params for quantization, if None - quantization will be disabled
init_from (Optional[common_types.InitFrom]) β Use data stored in another collection to initialize this collection
**kwargs β Additional arguments passed directly into REST client initialization
kwargs (Any) β
Return type
Qdrant
This is a user-friendly interface that:
1. Creates embeddings, one for each text
2. Initializes the Qdrant database as an in-memory docstore by default
(and overridable to a remote docstore)
Adds the text embeddings to the Qdrant database
This is intended to be a quick way to get started.
Example
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-102
|
This is intended to be a quick way to get started.
Example
from langchain import Qdrant
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
qdrant = Qdrant.from_texts(texts, embeddings, "localhost")
class langchain.vectorstores.Redis(redis_url, index_name, embedding_function, content_key='content', metadata_key='metadata', vector_key='content_vector', relevance_score_fn=<function _default_relevance_score>, **kwargs)[source]ο
Bases: langchain.vectorstores.base.VectorStore
Wrapper around Redis vector database.
To use, you should have the redis python package installed.
Example
from langchain.vectorstores import Redis
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
vectorstore = Redis(
redis_url="redis://username:password@localhost:6379"
index_name="my-index",
embedding_function=embeddings.embed_query,
)
Parameters
redis_url (str) β
index_name (str) β
embedding_function (Callable) β
content_key (str) β
metadata_key (str) β
vector_key (str) β
relevance_score_fn (Optional[Callable[[float], float]]) β
kwargs (Any) β
add_texts(texts, metadatas=None, embeddings=None, batch_size=1000, **kwargs)[source]ο
Add more texts to the vectorstore.
Parameters
texts (Iterable[str]) β Iterable of strings/text to add to the vectorstore.
metadatas (Optional[List[dict]], optional) β Optional list of metadatas.
Defaults to None.
embeddings (Optional[List[List[float]]], optional) β Optional pre-generated
embeddings. Defaults to None.
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-103
|
embeddings. Defaults to None.
keys (List[str]) or ids (List[str]) β Identifiers of entries.
Defaults to None.
batch_size (int, optional) β Batch size to use for writes. Defaults to 1000.
kwargs (Any) β
Returns
List of ids added to the vectorstore
Return type
List[str]
similarity_search(query, k=4, **kwargs)[source]ο
Returns the most similar indexed documents to the query text.
Parameters
query (str) β The query text for which to find similar documents.
k (int) β The number of documents to return. Default is 4.
kwargs (Any) β
Returns
A list of documents that are most similar to the query text.
Return type
List[Document]
similarity_search_limit_score(query, k=4, score_threshold=0.2, **kwargs)[source]ο
Returns the most similar indexed documents to the query text within the
score_threshold range.
Parameters
query (str) β The query text for which to find similar documents.
k (int) β The number of documents to return. Default is 4.
score_threshold (float) β The minimum matching score required for a document
0.2. (to be considered a match. Defaults to) β
similarity (Because the similarity calculation algorithm is based on cosine) β
kwargs (Any) β
Return type
List[langchain.schema.Document]
:param :
:param the smaller the angle:
:param the higher the similarity.:
Returns
A list of documents that are most similar to the query text,
including the match score for each document.
Return type
List[Document]
Parameters
query (str) β
k (int) β
score_threshold (float) β
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-104
|
k (int) β
score_threshold (float) β
kwargs (Any) β
Note
If there are no documents that satisfy the score_threshold value,
an empty list is returned.
similarity_search_with_score(query, k=4)[source]ο
Return docs most similar to query.
Parameters
query (str) β Text to look up documents similar to.
k (int) β Number of Documents to return. Defaults to 4.
Returns
List of Documents most similar to the query and score for each
Return type
List[Tuple[langchain.schema.Document, float]]
classmethod from_texts_return_keys(texts, embedding, metadatas=None, index_name=None, content_key='content', metadata_key='metadata', vector_key='content_vector', distance_metric='COSINE', **kwargs)[source]ο
Create a Redis vectorstore from raw documents.
This is a user-friendly interface that:
Embeds documents.
Creates a new index for the embeddings in Redis.
Adds the documents to the newly created Redis index.
Returns the keys of the newly created documents.
This is intended to be a quick way to get started.
.. rubric:: Example
Parameters
texts (List[str]) β
embedding (langchain.embeddings.base.Embeddings) β
metadatas (Optional[List[dict]]) β
index_name (Optional[str]) β
content_key (str) β
metadata_key (str) β
vector_key (str) β
distance_metric (Literal['COSINE', 'IP', 'L2']) β
kwargs (Any) β
Return type
Tuple[langchain.vectorstores.redis.Redis, List[str]]
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-105
|
Return type
Tuple[langchain.vectorstores.redis.Redis, List[str]]
classmethod from_texts(texts, embedding, metadatas=None, index_name=None, content_key='content', metadata_key='metadata', vector_key='content_vector', **kwargs)[source]ο
Create a Redis vectorstore from raw documents.
This is a user-friendly interface that:
Embeds documents.
Creates a new index for the embeddings in Redis.
Adds the documents to the newly created Redis index.
This is intended to be a quick way to get started.
.. rubric:: Example
Parameters
texts (List[str]) β
embedding (langchain.embeddings.base.Embeddings) β
metadatas (Optional[List[dict]]) β
index_name (Optional[str]) β
content_key (str) β
metadata_key (str) β
vector_key (str) β
kwargs (Any) β
Return type
langchain.vectorstores.redis.Redis
static delete(ids, **kwargs)[source]ο
Delete a Redis entry.
Parameters
ids (List[str]) β List of ids (keys) to delete.
kwargs (Any) β
Returns
Whether or not the deletions were successful.
Return type
bool
static drop_index(index_name, delete_documents, **kwargs)[source]ο
Drop a Redis search index.
Parameters
index_name (str) β Name of the index to drop.
delete_documents (bool) β Whether to drop the associated documents.
kwargs (Any) β
Returns
Whether or not the drop was successful.
Return type
bool
classmethod from_existing_index(embedding, index_name, content_key='content', metadata_key='metadata', vector_key='content_vector', **kwargs)[source]ο
Connect to an existing Redis index.
Parameters
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-106
|
Connect to an existing Redis index.
Parameters
embedding (langchain.embeddings.base.Embeddings) β
index_name (str) β
content_key (str) β
metadata_key (str) β
vector_key (str) β
kwargs (Any) β
Return type
langchain.vectorstores.redis.Redis
as_retriever(**kwargs)[source]ο
Parameters
kwargs (Any) β
Return type
langchain.vectorstores.redis.RedisVectorStoreRetriever
class langchain.vectorstores.Rockset(client, embeddings, collection_name, text_key, embedding_key)[source]ο
Bases: langchain.vectorstores.base.VectorStore
Wrapper arpund Rockset vector database.
To use, you should have the rockset python package installed. Note that to use
this, the collection being used must already exist in your Rockset instance.
You must also ensure you use a Rockset ingest transformation to apply
VECTOR_ENFORCE on the column being used to store embedding_key in the
collection.
See: https://rockset.com/blog/introducing-vector-search-on-rockset/ for more details
Everything below assumes commons Rockset workspace.
TODO: Add support for workspace args.
Example
from langchain.vectorstores import Rockset
from langchain.embeddings.openai import OpenAIEmbeddings
import rockset
# Make sure you use the right host (region) for your Rockset instance
# and APIKEY has both read-write access to your collection.
rs = rockset.RocksetClient(host=rockset.Regions.use1a1, api_key="***")
collection_name = "langchain_demo"
embeddings = OpenAIEmbeddings()
vectorstore = Rockset(rs, collection_name, embeddings,
"description", "description_embedding")
Parameters
client (Any) β
embeddings (Embeddings) β
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-107
|
Parameters
client (Any) β
embeddings (Embeddings) β
collection_name (str) β
text_key (str) β
embedding_key (str) β
add_texts(texts, metadatas=None, ids=None, batch_size=32, **kwargs)[source]ο
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.
ids: Optional list of ids to associate with the texts.
batch_size: Send documents in batches to rockset.
Returns
List of ids from adding the texts into the vectorstore.
Parameters
texts (Iterable[str]) β
metadatas (Optional[List[dict]]) β
ids (Optional[List[str]]) β
batch_size (int) β
kwargs (Any) β
Return type
List[str]
classmethod from_texts(texts, embedding, metadatas=None, client=None, collection_name='', text_key='', embedding_key='', ids=None, batch_size=32, **kwargs)[source]ο
Create Rockset wrapper with existing texts.
This is intended as a quicker way to get started.
Parameters
texts (List[str]) β
embedding (langchain.embeddings.base.Embeddings) β
metadatas (Optional[List[dict]]) β
client (Any) β
collection_name (str) β
text_key (str) β
embedding_key (str) β
ids (Optional[List[str]]) β
batch_size (int) β
kwargs (Any) β
Return type
langchain.vectorstores.rocksetdb.Rockset
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-108
|
Return type
langchain.vectorstores.rocksetdb.Rockset
class DistanceFunction(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]ο
Bases: enum.Enum
COSINE_SIM = 'COSINE_SIM'ο
EUCLIDEAN_DIST = 'EUCLIDEAN_DIST'ο
DOT_PRODUCT = 'DOT_PRODUCT'ο
order_by()[source]ο
Return type
str
similarity_search_with_relevance_scores(query, k=4, distance_func=DistanceFunction.COSINE_SIM, where_str=None, **kwargs)[source]ο
Perform a similarity search with Rockset
Parameters
query (str) β Text to look up documents similar to.
distance_func (DistanceFunction) β how to compute distance between two
vectors in Rockset.
k (int, optional) β Top K neighbors to retrieve. Defaults to 4.
where_str (Optional[str], optional) β Metadata filters supplied as a
SQL where condition string. Defaults to None.
eg. βprice<=70.0 AND brand=βNintendoββ
NOTE β Please do not let end-user to fill this and always be aware
of SQL injection.
kwargs (Any) β
Returns
List of documents with their relevance score
Return type
List[Tuple[Document, float]]
similarity_search(query, k=4, distance_func=DistanceFunction.COSINE_SIM, where_str=None, **kwargs)[source]ο
Same as similarity_search_with_relevance_scores but
doesnβt return the scores.
Parameters
query (str) β
k (int) β
distance_func (DistanceFunction) β
where_str (Optional[str]) β
kwargs (Any) β
Return type
List[Document]
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-109
|
kwargs (Any) β
Return type
List[Document]
similarity_search_by_vector(embedding, k=4, distance_func=DistanceFunction.COSINE_SIM, where_str=None, **kwargs)[source]ο
Accepts a query_embedding (vector), and returns documents with
similar embeddings.
Parameters
embedding (List[float]) β
k (int) β
distance_func (DistanceFunction) β
where_str (Optional[str]) β
kwargs (Any) β
Return type
List[Document]
similarity_search_by_vector_with_relevance_scores(embedding, k=4, distance_func=DistanceFunction.COSINE_SIM, where_str=None, **kwargs)[source]ο
Accepts a query_embedding (vector), and returns documents with
similar embeddings along with their relevance scores.
Parameters
embedding (List[float]) β
k (int) β
distance_func (DistanceFunction) β
where_str (Optional[str]) β
kwargs (Any) β
Return type
List[Tuple[Document, float]]
delete_texts(ids)[source]ο
Delete a list of docs from the Rockset collection
Parameters
ids (List[str]) β
Return type
None
class langchain.vectorstores.SKLearnVectorStore(embedding, *, persist_path=None, serializer='json', metric='cosine', **kwargs)[source]ο
Bases: langchain.vectorstores.base.VectorStore
A simple in-memory vector store based on the scikit-learn library
NearestNeighbors implementation.
Parameters
embedding (langchain.embeddings.base.Embeddings) β
persist_path (Optional[str]) β
serializer (Literal['json', 'bson', 'parquet']) β
metric (str) β
kwargs (Any) β
Return type
None
persist()[source]ο
Return type
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-110
|
Return type
None
persist()[source]ο
Return type
None
add_texts(texts, metadatas=None, ids=None, **kwargs)[source]ο
Run more texts through the embeddings and add to the vectorstore.
Parameters
texts (Iterable[str]) β Iterable of strings to add to the vectorstore.
metadatas (Optional[List[dict]]) β Optional list of metadatas associated with the texts.
kwargs (Any) β vectorstore specific parameters
ids (Optional[List[str]]) β
Returns
List of ids from adding the texts into the vectorstore.
Return type
List[str]
similarity_search_with_score(query, *, k=4, **kwargs)[source]ο
Parameters
query (str) β
k (int) β
kwargs (Any) β
Return type
List[Tuple[langchain.schema.Document, float]]
similarity_search(query, k=4, **kwargs)[source]ο
Return docs most similar to query.
Parameters
query (str) β
k (int) β
kwargs (Any) β
Return type
List[langchain.schema.Document]
max_marginal_relevance_search_by_vector(embedding, k=4, fetch_k=20, lambda_mult=0.5, **kwargs)[source]ο
Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
:param embedding: Embedding to look up documents similar to.
:param k: Number of Documents to return. Defaults to 4.
:param fetch_k: Number of Documents to fetch to pass to MMR algorithm.
:param 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.
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-111
|
to maximum diversity and 1 to minimum diversity.
Defaults to 0.5.
Returns
List of Documents selected by maximal marginal relevance.
Parameters
embedding (List[float]) β
k (int) β
fetch_k (int) β
lambda_mult (float) β
kwargs (Any) β
Return type
List[langchain.schema.Document]
max_marginal_relevance_search(query, k=4, fetch_k=20, lambda_mult=0.5, **kwargs)[source]ο
Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
:param query: Text to look up documents similar to.
:param k: Number of Documents to return. Defaults to 4.
:param fetch_k: Number of Documents to fetch to pass to MMR algorithm.
:param 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 Documents selected by maximal marginal relevance.
Parameters
query (str) β
k (int) β
fetch_k (int) β
lambda_mult (float) β
kwargs (Any) β
Return type
List[langchain.schema.Document]
classmethod from_texts(texts, embedding, metadatas=None, ids=None, persist_path=None, **kwargs)[source]ο
Return VectorStore initialized from texts and embeddings.
Parameters
texts (List[str]) β
embedding (langchain.embeddings.base.Embeddings) β
metadatas (Optional[List[dict]]) β
ids (Optional[List[str]]) β
persist_path (Optional[str]) β
kwargs (Any) β
Return type
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-112
|
persist_path (Optional[str]) β
kwargs (Any) β
Return type
langchain.vectorstores.sklearn.SKLearnVectorStore
class langchain.vectorstores.StarRocks(embedding, config=None, **kwargs)[source]ο
Bases: langchain.vectorstores.base.VectorStore
Wrapper around StarRocks vector database
You need a pymysql python package, and a valid account
to connect to StarRocks.
Right now StarRocks has only implemented cosine_similarity function to
compute distance between two vectors. And there is no vector inside right now,
so we have to iterate all vectors and compute spatial distance.
For more information, please visit[StarRocks official site](https://www.starrocks.io/)
[StarRocks github](https://github.com/StarRocks/starrocks)
Parameters
embedding (Embeddings) β
config (Optional[StarRocksSettings]) β
kwargs (Any) β
Return type
None
escape_str(value)[source]ο
Parameters
value (str) β
Return type
str
add_texts(texts, metadatas=None, batch_size=32, ids=None, **kwargs)[source]ο
Insert more texts through the embeddings and add to the VectorStore.
Parameters
texts (Iterable[str]) β Iterable of strings to add to the VectorStore.
ids (Optional[Iterable[str]]) β Optional list of ids to associate with the texts.
batch_size (int) β Batch size of insertion
metadata β Optional column data to be inserted
metadatas (Optional[List[dict]]) β
kwargs (Any) β
Returns
List of ids from adding the texts into the VectorStore.
Return type
List[str]
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-113
|
List of ids from adding the texts into the VectorStore.
Return type
List[str]
classmethod from_texts(texts, embedding, metadatas=None, config=None, text_ids=None, batch_size=32, **kwargs)[source]ο
Create StarRocks wrapper with existing texts
Parameters
embedding_function (Embeddings) β Function to extract text embedding
texts (Iterable[str]) β List or tuple of strings to be added
config (StarRocksSettings, Optional) β StarRocks configuration
text_ids (Optional[Iterable], optional) β IDs for the texts.
Defaults to None.
batch_size (int, optional) β Batchsize when transmitting data to StarRocks.
Defaults to 32.
metadata (List[dict], optional) β metadata to texts. Defaults to None.
embedding (langchain.embeddings.base.Embeddings) β
metadatas (Optional[List[Dict[Any, Any]]]) β
kwargs (Any) β
Returns
StarRocks Index
Return type
langchain.vectorstores.starrocks.StarRocks
similarity_search(query, k=4, where_str=None, **kwargs)[source]ο
Perform a similarity search with StarRocks
Parameters
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 always be aware
of SQL injection. When dealing with metadatas, remember to
use {self.metadata_column}.attribute instead of attribute
alone. The default name for it is metadata.
kwargs (Any) β
Returns
List of Documents
Return type
List[Document]
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-114
|
Returns
List of Documents
Return type
List[Document]
similarity_search_by_vector(embedding, k=4, where_str=None, **kwargs)[source]ο
Perform a similarity search with StarRocks by vectors
Parameters
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 always be aware
of SQL injection. When dealing with metadatas, remember to
use {self.metadata_column}.attribute instead of attribute
alone. The default name for it is metadata.
embedding (List[float]) β
kwargs (Any) β
Returns
List of (Document, similarity)
Return type
List[Document]
similarity_search_with_relevance_scores(query, k=4, where_str=None, **kwargs)[source]ο
Perform a similarity search with StarRocks
Parameters
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 always be aware
of SQL injection. When dealing with metadatas, remember to
use {self.metadata_column}.attribute instead of attribute
alone. The default name for it is metadata.
kwargs (Any) β
Returns
List of documents
Return type
List[Document]
drop()[source]ο
Helper function: Drop data
Return type
None
property metadata_column: strο
class langchain.vectorstores.SupabaseVectorStore(client, embedding, table_name, query_name=None)[source]ο
Bases: langchain.vectorstores.base.VectorStore
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-115
|
Bases: langchain.vectorstores.base.VectorStore
VectorStore for a Supabase postgres database. Assumes you have the pgvector
extension installed and a match_documents (or similar) function. For more details:
https://js.langchain.com/docs/modules/indexes/vector_stores/integrations/supabase
You can implement your own match_documents function in order to limit the search
space to a subset of documents based on your own authorization or business logic.
Note that the Supabase Python client does not yet support async operations.
If youβd like to use max_marginal_relevance_search, please review the instructions
below on modifying the match_documents function to return matched embeddings.
Parameters
client (supabase.client.Client) β
embedding (Embeddings) β
table_name (str) β
query_name (Union[str, None]) β
Return type
None
table_name: strο
query_name: strο
add_texts(texts, metadatas=None, ids=None, **kwargs)[source]ο
Run more texts through the embeddings and add to the vectorstore.
Parameters
texts (Iterable[str]) β Iterable of strings to add to the vectorstore.
metadatas (Optional[List[dict[Any, Any]]]) β Optional list of metadatas associated with the texts.
kwargs (Any) β vectorstore specific parameters
ids (Optional[List[str]]) β
Returns
List of ids from adding the texts into the vectorstore.
Return type
List[str]
classmethod from_texts(texts, embedding, metadatas=None, client=None, table_name='documents', query_name='match_documents', ids=None, **kwargs)[source]ο
Return VectorStore initialized from texts and embeddings.
Parameters
texts (List[str]) β
embedding (Embeddings) β
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-116
|
Parameters
texts (List[str]) β
embedding (Embeddings) β
metadatas (Optional[List[dict]]) β
client (Optional[supabase.client.Client]) β
table_name (Optional[str]) β
query_name (Union[str, None]) β
ids (Optional[List[str]]) β
kwargs (Any) β
Return type
SupabaseVectorStore
add_vectors(vectors, documents, ids)[source]ο
Parameters
vectors (List[List[float]]) β
documents (List[langchain.schema.Document]) β
ids (List[str]) β
Return type
List[str]
similarity_search(query, k=4, **kwargs)[source]ο
Return docs most similar to query.
Parameters
query (str) β
k (int) β
kwargs (Any) β
Return type
List[langchain.schema.Document]
similarity_search_by_vector(embedding, k=4, **kwargs)[source]ο
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[langchain.schema.Document]
similarity_search_with_relevance_scores(query, k=4, **kwargs)[source]ο
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 β kwargs to be passed to similarity search. Should include:
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-117
|
**kwargs β 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
kwargs (Any) β
Returns
List of Tuples of (doc, similarity_score)
Return type
List[Tuple[langchain.schema.Document, float]]
similarity_search_by_vector_with_relevance_scores(query, k)[source]ο
Parameters
query (List[float]) β
k (int) β
Return type
List[Tuple[langchain.schema.Document, float]]
similarity_search_by_vector_returning_embeddings(query, k)[source]ο
Parameters
query (List[float]) β
k (int) β
Return type
List[Tuple[langchain.schema.Document, float, numpy.ndarray[numpy.float32, Any]]]
max_marginal_relevance_search_by_vector(embedding, k=4, fetch_k=20, lambda_mult=0.5, **kwargs)[source]ο
Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
Parameters
embedding (List[float]) β Embedding to look up documents similar to.
k (int) β Number of Documents to return. Defaults to 4.
fetch_k (int) β Number of Documents to fetch to pass to MMR algorithm.
lambda_mult (float) β 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.
kwargs (Any) β
Returns
List of Documents selected by maximal marginal relevance.
Return type
List[langchain.schema.Document]
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-118
|
Return type
List[langchain.schema.Document]
max_marginal_relevance_search(query, k=4, fetch_k=20, lambda_mult=0.5, **kwargs)[source]ο
Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
Parameters
query (str) β Text to look up documents similar to.
k (int) β Number of Documents to return. Defaults to 4.
fetch_k (int) β Number of Documents to fetch to pass to MMR algorithm.
lambda_mult (float) β 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.
kwargs (Any) β
Returns
List of Documents selected by maximal marginal relevance.
Return type
List[langchain.schema.Document]
max_marginal_relevance_search requires that query_name returns matched
embeddings alongside the match documents. The following function
demonstrates how to do this:
```sql
CREATE FUNCTION match_documents_embeddings(query_embedding vector(1536),
match_count int)
RETURNS TABLE(id bigint,
content text,
metadata jsonb,
embedding vector(1536),
similarity float)
LANGUAGE plpgsql
AS $$
# variable_conflict use_column
BEGINRETURN query
SELECT
id,
content,
metadata,
embedding,
1 -(docstore.embedding <=> query_embedding) AS similarity
FROMdocstore
ORDER BYdocstore.embedding <=> query_embedding
LIMIT match_count;
END;
$$;
```
delete(ids)[source]ο
Delete by vector IDs.
Parameters
ids (List[str]) β List of ids to delete.
Return type
None
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-119
|
Parameters
ids (List[str]) β List of ids to delete.
Return type
None
class langchain.vectorstores.Tair(embedding_function, url, index_name, content_key='content', metadata_key='metadata', search_params=None, **kwargs)[source]ο
Bases: langchain.vectorstores.base.VectorStore
Wrapper around Tair Vector store.
Parameters
embedding_function (Embeddings) β
url (str) β
index_name (str) β
content_key (str) β
metadata_key (str) β
search_params (Optional[dict]) β
kwargs (Any) β
create_index_if_not_exist(dim, distance_type, index_type, data_type, **kwargs)[source]ο
Parameters
dim (int) β
distance_type (str) β
index_type (str) β
data_type (str) β
kwargs (Any) β
Return type
bool
add_texts(texts, metadatas=None, **kwargs)[source]ο
Add texts data to an existing index.
Parameters
texts (Iterable[str]) β
metadatas (Optional[List[dict]]) β
kwargs (Any) β
Return type
List[str]
similarity_search(query, k=4, **kwargs)[source]ο
Returns the most similar indexed documents to the query text.
Parameters
query (str) β The query text for which to find similar documents.
k (int) β The number of documents to return. Default is 4.
kwargs (Any) β
Returns
A list of documents that are most similar to the query text.
Return type
List[Document]
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-120
|
Return type
List[Document]
classmethod from_texts(texts, embedding, metadatas=None, index_name='langchain', content_key='content', metadata_key='metadata', **kwargs)[source]ο
Return VectorStore initialized from texts and embeddings.
Parameters
texts (List[str]) β
embedding (langchain.embeddings.base.Embeddings) β
metadatas (Optional[List[dict]]) β
index_name (str) β
content_key (str) β
metadata_key (str) β
kwargs (Any) β
Return type
langchain.vectorstores.tair.Tair
classmethod from_documents(documents, embedding, metadatas=None, index_name='langchain', content_key='content', metadata_key='metadata', **kwargs)[source]ο
Return VectorStore initialized from documents and embeddings.
Parameters
documents (List[langchain.schema.Document]) β
embedding (langchain.embeddings.base.Embeddings) β
metadatas (Optional[List[dict]]) β
index_name (str) β
content_key (str) β
metadata_key (str) β
kwargs (Any) β
Return type
langchain.vectorstores.tair.Tair
static drop_index(index_name='langchain', **kwargs)[source]ο
Drop an existing index.
Parameters
index_name (str) β Name of the index to drop.
kwargs (Any) β
Returns
True if the index is dropped successfully.
Return type
bool
classmethod from_existing_index(embedding, index_name='langchain', content_key='content', metadata_key='metadata', **kwargs)[source]ο
Connect to an existing Tair index.
Parameters
embedding (langchain.embeddings.base.Embeddings) β
index_name (str) β
content_key (str) β
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-121
|
index_name (str) β
content_key (str) β
metadata_key (str) β
kwargs (Any) β
Return type
langchain.vectorstores.tair.Tair
class langchain.vectorstores.Tigris(client, embeddings, index_name)[source]ο
Bases: langchain.vectorstores.base.VectorStore
Parameters
client (TigrisClient) β
embeddings (Embeddings) β
index_name (str) β
property search_index: TigrisVectorStoreο
add_texts(texts, metadatas=None, ids=None, **kwargs)[source]ο
Run more texts through the embeddings and add to the vectorstore.
Parameters
texts (Iterable[str]) β Iterable of strings to add to the vectorstore.
metadatas (Optional[List[dict]]) β Optional list of metadatas associated with the texts.
ids (Optional[List[str]]) β Optional list of ids for documents.
Ids will be autogenerated if not provided.
kwargs (Any) β vectorstore specific parameters
Returns
List of ids from adding the texts into the vectorstore.
Return type
List[str]
similarity_search(query, k=4, filter=None, **kwargs)[source]ο
Return docs most similar to query.
Parameters
query (str) β
k (int) β
filter (Optional[TigrisFilter]) β
kwargs (Any) β
Return type
List[Document]
similarity_search_with_score(query, k=4, filter=None)[source]ο
Run similarity search with Chroma with distance.
Parameters
query (str) β Query text to search for.
k (int) β Number of results to return. Defaults to 4.
filter (Optional[TigrisFilter]) β Filter by metadata. Defaults to None.
Returns
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-122
|
filter (Optional[TigrisFilter]) β Filter by metadata. Defaults to None.
Returns
List of documents most similar to the querytext with distance in float.
Return type
List[Tuple[Document, float]]
classmethod from_texts(texts, embedding, metadatas=None, ids=None, client=None, index_name=None, **kwargs)[source]ο
Return VectorStore initialized from texts and embeddings.
Parameters
texts (List[str]) β
embedding (Embeddings) β
metadatas (Optional[List[dict]]) β
ids (Optional[List[str]]) β
client (Optional[TigrisClient]) β
index_name (Optional[str]) β
kwargs (Any) β
Return type
Tigris
class langchain.vectorstores.Typesense(typesense_client, embedding, *, typesense_collection_name=None, text_key='text')[source]ο
Bases: langchain.vectorstores.base.VectorStore
Wrapper around Typesense vector search.
To use, you should have the typesense python package installed.
Example
from langchain.embedding.openai import OpenAIEmbeddings
from langchain.vectorstores import Typesense
import typesense
node = {
"host": "localhost", # For Typesense Cloud use xxx.a1.typesense.net
"port": "8108", # For Typesense Cloud use 443
"protocol": "http" # For Typesense Cloud use https
}
typesense_client = typesense.Client(
{
"nodes": [node],
"api_key": "<API_KEY>",
"connection_timeout_seconds": 2
}
)
typesense_collection_name = "langchain-memory"
embedding = OpenAIEmbeddings()
vectorstore = Typesense(
typesense_client=typesense_client,
embedding=embedding,
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-123
|
typesense_client=typesense_client,
embedding=embedding,
typesense_collection_name=typesense_collection_name,
text_key="text",
)
Parameters
typesense_client (Client) β
embedding (Embeddings) β
typesense_collection_name (Optional[str]) β
text_key (str) β
add_texts(texts, metadatas=None, ids=None, **kwargs)[source]ο
Run more texts through the embedding and add to the vectorstore.
Parameters
texts (Iterable[str]) β Iterable of strings to add to the vectorstore.
metadatas (Optional[List[dict]]) β Optional list of metadatas associated with the texts.
ids (Optional[List[str]]) β Optional list of ids to associate with the texts.
kwargs (Any) β
Returns
List of ids from adding the texts into the vectorstore.
Return type
List[str]
similarity_search_with_score(query, k=10, filter='')[source]ο
Return typesense documents most similar to query, along with scores.
Parameters
query (str) β Text to look up documents similar to.
k (int) β Number of Documents to return. Defaults to 10.
Minimum 10 results would be returned.
filter (Optional[str]) β typesense filter_by expression to filter documents on
Returns
List of Documents most similar to the query and score for each
Return type
List[Tuple[langchain.schema.Document, float]]
similarity_search(query, k=10, filter='', **kwargs)[source]ο
Return typesense documents most similar to query.
Parameters
query (str) β Text to look up documents similar to.
k (int) β Number of Documents to return. Defaults to 10.
Minimum 10 results would be returned.
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-124
|
Minimum 10 results would be returned.
filter (Optional[str]) β typesense filter_by expression to filter documents on
kwargs (Any) β
Returns
List of Documents most similar to the query and score for each
Return type
List[langchain.schema.Document]
classmethod from_client_params(embedding, *, host='localhost', port='8108', protocol='http', typesense_api_key=None, connection_timeout_seconds=2, **kwargs)[source]ο
Initialize Typesense directly from client parameters.
Example
from langchain.embedding.openai import OpenAIEmbeddings
from langchain.vectorstores import Typesense
# Pass in typesense_api_key as kwarg or set env var "TYPESENSE_API_KEY".
vectorstore = Typesense(
OpenAIEmbeddings(),
host="localhost",
port="8108",
protocol="http",
typesense_collection_name="langchain-memory",
)
Parameters
embedding (langchain.embeddings.base.Embeddings) β
host (str) β
port (Union[str, int]) β
protocol (str) β
typesense_api_key (Optional[str]) β
connection_timeout_seconds (int) β
kwargs (Any) β
Return type
langchain.vectorstores.typesense.Typesense
classmethod from_texts(texts, embedding, metadatas=None, ids=None, typesense_client=None, typesense_client_params=None, typesense_collection_name=None, text_key='text', **kwargs)[source]ο
Construct Typesense wrapper from raw text.
Parameters
texts (List[str]) β
embedding (Embeddings) β
metadatas (Optional[List[dict]]) β
ids (Optional[List[str]]) β
typesense_client (Optional[Client]) β
typesense_client_params (Optional[dict]) β
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-125
|
typesense_client_params (Optional[dict]) β
typesense_collection_name (Optional[str]) β
text_key (str) β
kwargs (Any) β
Return type
Typesense
class langchain.vectorstores.Vectara(vectara_customer_id=None, vectara_corpus_id=None, vectara_api_key=None)[source]ο
Bases: langchain.vectorstores.base.VectorStore
Implementation of Vector Store using Vectara (https://vectara.com).
.. rubric:: Example
from langchain.vectorstores import Vectara
vectorstore = Vectara(
vectara_customer_id=vectara_customer_id,
vectara_corpus_id=vectara_corpus_id,
vectara_api_key=vectara_api_key
)
Parameters
vectara_customer_id (Optional[str]) β
vectara_corpus_id (Optional[str]) β
vectara_api_key (Optional[str]) β
add_texts(texts, metadatas=None, **kwargs)[source]ο
Run more texts through the embeddings and add to the vectorstore.
Parameters
texts (Iterable[str]) β Iterable of strings to add to the vectorstore.
metadatas (Optional[List[dict]]) β Optional list of metadatas associated with the texts.
kwargs (Any) β
Returns
List of ids from adding the texts into the vectorstore.
Return type
List[str]
similarity_search_with_score(query, k=5, lambda_val=0.025, filter=None, n_sentence_context=0, **kwargs)[source]ο
Return Vectara documents most similar to query, along with scores.
Parameters
query (str) β Text to look up documents similar to.
k (int) β Number of Documents to return. Defaults to 5.
lambda_val (float) β lexical match parameter for hybrid search.
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-126
|
lambda_val (float) β lexical match parameter for hybrid search.
filter (Optional[str]) β Dictionary of argument(s) to filter on metadata. For example a
filter can be βdoc.rating > 3.0 and part.lang = βdeuββ} see
https://docs.vectara.com/docs/search-apis/sql/filter-overview
for more details.
n_sentence_context (int) β number of sentences before/after the matching segment
to add
kwargs (Any) β
Returns
List of Documents most similar to the query and score for each.
Return type
List[Tuple[langchain.schema.Document, float]]
similarity_search(query, k=5, lambda_val=0.025, filter=None, n_sentence_context=0, **kwargs)[source]ο
Return Vectara documents most similar to query, along with scores.
Parameters
query (str) β Text to look up documents similar to.
k (int) β Number of Documents to return. Defaults to 5.
filter (Optional[str]) β Dictionary of argument(s) to filter on metadata. For example a
filter can be βdoc.rating > 3.0 and part.lang = βdeuββ} see
https://docs.vectara.com/docs/search-apis/sql/filter-overview for more
details.
n_sentence_context (int) β number of sentences before/after the matching segment
to add
lambda_val (float) β
kwargs (Any) β
Returns
List of Documents most similar to the query
Return type
List[langchain.schema.Document]
classmethod from_texts(texts, embedding=None, metadatas=None, **kwargs)[source]ο
Construct Vectara wrapper from raw documents.
This is intended to be a quick way to get started.
.. rubric:: Example
from langchain import Vectara
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-127
|
.. rubric:: Example
from langchain import Vectara
vectara = Vectara.from_texts(
texts,
vectara_customer_id=customer_id,
vectara_corpus_id=corpus_id,
vectara_api_key=api_key,
)
Parameters
texts (List[str]) β
embedding (Optional[langchain.embeddings.base.Embeddings]) β
metadatas (Optional[List[dict]]) β
kwargs (Any) β
Return type
langchain.vectorstores.vectara.Vectara
as_retriever(**kwargs)[source]ο
Parameters
kwargs (Any) β
Return type
langchain.vectorstores.vectara.VectaraRetriever
class langchain.vectorstores.VectorStore[source]ο
Bases: abc.ABC
Interface for vector stores.
abstract add_texts(texts, metadatas=None, **kwargs)[source]ο
Run more texts through the embeddings and add to the vectorstore.
Parameters
texts (Iterable[str]) β Iterable of strings to add to the vectorstore.
metadatas (Optional[List[dict]]) β Optional list of metadatas associated with the texts.
kwargs (Any) β vectorstore specific parameters
Returns
List of ids from adding the texts into the vectorstore.
Return type
List[str]
delete(ids)[source]ο
Delete by vector ID.
Parameters
ids (List[str]) β List of ids to delete.
Returns
True if deletion is successful,
False otherwise, None if not implemented.
Return type
Optional[bool]
async aadd_texts(texts, metadatas=None, **kwargs)[source]ο
Run more texts through the embeddings and add to the vectorstore.
Parameters
texts (Iterable[str]) β
metadatas (Optional[List[dict]]) β
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-128
|
texts (Iterable[str]) β
metadatas (Optional[List[dict]]) β
kwargs (Any) β
Return type
List[str]
add_documents(documents, **kwargs)[source]ο
Run more documents through the embeddings and add to the vectorstore.
Parameters
(List[Document] (documents) β Documents to add to the vectorstore.
documents (List[langchain.schema.Document]) β
kwargs (Any) β
Returns
List of IDs of the added texts.
Return type
List[str]
async aadd_documents(documents, **kwargs)[source]ο
Run more documents through the embeddings and add to the vectorstore.
Parameters
(List[Document] (documents) β Documents to add to the vectorstore.
documents (List[langchain.schema.Document]) β
kwargs (Any) β
Returns
List of IDs of the added texts.
Return type
List[str]
search(query, search_type, **kwargs)[source]ο
Return docs most similar to query using specified search type.
Parameters
query (str) β
search_type (str) β
kwargs (Any) β
Return type
List[langchain.schema.Document]
async asearch(query, search_type, **kwargs)[source]ο
Return docs most similar to query using specified search type.
Parameters
query (str) β
search_type (str) β
kwargs (Any) β
Return type
List[langchain.schema.Document]
abstract similarity_search(query, k=4, **kwargs)[source]ο
Return docs most similar to query.
Parameters
query (str) β
k (int) β
kwargs (Any) β
Return type
List[langchain.schema.Document]
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-129
|
kwargs (Any) β
Return type
List[langchain.schema.Document]
similarity_search_with_relevance_scores(query, k=4, **kwargs)[source]ο
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 β 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
kwargs (Any) β
Returns
List of Tuples of (doc, similarity_score)
Return type
List[Tuple[langchain.schema.Document, float]]
async asimilarity_search_with_relevance_scores(query, k=4, **kwargs)[source]ο
Return docs most similar to query.
Parameters
query (str) β
k (int) β
kwargs (Any) β
Return type
List[Tuple[langchain.schema.Document, float]]
async asimilarity_search(query, k=4, **kwargs)[source]ο
Return docs most similar to query.
Parameters
query (str) β
k (int) β
kwargs (Any) β
Return type
List[langchain.schema.Document]
similarity_search_by_vector(embedding, k=4, **kwargs)[source]ο
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[langchain.schema.Document]
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-130
|
Return type
List[langchain.schema.Document]
async asimilarity_search_by_vector(embedding, k=4, **kwargs)[source]ο
Return docs most similar to embedding vector.
Parameters
embedding (List[float]) β
k (int) β
kwargs (Any) β
Return type
List[langchain.schema.Document]
max_marginal_relevance_search(query, k=4, fetch_k=20, lambda_mult=0.5, **kwargs)[source]ο
Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
Parameters
query (str) β Text to look up documents similar to.
k (int) β Number of Documents to return. Defaults to 4.
fetch_k (int) β Number of Documents to fetch to pass to MMR algorithm.
lambda_mult (float) β 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.
kwargs (Any) β
Returns
List of Documents selected by maximal marginal relevance.
Return type
List[langchain.schema.Document]
async amax_marginal_relevance_search(query, k=4, fetch_k=20, lambda_mult=0.5, **kwargs)[source]ο
Return docs selected using the maximal marginal relevance.
Parameters
query (str) β
k (int) β
fetch_k (int) β
lambda_mult (float) β
kwargs (Any) β
Return type
List[langchain.schema.Document]
max_marginal_relevance_search_by_vector(embedding, k=4, fetch_k=20, lambda_mult=0.5, **kwargs)[source]ο
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-131
|
Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
Parameters
embedding (List[float]) β Embedding to look up documents similar to.
k (int) β Number of Documents to return. Defaults to 4.
fetch_k (int) β Number of Documents to fetch to pass to MMR algorithm.
lambda_mult (float) β 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.
kwargs (Any) β
Returns
List of Documents selected by maximal marginal relevance.
Return type
List[langchain.schema.Document]
async amax_marginal_relevance_search_by_vector(embedding, k=4, fetch_k=20, lambda_mult=0.5, **kwargs)[source]ο
Return docs selected using the maximal marginal relevance.
Parameters
embedding (List[float]) β
k (int) β
fetch_k (int) β
lambda_mult (float) β
kwargs (Any) β
Return type
List[langchain.schema.Document]
classmethod from_documents(documents, embedding, **kwargs)[source]ο
Return VectorStore initialized from documents and embeddings.
Parameters
documents (List[langchain.schema.Document]) β
embedding (langchain.embeddings.base.Embeddings) β
kwargs (Any) β
Return type
langchain.vectorstores.base.VST
async classmethod afrom_documents(documents, embedding, **kwargs)[source]ο
Return VectorStore initialized from documents and embeddings.
Parameters
documents (List[langchain.schema.Document]) β
embedding (langchain.embeddings.base.Embeddings) β
kwargs (Any) β
Return type
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-132
|
kwargs (Any) β
Return type
langchain.vectorstores.base.VST
abstract classmethod from_texts(texts, embedding, metadatas=None, **kwargs)[source]ο
Return VectorStore initialized from texts and embeddings.
Parameters
texts (List[str]) β
embedding (langchain.embeddings.base.Embeddings) β
metadatas (Optional[List[dict]]) β
kwargs (Any) β
Return type
langchain.vectorstores.base.VST
async classmethod afrom_texts(texts, embedding, metadatas=None, **kwargs)[source]ο
Return VectorStore initialized from texts and embeddings.
Parameters
texts (List[str]) β
embedding (langchain.embeddings.base.Embeddings) β
metadatas (Optional[List[dict]]) β
kwargs (Any) β
Return type
langchain.vectorstores.base.VST
as_retriever(**kwargs)[source]ο
Parameters
kwargs (Any) β
Return type
langchain.vectorstores.base.VectorStoreRetriever
class langchain.vectorstores.Weaviate(client, index_name, text_key, embedding=None, attributes=None, relevance_score_fn=<function _default_score_normalizer>, by_text=True)[source]ο
Bases: langchain.vectorstores.base.VectorStore
Wrapper around Weaviate vector database.
To use, you should have the weaviate-client python package installed.
Example
import weaviate
from langchain.vectorstores import Weaviate
client = weaviate.Client(url=os.environ["WEAVIATE_URL"], ...)
weaviate = Weaviate(client, index_name, text_key)
Parameters
client (Any) β
index_name (str) β
text_key (str) β
embedding (Optional[Embeddings]) β
attributes (Optional[List[str]]) β
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-133
|
embedding (Optional[Embeddings]) β
attributes (Optional[List[str]]) β
relevance_score_fn (Optional[Callable[[float], float]]) β
by_text (bool) β
add_texts(texts, metadatas=None, **kwargs)[source]ο
Upload texts with metadata (properties) to Weaviate.
Parameters
texts (Iterable[str]) β
metadatas (Optional[List[dict]]) β
kwargs (Any) β
Return type
List[str]
similarity_search(query, k=4, **kwargs)[source]ο
Return docs most similar to query.
Parameters
query (str) β Text 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.
Return type
List[langchain.schema.Document]
similarity_search_by_text(query, k=4, **kwargs)[source]ο
Return docs most similar to query.
Parameters
query (str) β Text 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.
Return type
List[langchain.schema.Document]
similarity_search_by_vector(embedding, k=4, **kwargs)[source]ο
Look up similar documents by embedding vector in Weaviate.
Parameters
embedding (List[float]) β
k (int) β
kwargs (Any) β
Return type
List[langchain.schema.Document]
max_marginal_relevance_search(query, k=4, fetch_k=20, lambda_mult=0.5, **kwargs)[source]ο
Return docs selected using the maximal marginal relevance.
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-134
|
Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
Parameters
query (str) β Text to look up documents similar to.
k (int) β Number of Documents to return. Defaults to 4.
fetch_k (int) β Number of Documents to fetch to pass to MMR algorithm.
lambda_mult (float) β 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.
kwargs (Any) β
Returns
List of Documents selected by maximal marginal relevance.
Return type
List[langchain.schema.Document]
max_marginal_relevance_search_by_vector(embedding, k=4, fetch_k=20, lambda_mult=0.5, **kwargs)[source]ο
Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
Parameters
embedding (List[float]) β Embedding to look up documents similar to.
k (int) β Number of Documents to return. Defaults to 4.
fetch_k (int) β Number of Documents to fetch to pass to MMR algorithm.
lambda_mult (float) β 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.
kwargs (Any) β
Returns
List of Documents selected by maximal marginal relevance.
Return type
List[langchain.schema.Document]
similarity_search_with_score(query, k=4, **kwargs)[source]ο
Return list of documents most similar to the query
text and cosine distance in float for each.
Lower score represents more similarity.
Parameters
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
c018b0edb28a-135
|
text and cosine distance in float for each.
Lower score represents more similarity.
Parameters
query (str) β
k (int) β
kwargs (Any) β
Return type
List[Tuple[langchain.schema.Document, float]]
classmethod from_texts(texts, embedding, metadatas=None, **kwargs)[source]ο
Construct Weaviate wrapper from raw documents.
This is a user-friendly interface that:
Embeds documents.
Creates a new index for the embeddings in the Weaviate instance.
Adds the documents to the newly created Weaviate index.
This is intended to be a quick way to get started.
Example
from langchain.vectorstores.weaviate import Weaviate
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
weaviate = Weaviate.from_texts(
texts,
embeddings,
weaviate_url="http://localhost:8080"
)
Parameters
texts (List[str]) β
embedding (langchain.embeddings.base.Embeddings) β
metadatas (Optional[List[dict]]) β
kwargs (Any) β
Return type
langchain.vectorstores.weaviate.Weaviate
delete(ids)[source]ο
Delete by vector IDs.
Parameters
ids (List[str]) β List of ids to delete.
Return type
None
|
https://api.python.langchain.com/en/latest/modules/vectorstores.html
|
ff6d0b7b0742-0
|
LLMsο
Wrappers on top of large language models APIs.
class langchain.llms.AI21(*, cache=None, verbose=None, callbacks=None, callback_manager=None, tags=None, model='j2-jumbo-instruct', temperature=0.7, maxTokens=256, minTokens=0, topP=1.0, presencePenalty=AI21PenaltyData(scale=0, applyToWhitespaces=True, applyToPunctuations=True, applyToNumbers=True, applyToStopwords=True, applyToEmojis=True), countPenalty=AI21PenaltyData(scale=0, applyToWhitespaces=True, applyToPunctuations=True, applyToNumbers=True, applyToStopwords=True, applyToEmojis=True), frequencyPenalty=AI21PenaltyData(scale=0, applyToWhitespaces=True, applyToPunctuations=True, applyToNumbers=True, applyToStopwords=True, applyToEmojis=True), numResults=1, logitBias=None, ai21_api_key=None, stop=None, base_url=None)[source]ο
Bases: langchain.llms.base.LLM
Wrapper around AI21 large language models.
To use, you should have the environment variable AI21_API_KEY
set with your API key.
Example
from langchain.llms import AI21
ai21 = AI21(model="j2-jumbo-instruct")
Parameters
cache (Optional[bool]) β
verbose (bool) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) β
tags (Optional[List[str]]) β
model (str) β
temperature (float) β
maxTokens (int) β
minTokens (int) β
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-1
|
maxTokens (int) β
minTokens (int) β
topP (float) β
presencePenalty (langchain.llms.ai21.AI21PenaltyData) β
countPenalty (langchain.llms.ai21.AI21PenaltyData) β
frequencyPenalty (langchain.llms.ai21.AI21PenaltyData) β
numResults (int) β
logitBias (Optional[Dict[str, float]]) β
ai21_api_key (Optional[str]) β
stop (Optional[List[str]]) β
base_url (Optional[str]) β
Return type
None
attribute base_url: Optional[str] = Noneο
Base url to use, if None decides based on model name.
attribute countPenalty: langchain.llms.ai21.AI21PenaltyData = AI21PenaltyData(scale=0, applyToWhitespaces=True, applyToPunctuations=True, applyToNumbers=True, applyToStopwords=True, applyToEmojis=True)ο
Penalizes repeated tokens according to count.
attribute frequencyPenalty: langchain.llms.ai21.AI21PenaltyData = AI21PenaltyData(scale=0, applyToWhitespaces=True, applyToPunctuations=True, applyToNumbers=True, applyToStopwords=True, applyToEmojis=True)ο
Penalizes repeated tokens according to frequency.
attribute logitBias: Optional[Dict[str, float]] = Noneο
Adjust the probability of specific tokens being generated.
attribute maxTokens: int = 256ο
The maximum number of tokens to generate in the completion.
attribute minTokens: int = 0ο
The minimum number of tokens to generate in the completion.
attribute model: str = 'j2-jumbo-instruct'ο
Model name to use.
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-2
|
Model name to use.
attribute numResults: int = 1ο
How many completions to generate for each prompt.
attribute presencePenalty: langchain.llms.ai21.AI21PenaltyData = AI21PenaltyData(scale=0, applyToWhitespaces=True, applyToPunctuations=True, applyToNumbers=True, applyToStopwords=True, applyToEmojis=True)ο
Penalizes repeated tokens.
attribute tags: Optional[List[str]] = Noneο
Tags to add to the run trace.
attribute temperature: float = 0.7ο
What sampling temperature to use.
attribute topP: float = 1.0ο
Total probability mass of tokens to consider at each step.
attribute verbose: bool [Optional]ο
Whether to print out response text.
__call__(prompt, stop=None, callbacks=None, **kwargs)ο
Check Cache and run the LLM on the given prompt and input.
Parameters
prompt (str) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
kwargs (Any) β
Return type
str
async agenerate(prompts, stop=None, callbacks=None, *, tags=None, **kwargs)ο
Run the LLM on the given prompt and input.
Parameters
prompts (List[str]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
tags (Optional[List[str]]) β
kwargs (Any) β
Return type
langchain.schema.LLMResult
async agenerate_prompt(prompts, stop=None, callbacks=None, **kwargs)ο
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-3
|
async agenerate_prompt(prompts, stop=None, callbacks=None, **kwargs)ο
Take in a list of prompt values and return an LLMResult.
Parameters
prompts (List[langchain.schema.PromptValue]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
kwargs (Any) β
Return type
langchain.schema.LLMResult
async apredict(text, *, stop=None, **kwargs)ο
Predict text from text.
Parameters
text (str) β
stop (Optional[Sequence[str]]) β
kwargs (Any) β
Return type
str
async apredict_messages(messages, *, stop=None, **kwargs)ο
Predict message from messages.
Parameters
messages (List[langchain.schema.BaseMessage]) β
stop (Optional[Sequence[str]]) β
kwargs (Any) β
Return type
langchain.schema.BaseMessage
classmethod construct(_fields_set=None, **values)ο
Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.
Default values are respected, but no other validation is performed.
Behaves as if Config.extra = βallowβ was set since it adds all passed values
Parameters
_fields_set (Optional[SetStr]) β
values (Any) β
Return type
Model
copy(*, include=None, exclude=None, update=None, deep=False)ο
Duplicate a model, optionally choose which fields to include, exclude and change.
Parameters
include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) β fields to include in new model
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-4
|
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(**kwargs)ο
Return a dictionary of the LLM.
Parameters
kwargs (Any) β
Return type
Dict
generate(prompts, stop=None, callbacks=None, *, tags=None, **kwargs)ο
Run the LLM on the given prompt and input.
Parameters
prompts (List[str]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
tags (Optional[List[str]]) β
kwargs (Any) β
Return type
langchain.schema.LLMResult
generate_prompt(prompts, stop=None, callbacks=None, **kwargs)ο
Take in a list of prompt values and return an LLMResult.
Parameters
prompts (List[langchain.schema.PromptValue]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
kwargs (Any) β
Return type
langchain.schema.LLMResult
get_num_tokens(text)ο
Get the number of tokens present in the text.
Parameters
text (str) β
Return type
int
get_num_tokens_from_messages(messages)ο
Get the number of tokens in the message.
Parameters
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-5
|
Get the number of tokens in the message.
Parameters
messages (List[langchain.schema.BaseMessage]) β
Return type
int
get_token_ids(text)ο
Get the token present in the text.
Parameters
text (str) β
Return type
List[int]
json(*, include=None, exclude=None, by_alias=False, skip_defaults=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, encoder=None, models_as_dict=True, **dumps_kwargs)ο
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
predict(text, *, stop=None, **kwargs)ο
Predict text from text.
Parameters
text (str) β
stop (Optional[Sequence[str]]) β
kwargs (Any) β
Return type
str
predict_messages(messages, *, stop=None, **kwargs)ο
Predict message from messages.
Parameters
messages (List[langchain.schema.BaseMessage]) β
stop (Optional[Sequence[str]]) β
kwargs (Any) β
Return type
langchain.schema.BaseMessage
save(file_path)ο
Save the LLM.
Parameters
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-6
|
save(file_path)ο
Save the LLM.
Parameters
file_path (Union[pathlib.Path, str]) β Path to file to save the LLM to.
Return type
None
Example:
.. code-block:: python
llm.save(file_path=βpath/llm.yamlβ)
classmethod update_forward_refs(**localns)ο
Try to update ForwardRefs on fields based on this Model, globalns and localns.
Parameters
localns (Any) β
Return type
None
property lc_attributes: Dictο
Return a list of attribute names that should be included in the
serialized kwargs. These attributes must be accepted by the
constructor.
property lc_namespace: List[str]ο
Return the namespace of the langchain object.
eg. [βlangchainβ, βllmsβ, βopenaiβ]
property lc_secrets: Dict[str, str]ο
Return a map of constructor argument names to secret ids.
eg. {βopenai_api_keyβ: βOPENAI_API_KEYβ}
property lc_serializable: boolο
Return whether or not the class is serializable.
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-7
|
property lc_serializable: boolο
Return whether or not the class is serializable.
class langchain.llms.AlephAlpha(*, cache=None, verbose=None, callbacks=None, callback_manager=None, tags=None, client=None, model='luminous-base', maximum_tokens=64, temperature=0.0, top_k=0, top_p=0.0, presence_penalty=0.0, frequency_penalty=0.0, repetition_penalties_include_prompt=False, use_multiplicative_presence_penalty=False, penalty_bias=None, penalty_exceptions=None, penalty_exceptions_include_stop_sequences=None, best_of=None, n=1, logit_bias=None, log_probs=None, tokens=False, disable_optimizations=False, minimum_tokens=0, echo=False, use_multiplicative_frequency_penalty=False, sequence_penalty=0.0, sequence_penalty_min_length=2, use_multiplicative_sequence_penalty=False, completion_bias_inclusion=None, completion_bias_inclusion_first_token_only=False, completion_bias_exclusion=None, completion_bias_exclusion_first_token_only=False, contextual_control_threshold=None, control_log_additive=True, repetition_penalties_include_completion=True, raw_completion=False, aleph_alpha_api_key=None, stop_sequences=None)[source]ο
Bases: langchain.llms.base.LLM
Wrapper around Aleph Alpha large language models.
To use, you should have the aleph_alpha_client python package installed, and the
environment variable ALEPH_ALPHA_API_KEY set with your API key, or pass
it as a named parameter to the constructor.
Parameters are explained more in depth here:
https://github.com/Aleph-Alpha/aleph-alpha-client/blob/c14b7dd2b4325c7da0d6a119f6e76385800e097b/aleph_alpha_client/completion.py#L10
Example
from langchain.llms import AlephAlpha
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-8
|
Example
from langchain.llms import AlephAlpha
aleph_alpha = AlephAlpha(aleph_alpha_api_key="my-api-key")
Parameters
cache (Optional[bool]) β
verbose (bool) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) β
tags (Optional[List[str]]) β
client (Any) β
model (Optional[str]) β
maximum_tokens (int) β
temperature (float) β
top_k (int) β
top_p (float) β
presence_penalty (float) β
frequency_penalty (float) β
repetition_penalties_include_prompt (Optional[bool]) β
use_multiplicative_presence_penalty (Optional[bool]) β
penalty_bias (Optional[str]) β
penalty_exceptions (Optional[List[str]]) β
penalty_exceptions_include_stop_sequences (Optional[bool]) β
best_of (Optional[int]) β
n (int) β
logit_bias (Optional[Dict[int, float]]) β
log_probs (Optional[int]) β
tokens (Optional[bool]) β
disable_optimizations (Optional[bool]) β
minimum_tokens (Optional[int]) β
echo (bool) β
use_multiplicative_frequency_penalty (bool) β
sequence_penalty (float) β
sequence_penalty_min_length (int) β
use_multiplicative_sequence_penalty (bool) β
completion_bias_inclusion (Optional[Sequence[str]]) β
completion_bias_inclusion_first_token_only (bool) β
completion_bias_exclusion (Optional[Sequence[str]]) β
completion_bias_exclusion_first_token_only (bool) β
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-9
|
completion_bias_exclusion_first_token_only (bool) β
contextual_control_threshold (Optional[float]) β
control_log_additive (Optional[bool]) β
repetition_penalties_include_completion (bool) β
raw_completion (bool) β
aleph_alpha_api_key (Optional[str]) β
stop_sequences (Optional[List[str]]) β
Return type
None
attribute aleph_alpha_api_key: Optional[str] = Noneο
API key for Aleph Alpha API.
attribute best_of: Optional[int] = Noneο
returns the one with the βbest ofβ results
(highest log probability per token)
attribute completion_bias_exclusion_first_token_only: bool = Falseο
Only consider the first token for the completion_bias_exclusion.
attribute contextual_control_threshold: Optional[float] = Noneο
If set to None, attention control parameters only apply to those tokens that have
explicitly been set in the request.
If set to a non-None value, control parameters are also applied to similar tokens.
attribute control_log_additive: Optional[bool] = Trueο
True: apply control by adding the log(control_factor) to attention scores.
False: (attention_scores - - attention_scores.min(-1)) * control_factor
attribute echo: bool = Falseο
Echo the prompt in the completion.
attribute frequency_penalty: float = 0.0ο
Penalizes repeated tokens according to frequency.
attribute log_probs: Optional[int] = Noneο
Number of top log probabilities to be returned for each generated token.
attribute logit_bias: Optional[Dict[int, float]] = Noneο
The logit bias allows to influence the likelihood of generating tokens.
attribute maximum_tokens: int = 64ο
The maximum number of tokens to be generated.
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-10
|
The maximum number of tokens to be generated.
attribute minimum_tokens: Optional[int] = 0ο
Generate at least this number of tokens.
attribute model: Optional[str] = 'luminous-base'ο
Model name to use.
attribute n: int = 1ο
How many completions to generate for each prompt.
attribute penalty_bias: Optional[str] = Noneο
Penalty bias for the completion.
attribute penalty_exceptions: Optional[List[str]] = Noneο
List of strings that may be generated without penalty,
regardless of other penalty settings
attribute penalty_exceptions_include_stop_sequences: Optional[bool] = Noneο
Should stop_sequences be included in penalty_exceptions.
attribute presence_penalty: float = 0.0ο
Penalizes repeated tokens.
attribute raw_completion: bool = Falseο
Force the raw completion of the model to be returned.
attribute repetition_penalties_include_completion: bool = Trueο
Flag deciding whether presence penalty or frequency penalty
are updated from the completion.
attribute repetition_penalties_include_prompt: Optional[bool] = Falseο
Flag deciding whether presence penalty or frequency penalty are
updated from the prompt.
attribute stop_sequences: Optional[List[str]] = Noneο
Stop sequences to use.
attribute tags: Optional[List[str]] = Noneο
Tags to add to the run trace.
attribute temperature: float = 0.0ο
A non-negative float that tunes the degree of randomness in generation.
attribute tokens: Optional[bool] = Falseο
return tokens of completion.
attribute top_k: int = 0ο
Number of most likely tokens to consider at each step.
attribute top_p: float = 0.0ο
Total probability mass of tokens to consider at each step.
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-11
|
Total probability mass of tokens to consider at each step.
attribute use_multiplicative_presence_penalty: Optional[bool] = Falseο
Flag deciding whether presence penalty is applied
multiplicatively (True) or additively (False).
attribute verbose: bool [Optional]ο
Whether to print out response text.
__call__(prompt, stop=None, callbacks=None, **kwargs)ο
Check Cache and run the LLM on the given prompt and input.
Parameters
prompt (str) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
kwargs (Any) β
Return type
str
async agenerate(prompts, stop=None, callbacks=None, *, tags=None, **kwargs)ο
Run the LLM on the given prompt and input.
Parameters
prompts (List[str]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
tags (Optional[List[str]]) β
kwargs (Any) β
Return type
langchain.schema.LLMResult
async agenerate_prompt(prompts, stop=None, callbacks=None, **kwargs)ο
Take in a list of prompt values and return an LLMResult.
Parameters
prompts (List[langchain.schema.PromptValue]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
kwargs (Any) β
Return type
langchain.schema.LLMResult
async apredict(text, *, stop=None, **kwargs)ο
Predict text from text.
Parameters
text (str) β
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-12
|
Predict text from text.
Parameters
text (str) β
stop (Optional[Sequence[str]]) β
kwargs (Any) β
Return type
str
async apredict_messages(messages, *, stop=None, **kwargs)ο
Predict message from messages.
Parameters
messages (List[langchain.schema.BaseMessage]) β
stop (Optional[Sequence[str]]) β
kwargs (Any) β
Return type
langchain.schema.BaseMessage
classmethod construct(_fields_set=None, **values)ο
Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.
Default values are respected, but no other validation is performed.
Behaves as if Config.extra = βallowβ was set since it adds all passed values
Parameters
_fields_set (Optional[SetStr]) β
values (Any) β
Return type
Model
copy(*, include=None, exclude=None, update=None, deep=False)ο
Duplicate a model, optionally choose which fields to include, exclude and change.
Parameters
include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) β fields to include in new model
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(**kwargs)ο
Return a dictionary of the LLM.
Parameters
kwargs (Any) β
Return type
Dict
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-13
|
Parameters
kwargs (Any) β
Return type
Dict
generate(prompts, stop=None, callbacks=None, *, tags=None, **kwargs)ο
Run the LLM on the given prompt and input.
Parameters
prompts (List[str]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
tags (Optional[List[str]]) β
kwargs (Any) β
Return type
langchain.schema.LLMResult
generate_prompt(prompts, stop=None, callbacks=None, **kwargs)ο
Take in a list of prompt values and return an LLMResult.
Parameters
prompts (List[langchain.schema.PromptValue]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
kwargs (Any) β
Return type
langchain.schema.LLMResult
get_num_tokens(text)ο
Get the number of tokens present in the text.
Parameters
text (str) β
Return type
int
get_num_tokens_from_messages(messages)ο
Get the number of tokens in the message.
Parameters
messages (List[langchain.schema.BaseMessage]) β
Return type
int
get_token_ids(text)ο
Get the token present in the text.
Parameters
text (str) β
Return type
List[int]
json(*, include=None, exclude=None, by_alias=False, skip_defaults=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, encoder=None, models_as_dict=True, **dumps_kwargs)ο
Generate a JSON representation of the model, include and exclude arguments as per dict().
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-14
|
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
predict(text, *, stop=None, **kwargs)ο
Predict text from text.
Parameters
text (str) β
stop (Optional[Sequence[str]]) β
kwargs (Any) β
Return type
str
predict_messages(messages, *, stop=None, **kwargs)ο
Predict message from messages.
Parameters
messages (List[langchain.schema.BaseMessage]) β
stop (Optional[Sequence[str]]) β
kwargs (Any) β
Return type
langchain.schema.BaseMessage
save(file_path)ο
Save the LLM.
Parameters
file_path (Union[pathlib.Path, str]) β Path to file to save the LLM to.
Return type
None
Example:
.. code-block:: python
llm.save(file_path=βpath/llm.yamlβ)
classmethod update_forward_refs(**localns)ο
Try to update ForwardRefs on fields based on this Model, globalns and localns.
Parameters
localns (Any) β
Return type
None
property lc_attributes: Dictο
Return a list of attribute names that should be included in the
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-15
|
Return a list of attribute names that should be included in the
serialized kwargs. These attributes must be accepted by the
constructor.
property lc_namespace: List[str]ο
Return the namespace of the langchain object.
eg. [βlangchainβ, βllmsβ, βopenaiβ]
property lc_secrets: Dict[str, str]ο
Return a map of constructor argument names to secret ids.
eg. {βopenai_api_keyβ: βOPENAI_API_KEYβ}
property lc_serializable: boolο
Return whether or not the class is serializable.
class langchain.llms.AmazonAPIGateway(*, cache=None, verbose=None, callbacks=None, callback_manager=None, tags=None, api_url, model_kwargs=None, content_handler=<langchain.llms.amazon_api_gateway.ContentHandlerAmazonAPIGateway object>)[source]ο
Bases: langchain.llms.base.LLM
Wrapper around custom Amazon API Gateway
Parameters
cache (Optional[bool]) β
verbose (bool) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) β
tags (Optional[List[str]]) β
api_url (str) β
model_kwargs (Optional[Dict]) β
content_handler (langchain.llms.amazon_api_gateway.ContentHandlerAmazonAPIGateway) β
Return type
None
attribute api_url: str [Required]ο
API Gateway URL
attribute content_handler: langchain.llms.amazon_api_gateway.ContentHandlerAmazonAPIGateway = <langchain.llms.amazon_api_gateway.ContentHandlerAmazonAPIGateway object>ο
The content handler class that provides an input and
output transform functions to handle formats between LLM
and the endpoint.
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-16
|
output transform functions to handle formats between LLM
and the endpoint.
attribute model_kwargs: Optional[Dict] = Noneο
Key word arguments to pass to the model.
attribute tags: Optional[List[str]] = Noneο
Tags to add to the run trace.
attribute verbose: bool [Optional]ο
Whether to print out response text.
__call__(prompt, stop=None, callbacks=None, **kwargs)ο
Check Cache and run the LLM on the given prompt and input.
Parameters
prompt (str) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
kwargs (Any) β
Return type
str
async agenerate(prompts, stop=None, callbacks=None, *, tags=None, **kwargs)ο
Run the LLM on the given prompt and input.
Parameters
prompts (List[str]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
tags (Optional[List[str]]) β
kwargs (Any) β
Return type
langchain.schema.LLMResult
async agenerate_prompt(prompts, stop=None, callbacks=None, **kwargs)ο
Take in a list of prompt values and return an LLMResult.
Parameters
prompts (List[langchain.schema.PromptValue]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
kwargs (Any) β
Return type
langchain.schema.LLMResult
async apredict(text, *, stop=None, **kwargs)ο
Predict text from text.
Parameters
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-17
|
Predict text from text.
Parameters
text (str) β
stop (Optional[Sequence[str]]) β
kwargs (Any) β
Return type
str
async apredict_messages(messages, *, stop=None, **kwargs)ο
Predict message from messages.
Parameters
messages (List[langchain.schema.BaseMessage]) β
stop (Optional[Sequence[str]]) β
kwargs (Any) β
Return type
langchain.schema.BaseMessage
classmethod construct(_fields_set=None, **values)ο
Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.
Default values are respected, but no other validation is performed.
Behaves as if Config.extra = βallowβ was set since it adds all passed values
Parameters
_fields_set (Optional[SetStr]) β
values (Any) β
Return type
Model
copy(*, include=None, exclude=None, update=None, deep=False)ο
Duplicate a model, optionally choose which fields to include, exclude and change.
Parameters
include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) β fields to include in new model
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(**kwargs)ο
Return a dictionary of the LLM.
Parameters
kwargs (Any) β
Return type
Dict
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-18
|
Parameters
kwargs (Any) β
Return type
Dict
generate(prompts, stop=None, callbacks=None, *, tags=None, **kwargs)ο
Run the LLM on the given prompt and input.
Parameters
prompts (List[str]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
tags (Optional[List[str]]) β
kwargs (Any) β
Return type
langchain.schema.LLMResult
generate_prompt(prompts, stop=None, callbacks=None, **kwargs)ο
Take in a list of prompt values and return an LLMResult.
Parameters
prompts (List[langchain.schema.PromptValue]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
kwargs (Any) β
Return type
langchain.schema.LLMResult
get_num_tokens(text)ο
Get the number of tokens present in the text.
Parameters
text (str) β
Return type
int
get_num_tokens_from_messages(messages)ο
Get the number of tokens in the message.
Parameters
messages (List[langchain.schema.BaseMessage]) β
Return type
int
get_token_ids(text)ο
Get the token present in the text.
Parameters
text (str) β
Return type
List[int]
json(*, include=None, exclude=None, by_alias=False, skip_defaults=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, encoder=None, models_as_dict=True, **dumps_kwargs)ο
Generate a JSON representation of the model, include and exclude arguments as per dict().
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-19
|
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
predict(text, *, stop=None, **kwargs)ο
Predict text from text.
Parameters
text (str) β
stop (Optional[Sequence[str]]) β
kwargs (Any) β
Return type
str
predict_messages(messages, *, stop=None, **kwargs)ο
Predict message from messages.
Parameters
messages (List[langchain.schema.BaseMessage]) β
stop (Optional[Sequence[str]]) β
kwargs (Any) β
Return type
langchain.schema.BaseMessage
save(file_path)ο
Save the LLM.
Parameters
file_path (Union[pathlib.Path, str]) β Path to file to save the LLM to.
Return type
None
Example:
.. code-block:: python
llm.save(file_path=βpath/llm.yamlβ)
classmethod update_forward_refs(**localns)ο
Try to update ForwardRefs on fields based on this Model, globalns and localns.
Parameters
localns (Any) β
Return type
None
property lc_attributes: Dictο
Return a list of attribute names that should be included in the
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-20
|
Return a list of attribute names that should be included in the
serialized kwargs. These attributes must be accepted by the
constructor.
property lc_namespace: List[str]ο
Return the namespace of the langchain object.
eg. [βlangchainβ, βllmsβ, βopenaiβ]
property lc_secrets: Dict[str, str]ο
Return a map of constructor argument names to secret ids.
eg. {βopenai_api_keyβ: βOPENAI_API_KEYβ}
property lc_serializable: boolο
Return whether or not the class is serializable.
class langchain.llms.Anthropic(*, client=None, model='claude-v1', max_tokens_to_sample=256, temperature=None, top_k=None, top_p=None, streaming=False, default_request_timeout=None, anthropic_api_url=None, anthropic_api_key=None, HUMAN_PROMPT=None, AI_PROMPT=None, count_tokens=None, cache=None, verbose=None, callbacks=None, callback_manager=None, tags=None)[source]ο
Bases: langchain.llms.base.LLM, langchain.llms.anthropic._AnthropicCommon
Wrapper around Anthropicβs large language models.
To use, you should have the anthropic python package installed, and the
environment variable ANTHROPIC_API_KEY set with your API key, or pass
it as a named parameter to the constructor.
Example
import anthropic
from langchain.llms import Anthropic
model = Anthropic(model="<model_name>", anthropic_api_key="my-api-key")
# Simplest invocation, automatically wrapped with HUMAN_PROMPT
# and AI_PROMPT.
response = model("What are the biggest risks facing humanity?")
# Or if you want to use the chat mode, build a few-shot-prompt, or
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-21
|
# Or if you want to use the chat mode, build a few-shot-prompt, or
# put words in the Assistant's mouth, use HUMAN_PROMPT and AI_PROMPT:
raw_prompt = "What are the biggest risks facing humanity?"
prompt = f"{anthropic.HUMAN_PROMPT} {prompt}{anthropic.AI_PROMPT}"
response = model(prompt)
Parameters
client (Any) β
model (str) β
max_tokens_to_sample (int) β
temperature (Optional[float]) β
top_k (Optional[int]) β
top_p (Optional[float]) β
streaming (bool) β
default_request_timeout (Optional[Union[float, Tuple[float, float]]]) β
anthropic_api_url (Optional[str]) β
anthropic_api_key (Optional[str]) β
HUMAN_PROMPT (Optional[str]) β
AI_PROMPT (Optional[str]) β
count_tokens (Optional[Callable[[str], int]]) β
cache (Optional[bool]) β
verbose (bool) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) β
tags (Optional[List[str]]) β
Return type
None
attribute default_request_timeout: Optional[Union[float, Tuple[float, float]]] = Noneο
Timeout for requests to Anthropic Completion API. Default is 600 seconds.
attribute max_tokens_to_sample: int = 256ο
Denotes the number of tokens to predict per generation.
attribute model: str = 'claude-v1'ο
Model name to use.
attribute streaming: bool = Falseο
Whether to stream the results.
attribute tags: Optional[List[str]] = Noneο
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-22
|
Whether to stream the results.
attribute tags: Optional[List[str]] = Noneο
Tags to add to the run trace.
attribute temperature: Optional[float] = Noneο
A non-negative float that tunes the degree of randomness in generation.
attribute top_k: Optional[int] = Noneο
Number of most likely tokens to consider at each step.
attribute top_p: Optional[float] = Noneο
Total probability mass of tokens to consider at each step.
attribute verbose: bool [Optional]ο
Whether to print out response text.
__call__(prompt, stop=None, callbacks=None, **kwargs)ο
Check Cache and run the LLM on the given prompt and input.
Parameters
prompt (str) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
kwargs (Any) β
Return type
str
async agenerate(prompts, stop=None, callbacks=None, *, tags=None, **kwargs)ο
Run the LLM on the given prompt and input.
Parameters
prompts (List[str]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
tags (Optional[List[str]]) β
kwargs (Any) β
Return type
langchain.schema.LLMResult
async agenerate_prompt(prompts, stop=None, callbacks=None, **kwargs)ο
Take in a list of prompt values and return an LLMResult.
Parameters
prompts (List[langchain.schema.PromptValue]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-23
|
kwargs (Any) β
Return type
langchain.schema.LLMResult
async apredict(text, *, stop=None, **kwargs)ο
Predict text from text.
Parameters
text (str) β
stop (Optional[Sequence[str]]) β
kwargs (Any) β
Return type
str
async apredict_messages(messages, *, stop=None, **kwargs)ο
Predict message from messages.
Parameters
messages (List[langchain.schema.BaseMessage]) β
stop (Optional[Sequence[str]]) β
kwargs (Any) β
Return type
langchain.schema.BaseMessage
classmethod construct(_fields_set=None, **values)ο
Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.
Default values are respected, but no other validation is performed.
Behaves as if Config.extra = βallowβ was set since it adds all passed values
Parameters
_fields_set (Optional[SetStr]) β
values (Any) β
Return type
Model
copy(*, include=None, exclude=None, update=None, deep=False)ο
Duplicate a model, optionally choose which fields to include, exclude and change.
Parameters
include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) β fields to include in new model
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(**kwargs)ο
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-24
|
Returns
new model instance
Return type
Model
dict(**kwargs)ο
Return a dictionary of the LLM.
Parameters
kwargs (Any) β
Return type
Dict
generate(prompts, stop=None, callbacks=None, *, tags=None, **kwargs)ο
Run the LLM on the given prompt and input.
Parameters
prompts (List[str]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
tags (Optional[List[str]]) β
kwargs (Any) β
Return type
langchain.schema.LLMResult
generate_prompt(prompts, stop=None, callbacks=None, **kwargs)ο
Take in a list of prompt values and return an LLMResult.
Parameters
prompts (List[langchain.schema.PromptValue]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
kwargs (Any) β
Return type
langchain.schema.LLMResult
get_num_tokens(text)[source]ο
Calculate number of tokens.
Parameters
text (str) β
Return type
int
get_num_tokens_from_messages(messages)ο
Get the number of tokens in the message.
Parameters
messages (List[langchain.schema.BaseMessage]) β
Return type
int
get_token_ids(text)ο
Get the token present in the text.
Parameters
text (str) β
Return type
List[int]
json(*, include=None, exclude=None, by_alias=False, skip_defaults=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, encoder=None, models_as_dict=True, **dumps_kwargs)ο
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-25
|
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
predict(text, *, stop=None, **kwargs)ο
Predict text from text.
Parameters
text (str) β
stop (Optional[Sequence[str]]) β
kwargs (Any) β
Return type
str
predict_messages(messages, *, stop=None, **kwargs)ο
Predict message from messages.
Parameters
messages (List[langchain.schema.BaseMessage]) β
stop (Optional[Sequence[str]]) β
kwargs (Any) β
Return type
langchain.schema.BaseMessage
save(file_path)ο
Save the LLM.
Parameters
file_path (Union[pathlib.Path, str]) β Path to file to save the LLM to.
Return type
None
Example:
.. code-block:: python
llm.save(file_path=βpath/llm.yamlβ)
stream(prompt, stop=None)[source]ο
Call Anthropic completion_stream and return the resulting generator.
BETA: this is a beta feature while we figure out the right abstraction.
Once that happens, this interface could change.
Parameters
prompt (str) β The prompt to pass into the model.
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-26
|
Parameters
prompt (str) β The prompt to pass into the model.
stop (Optional[List[str]]) β Optional list of stop words to use when generating.
Returns
A generator representing the stream of tokens from Anthropic.
Return type
Generator
Example
prompt = "Write a poem about a stream."
prompt = f"\n\nHuman: {prompt}\n\nAssistant:"
generator = anthropic.stream(prompt)
for token in generator:
yield token
classmethod update_forward_refs(**localns)ο
Try to update ForwardRefs on fields based on this Model, globalns and localns.
Parameters
localns (Any) β
Return type
None
property lc_attributes: Dictο
Return a list of attribute names that should be included in the
serialized kwargs. These attributes must be accepted by the
constructor.
property lc_namespace: List[str]ο
Return the namespace of the langchain object.
eg. [βlangchainβ, βllmsβ, βopenaiβ]
property lc_secrets: Dict[str, str]ο
Return a map of constructor argument names to secret ids.
eg. {βopenai_api_keyβ: βOPENAI_API_KEYβ}
property lc_serializable: boolο
Return whether or not the class is serializable.
class langchain.llms.Anyscale(*, cache=None, verbose=None, callbacks=None, callback_manager=None, tags=None, model_kwargs=None, anyscale_service_url=None, anyscale_service_route=None, anyscale_service_token=None)[source]ο
Bases: langchain.llms.base.LLM
Wrapper around Anyscale Services.
To use, you should have the environment variable ANYSCALE_SERVICE_URL,
ANYSCALE_SERVICE_ROUTE and ANYSCALE_SERVICE_TOKEN set with your Anyscale
Service, or pass it as a named parameter to the constructor.
Example
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-27
|
Service, or pass it as a named parameter to the constructor.
Example
from langchain.llms import Anyscale
anyscale = Anyscale(anyscale_service_url="SERVICE_URL",
anyscale_service_route="SERVICE_ROUTE",
anyscale_service_token="SERVICE_TOKEN")
# Use Ray for distributed processing
import ray
prompt_list=[]
@ray.remote
def send_query(llm, prompt):
resp = llm(prompt)
return resp
futures = [send_query.remote(anyscale, prompt) for prompt in prompt_list]
results = ray.get(futures)
Parameters
cache (Optional[bool]) β
verbose (bool) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) β
tags (Optional[List[str]]) β
model_kwargs (Optional[dict]) β
anyscale_service_url (Optional[str]) β
anyscale_service_route (Optional[str]) β
anyscale_service_token (Optional[str]) β
Return type
None
attribute model_kwargs: Optional[dict] = Noneο
Key word arguments to pass to the model. Reserved for future use
attribute tags: Optional[List[str]] = Noneο
Tags to add to the run trace.
attribute verbose: bool [Optional]ο
Whether to print out response text.
__call__(prompt, stop=None, callbacks=None, **kwargs)ο
Check Cache and run the LLM on the given prompt and input.
Parameters
prompt (str) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
kwargs (Any) β
Return type
str
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-28
|
kwargs (Any) β
Return type
str
async agenerate(prompts, stop=None, callbacks=None, *, tags=None, **kwargs)ο
Run the LLM on the given prompt and input.
Parameters
prompts (List[str]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
tags (Optional[List[str]]) β
kwargs (Any) β
Return type
langchain.schema.LLMResult
async agenerate_prompt(prompts, stop=None, callbacks=None, **kwargs)ο
Take in a list of prompt values and return an LLMResult.
Parameters
prompts (List[langchain.schema.PromptValue]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
kwargs (Any) β
Return type
langchain.schema.LLMResult
async apredict(text, *, stop=None, **kwargs)ο
Predict text from text.
Parameters
text (str) β
stop (Optional[Sequence[str]]) β
kwargs (Any) β
Return type
str
async apredict_messages(messages, *, stop=None, **kwargs)ο
Predict message from messages.
Parameters
messages (List[langchain.schema.BaseMessage]) β
stop (Optional[Sequence[str]]) β
kwargs (Any) β
Return type
langchain.schema.BaseMessage
classmethod construct(_fields_set=None, **values)ο
Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.
Default values are respected, but no other validation is performed.
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-29
|
Default values are respected, but no other validation is performed.
Behaves as if Config.extra = βallowβ was set since it adds all passed values
Parameters
_fields_set (Optional[SetStr]) β
values (Any) β
Return type
Model
copy(*, include=None, exclude=None, update=None, deep=False)ο
Duplicate a model, optionally choose which fields to include, exclude and change.
Parameters
include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) β fields to include in new model
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(**kwargs)ο
Return a dictionary of the LLM.
Parameters
kwargs (Any) β
Return type
Dict
generate(prompts, stop=None, callbacks=None, *, tags=None, **kwargs)ο
Run the LLM on the given prompt and input.
Parameters
prompts (List[str]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
tags (Optional[List[str]]) β
kwargs (Any) β
Return type
langchain.schema.LLMResult
generate_prompt(prompts, stop=None, callbacks=None, **kwargs)ο
Take in a list of prompt values and return an LLMResult.
Parameters
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-30
|
Take in a list of prompt values and return an LLMResult.
Parameters
prompts (List[langchain.schema.PromptValue]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
kwargs (Any) β
Return type
langchain.schema.LLMResult
get_num_tokens(text)ο
Get the number of tokens present in the text.
Parameters
text (str) β
Return type
int
get_num_tokens_from_messages(messages)ο
Get the number of tokens in the message.
Parameters
messages (List[langchain.schema.BaseMessage]) β
Return type
int
get_token_ids(text)ο
Get the token present in the text.
Parameters
text (str) β
Return type
List[int]
json(*, include=None, exclude=None, by_alias=False, skip_defaults=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, encoder=None, models_as_dict=True, **dumps_kwargs)ο
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
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-31
|
dumps_kwargs (Any) β
Return type
unicode
predict(text, *, stop=None, **kwargs)ο
Predict text from text.
Parameters
text (str) β
stop (Optional[Sequence[str]]) β
kwargs (Any) β
Return type
str
predict_messages(messages, *, stop=None, **kwargs)ο
Predict message from messages.
Parameters
messages (List[langchain.schema.BaseMessage]) β
stop (Optional[Sequence[str]]) β
kwargs (Any) β
Return type
langchain.schema.BaseMessage
save(file_path)ο
Save the LLM.
Parameters
file_path (Union[pathlib.Path, str]) β Path to file to save the LLM to.
Return type
None
Example:
.. code-block:: python
llm.save(file_path=βpath/llm.yamlβ)
classmethod update_forward_refs(**localns)ο
Try to update ForwardRefs on fields based on this Model, globalns and localns.
Parameters
localns (Any) β
Return type
None
property lc_attributes: Dictο
Return a list of attribute names that should be included in the
serialized kwargs. These attributes must be accepted by the
constructor.
property lc_namespace: List[str]ο
Return the namespace of the langchain object.
eg. [βlangchainβ, βllmsβ, βopenaiβ]
property lc_secrets: Dict[str, str]ο
Return a map of constructor argument names to secret ids.
eg. {βopenai_api_keyβ: βOPENAI_API_KEYβ}
property lc_serializable: boolο
Return whether or not the class is serializable.
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-32
|
property lc_serializable: boolο
Return whether or not the class is serializable.
class langchain.llms.Aviary(*, cache=None, verbose=None, callbacks=None, callback_manager=None, tags=None, model='amazon/LightGPT', aviary_url=None, aviary_token=None, use_prompt_format=True, version=None)[source]ο
Bases: langchain.llms.base.LLM
Allow you to use an Aviary.
Aviary is a backend for hosted models. You can
find out more about aviary at
http://github.com/ray-project/aviary
To get a list of the models supported on an
aviary, follow the instructions on the web site to
install the aviary CLI and then use:
aviary models
AVIARY_URL and AVIARY_TOKEN environement variables must be set.
Example
from langchain.llms import Aviary
os.environ["AVIARY_URL"] = "<URL>"
os.environ["AVIARY_TOKEN"] = "<TOKEN>"
light = Aviary(model='amazon/LightGPT')
output = light('How do you make fried rice?')
Parameters
cache (Optional[bool]) β
verbose (bool) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) β
tags (Optional[List[str]]) β
model (str) β
aviary_url (Optional[str]) β
aviary_token (Optional[str]) β
use_prompt_format (bool) β
version (Optional[str]) β
Return type
None
attribute tags: Optional[List[str]] = Noneο
Tags to add to the run trace.
attribute verbose: bool [Optional]ο
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-33
|
Tags to add to the run trace.
attribute verbose: bool [Optional]ο
Whether to print out response text.
__call__(prompt, stop=None, callbacks=None, **kwargs)ο
Check Cache and run the LLM on the given prompt and input.
Parameters
prompt (str) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
kwargs (Any) β
Return type
str
async agenerate(prompts, stop=None, callbacks=None, *, tags=None, **kwargs)ο
Run the LLM on the given prompt and input.
Parameters
prompts (List[str]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
tags (Optional[List[str]]) β
kwargs (Any) β
Return type
langchain.schema.LLMResult
async agenerate_prompt(prompts, stop=None, callbacks=None, **kwargs)ο
Take in a list of prompt values and return an LLMResult.
Parameters
prompts (List[langchain.schema.PromptValue]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
kwargs (Any) β
Return type
langchain.schema.LLMResult
async apredict(text, *, stop=None, **kwargs)ο
Predict text from text.
Parameters
text (str) β
stop (Optional[Sequence[str]]) β
kwargs (Any) β
Return type
str
async apredict_messages(messages, *, stop=None, **kwargs)ο
Predict message from messages.
Parameters
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-34
|
Predict message from messages.
Parameters
messages (List[langchain.schema.BaseMessage]) β
stop (Optional[Sequence[str]]) β
kwargs (Any) β
Return type
langchain.schema.BaseMessage
classmethod construct(_fields_set=None, **values)ο
Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.
Default values are respected, but no other validation is performed.
Behaves as if Config.extra = βallowβ was set since it adds all passed values
Parameters
_fields_set (Optional[SetStr]) β
values (Any) β
Return type
Model
copy(*, include=None, exclude=None, update=None, deep=False)ο
Duplicate a model, optionally choose which fields to include, exclude and change.
Parameters
include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) β fields to include in new model
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(**kwargs)ο
Return a dictionary of the LLM.
Parameters
kwargs (Any) β
Return type
Dict
generate(prompts, stop=None, callbacks=None, *, tags=None, **kwargs)ο
Run the LLM on the given prompt and input.
Parameters
prompts (List[str]) β
stop (Optional[List[str]]) β
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-35
|
Parameters
prompts (List[str]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
tags (Optional[List[str]]) β
kwargs (Any) β
Return type
langchain.schema.LLMResult
generate_prompt(prompts, stop=None, callbacks=None, **kwargs)ο
Take in a list of prompt values and return an LLMResult.
Parameters
prompts (List[langchain.schema.PromptValue]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
kwargs (Any) β
Return type
langchain.schema.LLMResult
get_num_tokens(text)ο
Get the number of tokens present in the text.
Parameters
text (str) β
Return type
int
get_num_tokens_from_messages(messages)ο
Get the number of tokens in the message.
Parameters
messages (List[langchain.schema.BaseMessage]) β
Return type
int
get_token_ids(text)ο
Get the token present in the text.
Parameters
text (str) β
Return type
List[int]
json(*, include=None, exclude=None, by_alias=False, skip_defaults=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, encoder=None, models_as_dict=True, **dumps_kwargs)ο
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]]) β
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-36
|
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
predict(text, *, stop=None, **kwargs)ο
Predict text from text.
Parameters
text (str) β
stop (Optional[Sequence[str]]) β
kwargs (Any) β
Return type
str
predict_messages(messages, *, stop=None, **kwargs)ο
Predict message from messages.
Parameters
messages (List[langchain.schema.BaseMessage]) β
stop (Optional[Sequence[str]]) β
kwargs (Any) β
Return type
langchain.schema.BaseMessage
save(file_path)ο
Save the LLM.
Parameters
file_path (Union[pathlib.Path, str]) β Path to file to save the LLM to.
Return type
None
Example:
.. code-block:: python
llm.save(file_path=βpath/llm.yamlβ)
classmethod update_forward_refs(**localns)ο
Try to update ForwardRefs on fields based on this Model, globalns and localns.
Parameters
localns (Any) β
Return type
None
property lc_attributes: Dictο
Return a list of attribute names that should be included in the
serialized kwargs. These attributes must be accepted by the
constructor.
property lc_namespace: List[str]ο
Return the namespace of the langchain object.
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-37
|
property lc_namespace: List[str]ο
Return the namespace of the langchain object.
eg. [βlangchainβ, βllmsβ, βopenaiβ]
property lc_secrets: Dict[str, str]ο
Return a map of constructor argument names to secret ids.
eg. {βopenai_api_keyβ: βOPENAI_API_KEYβ}
property lc_serializable: boolο
Return whether or not the class is serializable.
class langchain.llms.AzureMLOnlineEndpoint(*, cache=None, verbose=None, callbacks=None, callback_manager=None, tags=None, endpoint_url='', endpoint_api_key='', deployment_name='', http_client=None, content_formatter=None, model_kwargs=None)[source]ο
Bases: langchain.llms.base.LLM, pydantic.main.BaseModel
Wrapper around Azure ML Hosted models using Managed Online Endpoints.
Example
azure_llm = AzureMLModel(
endpoint_url="https://<your-endpoint>.<your_region>.inference.ml.azure.com/score",
endpoint_api_key="my-api-key",
deployment_name="my-deployment-name",
content_formatter=content_formatter,
)
Parameters
cache (Optional[bool]) β
verbose (bool) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) β
tags (Optional[List[str]]) β
endpoint_url (str) β
endpoint_api_key (str) β
deployment_name (str) β
http_client (Any) β
content_formatter (Any) β
model_kwargs (Optional[dict]) β
Return type
None
attribute content_formatter: Any = Noneο
The content formatter that provides an input and output
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-38
|
attribute content_formatter: Any = Noneο
The content formatter that provides an input and output
transform function to handle formats between the LLM and
the endpoint
attribute deployment_name: str = ''ο
Deployment Name for Endpoint. Should be passed to constructor or specified as
env var AZUREML_DEPLOYMENT_NAME.
attribute endpoint_api_key: str = ''ο
Authentication Key for Endpoint. Should be passed to constructor or specified as
env var AZUREML_ENDPOINT_API_KEY.
attribute endpoint_url: str = ''ο
URL of pre-existing Endpoint. Should be passed to constructor or specified as
env var AZUREML_ENDPOINT_URL.
attribute model_kwargs: Optional[dict] = Noneο
Key word arguments to pass to the model.
attribute tags: Optional[List[str]] = Noneο
Tags to add to the run trace.
attribute verbose: bool [Optional]ο
Whether to print out response text.
__call__(prompt, stop=None, callbacks=None, **kwargs)ο
Check Cache and run the LLM on the given prompt and input.
Parameters
prompt (str) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
kwargs (Any) β
Return type
str
async agenerate(prompts, stop=None, callbacks=None, *, tags=None, **kwargs)ο
Run the LLM on the given prompt and input.
Parameters
prompts (List[str]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
tags (Optional[List[str]]) β
kwargs (Any) β
Return type
langchain.schema.LLMResult
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-39
|
kwargs (Any) β
Return type
langchain.schema.LLMResult
async agenerate_prompt(prompts, stop=None, callbacks=None, **kwargs)ο
Take in a list of prompt values and return an LLMResult.
Parameters
prompts (List[langchain.schema.PromptValue]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
kwargs (Any) β
Return type
langchain.schema.LLMResult
async apredict(text, *, stop=None, **kwargs)ο
Predict text from text.
Parameters
text (str) β
stop (Optional[Sequence[str]]) β
kwargs (Any) β
Return type
str
async apredict_messages(messages, *, stop=None, **kwargs)ο
Predict message from messages.
Parameters
messages (List[langchain.schema.BaseMessage]) β
stop (Optional[Sequence[str]]) β
kwargs (Any) β
Return type
langchain.schema.BaseMessage
classmethod construct(_fields_set=None, **values)ο
Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.
Default values are respected, but no other validation is performed.
Behaves as if Config.extra = βallowβ was set since it adds all passed values
Parameters
_fields_set (Optional[SetStr]) β
values (Any) β
Return type
Model
copy(*, include=None, exclude=None, update=None, deep=False)ο
Duplicate a model, optionally choose which fields to include, exclude and change.
Parameters
include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) β fields to include in new model
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-40
|
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(**kwargs)ο
Return a dictionary of the LLM.
Parameters
kwargs (Any) β
Return type
Dict
generate(prompts, stop=None, callbacks=None, *, tags=None, **kwargs)ο
Run the LLM on the given prompt and input.
Parameters
prompts (List[str]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
tags (Optional[List[str]]) β
kwargs (Any) β
Return type
langchain.schema.LLMResult
generate_prompt(prompts, stop=None, callbacks=None, **kwargs)ο
Take in a list of prompt values and return an LLMResult.
Parameters
prompts (List[langchain.schema.PromptValue]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
kwargs (Any) β
Return type
langchain.schema.LLMResult
get_num_tokens(text)ο
Get the number of tokens present in the text.
Parameters
text (str) β
Return type
int
get_num_tokens_from_messages(messages)ο
Get the number of tokens in the message.
Parameters
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-41
|
Get the number of tokens in the message.
Parameters
messages (List[langchain.schema.BaseMessage]) β
Return type
int
get_token_ids(text)ο
Get the token present in the text.
Parameters
text (str) β
Return type
List[int]
json(*, include=None, exclude=None, by_alias=False, skip_defaults=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, encoder=None, models_as_dict=True, **dumps_kwargs)ο
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
predict(text, *, stop=None, **kwargs)ο
Predict text from text.
Parameters
text (str) β
stop (Optional[Sequence[str]]) β
kwargs (Any) β
Return type
str
predict_messages(messages, *, stop=None, **kwargs)ο
Predict message from messages.
Parameters
messages (List[langchain.schema.BaseMessage]) β
stop (Optional[Sequence[str]]) β
kwargs (Any) β
Return type
langchain.schema.BaseMessage
save(file_path)ο
Save the LLM.
Parameters
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-42
|
save(file_path)ο
Save the LLM.
Parameters
file_path (Union[pathlib.Path, str]) β Path to file to save the LLM to.
Return type
None
Example:
.. code-block:: python
llm.save(file_path=βpath/llm.yamlβ)
classmethod update_forward_refs(**localns)ο
Try to update ForwardRefs on fields based on this Model, globalns and localns.
Parameters
localns (Any) β
Return type
None
property lc_attributes: Dictο
Return a list of attribute names that should be included in the
serialized kwargs. These attributes must be accepted by the
constructor.
property lc_namespace: List[str]ο
Return the namespace of the langchain object.
eg. [βlangchainβ, βllmsβ, βopenaiβ]
property lc_secrets: Dict[str, str]ο
Return a map of constructor argument names to secret ids.
eg. {βopenai_api_keyβ: βOPENAI_API_KEYβ}
property lc_serializable: boolο
Return whether or not the class is serializable.
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-43
|
property lc_serializable: boolο
Return whether or not the class is serializable.
class langchain.llms.AzureOpenAI(*, cache=None, verbose=None, callbacks=None, callback_manager=None, tags=None, client=None, model='text-davinci-003', temperature=0.7, max_tokens=256, top_p=1, frequency_penalty=0, presence_penalty=0, n=1, best_of=1, model_kwargs=None, openai_api_key=None, openai_api_base=None, openai_organization=None, openai_proxy=None, batch_size=20, request_timeout=None, logit_bias=None, max_retries=6, streaming=False, allowed_special={}, disallowed_special='all', tiktoken_model_name=None, deployment_name='', openai_api_type='azure', openai_api_version='')[source]ο
Bases: langchain.llms.openai.BaseOpenAI
Wrapper around Azure-specific OpenAI large language models.
To use, you should have the openai python package installed, and the
environment variable OPENAI_API_KEY set with your API key.
Any parameters that are valid to be passed to the openai.create call can be passed
in, even if not explicitly saved on this class.
Example
from langchain.llms import AzureOpenAI
openai = AzureOpenAI(model_name="text-davinci-003")
Parameters
cache (Optional[bool]) β
verbose (bool) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) β
tags (Optional[List[str]]) β
client (Any) β
model (str) β
temperature (float) β
max_tokens (int) β
top_p (float) β
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-44
|
max_tokens (int) β
top_p (float) β
frequency_penalty (float) β
presence_penalty (float) β
n (int) β
best_of (int) β
model_kwargs (Dict[str, Any]) β
openai_api_key (Optional[str]) β
openai_api_base (Optional[str]) β
openai_organization (Optional[str]) β
openai_proxy (Optional[str]) β
batch_size (int) β
request_timeout (Optional[Union[float, Tuple[float, float]]]) β
logit_bias (Optional[Dict[str, float]]) β
max_retries (int) β
streaming (bool) β
allowed_special (Union[Literal['all'], typing.AbstractSet[str]]) β
disallowed_special (Union[Literal['all'], typing.Collection[str]]) β
tiktoken_model_name (Optional[str]) β
deployment_name (str) β
openai_api_type (str) β
openai_api_version (str) β
Return type
None
attribute allowed_special: Union[Literal['all'], AbstractSet[str]] = {}ο
Set of special tokens that are allowedγ
attribute batch_size: int = 20ο
Batch size to use when passing multiple documents to generate.
attribute best_of: int = 1ο
Generates best_of completions server-side and returns the βbestβ.
attribute deployment_name: str = ''ο
Deployment name to use.
attribute disallowed_special: Union[Literal['all'], Collection[str]] = 'all'ο
Set of special tokens that are not allowedγ
attribute frequency_penalty: float = 0ο
Penalizes repeated tokens according to frequency.
attribute logit_bias: Optional[Dict[str, float]] [Optional]ο
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-45
|
attribute logit_bias: Optional[Dict[str, float]] [Optional]ο
Adjust the probability of specific tokens being generated.
attribute max_retries: int = 6ο
Maximum number of retries to make when generating.
attribute max_tokens: int = 256ο
The maximum number of tokens to generate in the completion.
-1 returns as many tokens as possible given the prompt and
the models maximal context size.
attribute model_kwargs: Dict[str, Any] [Optional]ο
Holds any model parameters valid for create call not explicitly specified.
attribute model_name: str = 'text-davinci-003' (alias 'model')ο
Model name to use.
attribute n: int = 1ο
How many completions to generate for each prompt.
attribute presence_penalty: float = 0ο
Penalizes repeated tokens.
attribute request_timeout: Optional[Union[float, Tuple[float, float]]] = Noneο
Timeout for requests to OpenAI completion API. Default is 600 seconds.
attribute streaming: bool = Falseο
Whether to stream the results or not.
attribute tags: Optional[List[str]] = Noneο
Tags to add to the run trace.
attribute temperature: float = 0.7ο
What sampling temperature to use.
attribute tiktoken_model_name: Optional[str] = Noneο
The model name to pass to tiktoken when using this class.
Tiktoken is used to count the number of tokens in documents to constrain
them to be under a certain limit. By default, when set to None, this will
be the same as the embedding model name. However, there are some cases
where you may want to use this Embedding class with a model name not
supported by tiktoken. This can include when using Azure embeddings or
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-46
|
supported by tiktoken. This can include when using Azure embeddings or
when using one of the many model providers that expose an OpenAI-like
API but with different models. In those cases, in order to avoid erroring
when tiktoken is called, you can specify a model name to use here.
attribute top_p: float = 1ο
Total probability mass of tokens to consider at each step.
attribute verbose: bool [Optional]ο
Whether to print out response text.
__call__(prompt, stop=None, callbacks=None, **kwargs)ο
Check Cache and run the LLM on the given prompt and input.
Parameters
prompt (str) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
kwargs (Any) β
Return type
str
async agenerate(prompts, stop=None, callbacks=None, *, tags=None, **kwargs)ο
Run the LLM on the given prompt and input.
Parameters
prompts (List[str]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
tags (Optional[List[str]]) β
kwargs (Any) β
Return type
langchain.schema.LLMResult
async agenerate_prompt(prompts, stop=None, callbacks=None, **kwargs)ο
Take in a list of prompt values and return an LLMResult.
Parameters
prompts (List[langchain.schema.PromptValue]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
kwargs (Any) β
Return type
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-47
|
kwargs (Any) β
Return type
langchain.schema.LLMResult
async apredict(text, *, stop=None, **kwargs)ο
Predict text from text.
Parameters
text (str) β
stop (Optional[Sequence[str]]) β
kwargs (Any) β
Return type
str
async apredict_messages(messages, *, stop=None, **kwargs)ο
Predict message from messages.
Parameters
messages (List[langchain.schema.BaseMessage]) β
stop (Optional[Sequence[str]]) β
kwargs (Any) β
Return type
langchain.schema.BaseMessage
classmethod construct(_fields_set=None, **values)ο
Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.
Default values are respected, but no other validation is performed.
Behaves as if Config.extra = βallowβ was set since it adds all passed values
Parameters
_fields_set (Optional[SetStr]) β
values (Any) β
Return type
Model
copy(*, include=None, exclude=None, update=None, deep=False)ο
Duplicate a model, optionally choose which fields to include, exclude and change.
Parameters
include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) β fields to include in new model
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
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-48
|
self (Model) β
Returns
new model instance
Return type
Model
create_llm_result(choices, prompts, token_usage)ο
Create the LLMResult from the choices and prompts.
Parameters
choices (Any) β
prompts (List[str]) β
token_usage (Dict[str, int]) β
Return type
langchain.schema.LLMResult
dict(**kwargs)ο
Return a dictionary of the LLM.
Parameters
kwargs (Any) β
Return type
Dict
generate(prompts, stop=None, callbacks=None, *, tags=None, **kwargs)ο
Run the LLM on the given prompt and input.
Parameters
prompts (List[str]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
tags (Optional[List[str]]) β
kwargs (Any) β
Return type
langchain.schema.LLMResult
generate_prompt(prompts, stop=None, callbacks=None, **kwargs)ο
Take in a list of prompt values and return an LLMResult.
Parameters
prompts (List[langchain.schema.PromptValue]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
kwargs (Any) β
Return type
langchain.schema.LLMResult
get_num_tokens(text)ο
Get the number of tokens present in the text.
Parameters
text (str) β
Return type
int
get_num_tokens_from_messages(messages)ο
Get the number of tokens in the message.
Parameters
messages (List[langchain.schema.BaseMessage]) β
Return type
int
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-49
|
Parameters
messages (List[langchain.schema.BaseMessage]) β
Return type
int
get_sub_prompts(params, prompts, stop=None)ο
Get the sub prompts for llm call.
Parameters
params (Dict[str, Any]) β
prompts (List[str]) β
stop (Optional[List[str]]) β
Return type
List[List[str]]
get_token_ids(text)ο
Get the token IDs using the tiktoken package.
Parameters
text (str) β
Return type
List[int]
json(*, include=None, exclude=None, by_alias=False, skip_defaults=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, encoder=None, models_as_dict=True, **dumps_kwargs)ο
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
max_tokens_for_prompt(prompt)ο
Calculate the maximum number of tokens possible to generate for a prompt.
Parameters
prompt (str) β The prompt to pass into the model.
Returns
The maximum number of tokens to generate for a prompt.
Return type
int
Example
max_tokens = openai.max_token_for_prompt("Tell me a joke.")
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-50
|
int
Example
max_tokens = openai.max_token_for_prompt("Tell me a joke.")
static modelname_to_contextsize(modelname)ο
Calculate the maximum number of tokens possible to generate for a model.
Parameters
modelname (str) β The modelname we want to know the context size for.
Returns
The maximum context size
Return type
int
Example
max_tokens = openai.modelname_to_contextsize("text-davinci-003")
predict(text, *, stop=None, **kwargs)ο
Predict text from text.
Parameters
text (str) β
stop (Optional[Sequence[str]]) β
kwargs (Any) β
Return type
str
predict_messages(messages, *, stop=None, **kwargs)ο
Predict message from messages.
Parameters
messages (List[langchain.schema.BaseMessage]) β
stop (Optional[Sequence[str]]) β
kwargs (Any) β
Return type
langchain.schema.BaseMessage
prep_streaming_params(stop=None)ο
Prepare the params for streaming.
Parameters
stop (Optional[List[str]]) β
Return type
Dict[str, Any]
save(file_path)ο
Save the LLM.
Parameters
file_path (Union[pathlib.Path, str]) β Path to file to save the LLM to.
Return type
None
Example:
.. code-block:: python
llm.save(file_path=βpath/llm.yamlβ)
stream(prompt, stop=None)ο
Call OpenAI with streaming flag and return the resulting generator.
BETA: this is a beta feature while we figure out the right abstraction.
Once that happens, this interface could change.
Parameters
prompt (str) β The prompts to pass into the model.
stop (Optional[List[str]]) β Optional list of stop words to use when generating.
Returns
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-51
|
stop (Optional[List[str]]) β Optional list of stop words to use when generating.
Returns
A generator representing the stream of tokens from OpenAI.
Return type
Generator
Example
generator = openai.stream("Tell me a joke.")
for token in generator:
yield token
classmethod update_forward_refs(**localns)ο
Try to update ForwardRefs on fields based on this Model, globalns and localns.
Parameters
localns (Any) β
Return type
None
property lc_attributes: Dictο
Return a list of attribute names that should be included in the
serialized kwargs. These attributes must be accepted by the
constructor.
property lc_namespace: List[str]ο
Return the namespace of the langchain object.
eg. [βlangchainβ, βllmsβ, βopenaiβ]
property lc_secrets: Dict[str, str]ο
Return a map of constructor argument names to secret ids.
eg. {βopenai_api_keyβ: βOPENAI_API_KEYβ}
property lc_serializable: boolο
Return whether or not the class is serializable.
property max_context_size: intο
Get max context size for this model.
class langchain.llms.Banana(*, cache=None, verbose=None, callbacks=None, callback_manager=None, tags=None, model_key='', model_kwargs=None, banana_api_key=None)[source]ο
Bases: langchain.llms.base.LLM
Wrapper around Banana large language models.
To use, you should have the banana-dev python package installed,
and the environment variable BANANA_API_KEY set with your API key.
Any parameters that are valid to be passed to the call can be passed
in, even if not explicitly saved on this class.
Example
from langchain.llms import Banana
banana = Banana(model_key="")
Parameters
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-52
|
Example
from langchain.llms import Banana
banana = Banana(model_key="")
Parameters
cache (Optional[bool]) β
verbose (bool) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) β
tags (Optional[List[str]]) β
model_key (str) β
model_kwargs (Dict[str, Any]) β
banana_api_key (Optional[str]) β
Return type
None
attribute model_key: str = ''ο
model endpoint to use
attribute model_kwargs: Dict[str, Any] [Optional]ο
Holds any model parameters valid for create call not
explicitly specified.
attribute tags: Optional[List[str]] = Noneο
Tags to add to the run trace.
attribute verbose: bool [Optional]ο
Whether to print out response text.
__call__(prompt, stop=None, callbacks=None, **kwargs)ο
Check Cache and run the LLM on the given prompt and input.
Parameters
prompt (str) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
kwargs (Any) β
Return type
str
async agenerate(prompts, stop=None, callbacks=None, *, tags=None, **kwargs)ο
Run the LLM on the given prompt and input.
Parameters
prompts (List[str]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
tags (Optional[List[str]]) β
kwargs (Any) β
Return type
langchain.schema.LLMResult
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-53
|
kwargs (Any) β
Return type
langchain.schema.LLMResult
async agenerate_prompt(prompts, stop=None, callbacks=None, **kwargs)ο
Take in a list of prompt values and return an LLMResult.
Parameters
prompts (List[langchain.schema.PromptValue]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
kwargs (Any) β
Return type
langchain.schema.LLMResult
async apredict(text, *, stop=None, **kwargs)ο
Predict text from text.
Parameters
text (str) β
stop (Optional[Sequence[str]]) β
kwargs (Any) β
Return type
str
async apredict_messages(messages, *, stop=None, **kwargs)ο
Predict message from messages.
Parameters
messages (List[langchain.schema.BaseMessage]) β
stop (Optional[Sequence[str]]) β
kwargs (Any) β
Return type
langchain.schema.BaseMessage
classmethod construct(_fields_set=None, **values)ο
Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.
Default values are respected, but no other validation is performed.
Behaves as if Config.extra = βallowβ was set since it adds all passed values
Parameters
_fields_set (Optional[SetStr]) β
values (Any) β
Return type
Model
copy(*, include=None, exclude=None, update=None, deep=False)ο
Duplicate a model, optionally choose which fields to include, exclude and change.
Parameters
include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) β fields to include in new model
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
ff6d0b7b0742-54
|
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(**kwargs)ο
Return a dictionary of the LLM.
Parameters
kwargs (Any) β
Return type
Dict
generate(prompts, stop=None, callbacks=None, *, tags=None, **kwargs)ο
Run the LLM on the given prompt and input.
Parameters
prompts (List[str]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
tags (Optional[List[str]]) β
kwargs (Any) β
Return type
langchain.schema.LLMResult
generate_prompt(prompts, stop=None, callbacks=None, **kwargs)ο
Take in a list of prompt values and return an LLMResult.
Parameters
prompts (List[langchain.schema.PromptValue]) β
stop (Optional[List[str]]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
kwargs (Any) β
Return type
langchain.schema.LLMResult
get_num_tokens(text)ο
Get the number of tokens present in the text.
Parameters
text (str) β
Return type
int
get_num_tokens_from_messages(messages)ο
Get the number of tokens in the message.
Parameters
|
https://api.python.langchain.com/en/latest/modules/llms.html
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.