langchain.retrievers.pinecone_hybrid_search.PineconeHybridSearchRetriever¶
class langchain.retrievers.pinecone_hybrid_search.PineconeHybridSearchRetriever(*, embeddings: Embeddings, sparse_encoder: Any = None, index: Any = None, top_k: int = 4, alpha: float = 0.5)[source]¶
Bases: BaseRetriever, BaseModel
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param alpha: float = 0.5¶
param embeddings: langchain.embeddings.base.Embeddings [Required]¶
description
param index: Any = None¶
param sparse_encoder: Any = None¶
param top_k: int = 4¶
add_texts(texts: List[str], ids: Optional[List[str]] = None, metadatas: Optional[List[dict]] = None) → None[source]¶
async aget_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Asynchronously get documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
get_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Retrieve documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
validator validate_environment  »  all fields[source]¶
Validate that api key and python package exists in environment.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
arbitrary_types_allowed = True¶


Configuration for this pydantic object.
arbitrary_types_allowed = True¶
extra = 'forbid'¶


langchain.retrievers.kendra.QueryResult¶
class langchain.retrievers.kendra.QueryResult(*, ResultItems: List[QueryResultItem], **extra_data: Any)[source]¶
Bases: BaseModel
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param ResultItems: List[langchain.retrievers.kendra.QueryResultItem] [Required]¶
get_top_k_docs(top_n: int) → List[Document][source]¶


langchain.retrievers.milvus.MilvusRetriever¶
class langchain.retrievers.milvus.MilvusRetriever(embedding_function: Embeddings, collection_name: str = 'LangChainCollection', connection_args: Optional[Dict[str, Any]] = None, consistency_level: str = 'Session', search_params: Optional[dict] = None)[source]¶
Bases: BaseRetriever
Retriever that uses the Milvus API.
Methods
__init__(embedding_function[, ...])
add_texts(texts[, metadatas])
Add text to the Milvus store
aget_relevant_documents(query, *[, callbacks])
Asynchronously get documents relevant to a query.
get_relevant_documents(query, *[, callbacks])
Retrieve documents relevant to a query.
add_texts(texts: List[str], metadatas: Optional[List[dict]] = None) → None[source]¶
Add text to the Milvus store
Parameters
texts (List[str]) – The text
metadatas (List[dict]) – Metadata dicts, must line up with existing store
async aget_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Asynchronously get documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
get_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Retrieve documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents


langchain.retrievers.merger_retriever.MergerRetriever¶
class langchain.retrievers.merger_retriever.MergerRetriever(retrievers: List[BaseRetriever])[source]¶
Bases: BaseRetriever
This class merges the results of multiple retrievers.
Parameters
retrievers – A list of retrievers to merge.
Initialize the MergerRetriever class.
Parameters
retrievers – A list of retrievers to merge.
Methods
__init__(retrievers)
Initialize the MergerRetriever class.
aget_relevant_documents(query, *[, callbacks])
Asynchronously get documents relevant to a query.
amerge_documents(query, run_manager)
Asynchronously merge the results of the retrievers.
get_relevant_documents(query, *[, callbacks])
Retrieve documents relevant to a query.
merge_documents(query, run_manager)
Merge the results of the retrievers.
async aget_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Asynchronously get documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
async amerge_documents(query: str, run_manager: AsyncCallbackManagerForRetrieverRun) → List[Document][source]¶
Asynchronously merge the results of the retrievers.
Parameters
query – The query to search for.
Returns
A list of merged documents.
get_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Retrieve documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns


:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
merge_documents(query: str, run_manager: CallbackManagerForRetrieverRun) → List[Document][source]¶
Merge the results of the retrievers.
Parameters
query – The query to search for.
Returns
A list of merged documents.


langchain.retrievers.kendra.Highlight¶
class langchain.retrievers.kendra.Highlight(*, BeginOffset: int, EndOffset: int, TopAnswer: Optional[bool] = None, Type: Optional[str] = None, **extra_data: Any)[source]¶
Bases: BaseModel
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param BeginOffset: int [Required]¶
param EndOffset: int [Required]¶
param TopAnswer: Optional[bool] = None¶
param Type: Optional[str] = None¶


langchain.retrievers.self_query.chroma.ChromaTranslator¶
class langchain.retrievers.self_query.chroma.ChromaTranslator[source]¶
Bases: Visitor
Logic for converting internal query language elements to valid filters.
Methods
__init__()
visit_comparison(comparison)
Translate a Comparison.
visit_operation(operation)
Translate an Operation.
visit_structured_query(structured_query)
Translate a StructuredQuery.
Attributes
allowed_comparators
allowed_operators
Subset of allowed logical operators.
visit_comparison(comparison: Comparison) → Dict[source]¶
Translate a Comparison.
visit_operation(operation: Operation) → Dict[source]¶
Translate an Operation.
visit_structured_query(structured_query: StructuredQuery) → Tuple[str, dict][source]¶
Translate a StructuredQuery.
allowed_comparators: Optional[Sequence[Comparator]] = None¶
allowed_operators: Optional[Sequence[Operator]] = [<Operator.AND: 'and'>, <Operator.OR: 'or'>]¶
Subset of allowed logical operators.


langchain.retrievers.self_query.myscale.DEFAULT_COMPOSER¶
langchain.retrievers.self_query.myscale.DEFAULT_COMPOSER(op_name: str) → Callable[source]¶
Default composer for logical operators.
Parameters
op_name – Name of the operator.
Returns
Callable that takes a list of arguments and returns a string.


langchain.retrievers.weaviate_hybrid_search.WeaviateHybridSearchRetriever¶
class langchain.retrievers.weaviate_hybrid_search.WeaviateHybridSearchRetriever(client: Any, index_name: str, text_key: str, alpha: float = 0.5, k: int = 4, attributes: Optional[List[str]] = None, create_schema_if_missing: bool = True)[source]¶
Bases: BaseRetriever
Methods
__init__(client, index_name, text_key[, ...])
add_documents(docs, **kwargs)
Upload documents to Weaviate.
aget_relevant_documents(query, *[, callbacks])
Asynchronously get documents relevant to a query.
get_relevant_documents(query, *[, callbacks])
Retrieve documents relevant to a query.
class Config[source]¶
Bases: object
Configuration for this pydantic object.
arbitrary_types_allowed = True¶
extra = 'forbid'¶
add_documents(docs: List[Document], **kwargs: Any) → List[str][source]¶
Upload documents to Weaviate.
async aget_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Asynchronously get documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
get_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Retrieve documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents


langchain.retrievers.arxiv.ArxivRetriever¶
class langchain.retrievers.arxiv.ArxivRetriever(*, arxiv_search: Any = None, arxiv_exceptions: Any = None, top_k_results: int = 3, load_max_docs: int = 100, load_all_available_meta: bool = False, doc_content_chars_max: Optional[int] = 4000, ARXIV_MAX_QUERY_LENGTH: int = 300)[source]¶
Bases: BaseRetriever, ArxivAPIWrapper
It is effectively a wrapper for ArxivAPIWrapper.
It wraps load() to get_relevant_documents().
It uses all ArxivAPIWrapper arguments without any change.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param arxiv_exceptions: Any = None¶
param doc_content_chars_max: Optional[int] = 4000¶
param load_all_available_meta: bool = False¶
param load_max_docs: int = 100¶
param top_k_results: int = 3¶
async aget_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Asynchronously get documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
get_relevant_documents(query: str, *, callbacks: Callbacks = None, **kwargs: Any) → List[Document]¶
Retrieve documents relevant to a query.
:param query: string to find relevant documents for
:param callbacks: Callback manager or list of callbacks
Returns
List of relevant documents
load(query: str) → List[Document]¶
Run Arxiv search and get the article texts plus the article meta information.


Run Arxiv search and get the article texts plus the article meta information.
See https://lukasschwab.me/arxiv.py/index.html#Search
Returns: a list of documents with the document.page_content in text format
run(query: str) → str¶
Run Arxiv search and get the article meta information.
See https://lukasschwab.me/arxiv.py/index.html#Search
See https://lukasschwab.me/arxiv.py/index.html#Result
It uses only the most informative fields of article meta information.
validator validate_environment  »  all fields¶
Validate that the python package exists in environment.
model Config¶
Bases: object
Configuration for this pydantic object.
extra = 'forbid'¶


langchain.utilities.openapi.HTTPVerb¶
class langchain.utilities.openapi.HTTPVerb(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]¶
Bases: str, Enum
HTTP verbs.
Methods
from_str(verb)
Parse an HTTP verb.
__init__(*args, **kwds)
capitalize()
Return a capitalized version of the string.
casefold()
Return a version of the string suitable for caseless comparisons.
center(width[, fillchar])
Return a centered string of length width.
count(sub[, start[, end]])
Return the number of non-overlapping occurrences of substring sub in string S[start:end].
encode([encoding, errors])
Encode the string using the codec registered for encoding.
endswith(suffix[, start[, end]])
Return True if S ends with the specified suffix, False otherwise.
expandtabs([tabsize])
Return a copy where all tab characters are expanded using spaces.
find(sub[, start[, end]])
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].
format(*args, **kwargs)
Return a formatted version of S, using substitutions from args and kwargs.
format_map(mapping)
Return a formatted version of S, using substitutions from mapping.
index(sub[, start[, end]])
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].
isalnum()
Return True if the string is an alpha-numeric string, False otherwise.
isalpha()
Return True if the string is an alphabetic string, False otherwise.
isascii()
Return True if all characters in the string are ASCII, False otherwise.
isdecimal()
Return True if the string is a decimal string, False otherwise.


isdecimal()
Return True if the string is a decimal string, False otherwise.
isdigit()
Return True if the string is a digit string, False otherwise.
isidentifier()
Return True if the string is a valid Python identifier, False otherwise.
islower()
Return True if the string is a lowercase string, False otherwise.
isnumeric()
Return True if the string is a numeric string, False otherwise.
isprintable()
Return True if the string is printable, False otherwise.
isspace()
Return True if the string is a whitespace string, False otherwise.
istitle()
Return True if the string is a title-cased string, False otherwise.
isupper()
Return True if the string is an uppercase string, False otherwise.
join(iterable, /)
Concatenate any number of strings.
ljust(width[, fillchar])
Return a left-justified string of length width.
lower()
Return a copy of the string converted to lowercase.
lstrip([chars])
Return a copy of the string with leading whitespace removed.
maketrans
Return a translation table usable for str.translate().
partition(sep, /)
Partition the string into three parts using the given separator.
removeprefix(prefix, /)
Return a str with the given prefix string removed if present.
removesuffix(suffix, /)
Return a str with the given suffix string removed if present.
replace(old, new[, count])
Return a copy with all occurrences of substring old replaced by new.
rfind(sub[, start[, end]])
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end].
rindex(sub[, start[, end]])
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end].


rjust(width[, fillchar])
Return a right-justified string of length width.
rpartition(sep, /)
Partition the string into three parts using the given separator.
rsplit([sep, maxsplit])
Return a list of the substrings in the string, using sep as the separator string.
rstrip([chars])
Return a copy of the string with trailing whitespace removed.
split([sep, maxsplit])
Return a list of the substrings in the string, using sep as the separator string.
splitlines([keepends])
Return a list of the lines in the string, breaking at line boundaries.
startswith(prefix[, start[, end]])
Return True if S starts with the specified prefix, False otherwise.
strip([chars])
Return a copy of the string with leading and trailing whitespace removed.
swapcase()
Convert uppercase characters to lowercase and lowercase characters to uppercase.
title()
Return a version of the string where each word is titlecased.
translate(table, /)
Replace each character in the string using the given translation table.
upper()
Return a copy of the string converted to uppercase.
zfill(width, /)
Pad a numeric string with zeros on the left, to fill a field of the given width.
Attributes
GET
PUT
POST
DELETE
OPTIONS
HEAD
PATCH
TRACE
capitalize()¶
Return a capitalized version of the string.
More specifically, make the first character have upper case and the rest lower
case.
casefold()¶
Return a version of the string suitable for caseless comparisons.
center(width, fillchar=' ', /)¶
Return a centered string of length width.
Padding is done using the specified fill character (default is a space).
count(sub[, start[, end]]) → int¶
Return the number of non-overlapping occurrences of substring sub in


Return the number of non-overlapping occurrences of substring sub in
string S[start:end].  Optional arguments start and end are
interpreted as in slice notation.
encode(encoding='utf-8', errors='strict')¶
Encode the string using the codec registered for encoding.
encodingThe encoding in which to encode the string.
errorsThe error handling scheme to use for encoding errors.
The default is ‘strict’ meaning that encoding errors raise a
UnicodeEncodeError.  Other possible values are ‘ignore’, ‘replace’ and
‘xmlcharrefreplace’ as well as any other name registered with
codecs.register_error that can handle UnicodeEncodeErrors.
endswith(suffix[, start[, end]]) → bool¶
Return True if S ends with the specified suffix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
suffix can also be a tuple of strings to try.
expandtabs(tabsize=8)¶
Return a copy where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
find(sub[, start[, end]]) → int¶
Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end].  Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
format(*args, **kwargs) → str¶
Return a formatted version of S, using substitutions from args and kwargs.
The substitutions are identified by braces (‘{’ and ‘}’).
format_map(mapping) → str¶
Return a formatted version of S, using substitutions from mapping.
The substitutions are identified by braces (‘{’ and ‘}’).
classmethod from_str(verb: str) → HTTPVerb[source]¶
Parse an HTTP verb.


Parse an HTTP verb.
index(sub[, start[, end]]) → int¶
Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end].  Optional
arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
isalnum()¶
Return True if the string is an alpha-numeric string, False otherwise.
A string is alpha-numeric if all characters in the string are alpha-numeric and
there is at least one character in the string.
isalpha()¶
Return True if the string is an alphabetic string, False otherwise.
A string is alphabetic if all characters in the string are alphabetic and there
is at least one character in the string.
isascii()¶
Return True if all characters in the string are ASCII, False otherwise.
ASCII characters have code points in the range U+0000-U+007F.
Empty string is ASCII too.
isdecimal()¶
Return True if the string is a decimal string, False otherwise.
A string is a decimal string if all characters in the string are decimal and
there is at least one character in the string.
isdigit()¶
Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there
is at least one character in the string.
isidentifier()¶
Return True if the string is a valid Python identifier, False otherwise.
Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
such as “def” or “class”.
islower()¶
Return True if the string is a lowercase string, False otherwise.
A string is lowercase if all cased characters in the string are lowercase and
there is at least one cased character in the string.
isnumeric()¶


there is at least one cased character in the string.
isnumeric()¶
Return True if the string is a numeric string, False otherwise.
A string is numeric if all characters in the string are numeric and there is at
least one character in the string.
isprintable()¶
Return True if the string is printable, False otherwise.
A string is printable if all of its characters are considered printable in
repr() or if it is empty.
isspace()¶
Return True if the string is a whitespace string, False otherwise.
A string is whitespace if all characters in the string are whitespace and there
is at least one character in the string.
istitle()¶
Return True if the string is a title-cased string, False otherwise.
In a title-cased string, upper- and title-case characters may only
follow uncased characters and lowercase characters only cased ones.
isupper()¶
Return True if the string is an uppercase string, False otherwise.
A string is uppercase if all cased characters in the string are uppercase and
there is at least one cased character in the string.
join(iterable, /)¶
Concatenate any number of strings.
The string whose method is called is inserted in between each given string.
The result is returned as a new string.
Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’
ljust(width, fillchar=' ', /)¶
Return a left-justified string of length width.
Padding is done using the specified fill character (default is a space).
lower()¶
Return a copy of the string converted to lowercase.
lstrip(chars=None, /)¶
Return a copy of the string with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.


If chars is given and not None, remove characters in chars instead.
static maketrans()¶
Return a translation table usable for str.translate().
If there is only one argument, it must be a dictionary mapping Unicode
ordinals (integers) or characters to Unicode ordinals, strings or None.
Character keys will be then converted to ordinals.
If there are two arguments, they must be strings of equal length, and
in the resulting dictionary, each character in x will be mapped to the
character at the same position in y. If there is a third argument, it
must be a string, whose characters will be mapped to None in the result.
partition(sep, /)¶
Partition the string into three parts using the given separator.
This will search for the separator in the string.  If the separator is found,
returns a 3-tuple containing the part before the separator, the separator
itself, and the part after it.
If the separator is not found, returns a 3-tuple containing the original string
and two empty strings.
removeprefix(prefix, /)¶
Return a str with the given prefix string removed if present.
If the string starts with the prefix string, return string[len(prefix):].
Otherwise, return a copy of the original string.
removesuffix(suffix, /)¶
Return a str with the given suffix string removed if present.
If the string ends with the suffix string and that suffix is not empty,
return string[:-len(suffix)]. Otherwise, return a copy of the original
string.
replace(old, new, count=- 1, /)¶
Return a copy with all occurrences of substring old replaced by new.
countMaximum number of occurrences to replace.
-1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are


If the optional argument count is given, only the first count occurrences are
replaced.
rfind(sub[, start[, end]]) → int¶
Return the highest index in S where substring sub is found,
such that sub is contained within S[start:end].  Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
rindex(sub[, start[, end]]) → int¶
Return the highest index in S where substring sub is found,
such that sub is contained within S[start:end].  Optional
arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
rjust(width, fillchar=' ', /)¶
Return a right-justified string of length width.
Padding is done using the specified fill character (default is a space).
rpartition(sep, /)¶
Partition the string into three parts using the given separator.
This will search for the separator in the string, starting at the end. If
the separator is found, returns a 3-tuple containing the part before the
separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing two empty strings
and the original string.
rsplit(sep=None, maxsplit=- 1)¶
Return a list of the substrings in the string, using sep as the separator string.
sepThe separator used to split the string.
When set to None (the default value), will split on any whitespace
character (including \n \r \t \f and spaces) and will discard
empty strings from the result.
maxsplitMaximum number of splits (starting from the left).
-1 (the default value) means no limit.
Splitting starts at the end of the string and works to the front.
rstrip(chars=None, /)¶


rstrip(chars=None, /)¶
Return a copy of the string with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
split(sep=None, maxsplit=- 1)¶
Return a list of the substrings in the string, using sep as the separator string.
sepThe separator used to split the string.
When set to None (the default value), will split on any whitespace
character (including \n \r \t \f and spaces) and will discard
empty strings from the result.
maxsplitMaximum number of splits (starting from the left).
-1 (the default value) means no limit.
Note, str.split() is mainly useful for data that has been intentionally
delimited.  With natural text that includes punctuation, consider using
the regular expression module.
splitlines(keepends=False)¶
Return a list of the lines in the string, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends is given and
true.
startswith(prefix[, start[, end]]) → bool¶
Return True if S starts with the specified prefix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
prefix can also be a tuple of strings to try.
strip(chars=None, /)¶
Return a copy of the string with leading and trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
swapcase()¶
Convert uppercase characters to lowercase and lowercase characters to uppercase.
title()¶
Return a version of the string where each word is titlecased.
More specifically, words start with uppercased characters and all remaining
cased characters have lower case.
translate(table, /)¶
Replace each character in the string using the given translation table.


translate(table, /)¶
Replace each character in the string using the given translation table.
tableTranslation table, which must be a mapping of Unicode ordinals to
Unicode ordinals, strings, or None.
The table must implement lookup/indexing via __getitem__, for instance a
dictionary or list.  If this operation raises LookupError, the character is
left untouched.  Characters mapped to None are deleted.
upper()¶
Return a copy of the string converted to uppercase.
zfill(width, /)¶
Pad a numeric string with zeros on the left, to fill a field of the given width.
The string is never truncated.
DELETE = 'delete'¶
GET = 'get'¶
HEAD = 'head'¶
OPTIONS = 'options'¶
PATCH = 'patch'¶
POST = 'post'¶
PUT = 'put'¶
TRACE = 'trace'¶


langchain.utilities.searx_search.SearxResults¶
class langchain.utilities.searx_search.SearxResults(data: str)[source]¶
Bases: dict
Dict like wrapper around search api results.
Take a raw result from Searx and make it into a dict like object.
Methods
__init__(data)
Take a raw result from Searx and make it into a dict like object.
clear()
copy()
fromkeys([value])
Create a new dictionary with keys from iterable and values set to value.
get(key[, default])
Return the value for key if key is in the dictionary, else default.
items()
keys()
pop(k[,d])
If the key is not found, return the default if given; otherwise, raise a KeyError.
popitem()
Remove and return a (key, value) pair as a 2-tuple.
setdefault(key[, default])
Insert key with a value of default if key is not in the dictionary.
update([E, ]**F)
If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v In either case, this is followed by: for k in F:  D[k] = F[k]
values()
Attributes
answers
Helper accessor on the json result.
results
Silence mypy for accessing this field.
clear() → None.  Remove all items from D.¶
copy() → a shallow copy of D¶
fromkeys(value=None, /)¶
Create a new dictionary with keys from iterable and values set to value.
get(key, default=None, /)¶


get(key, default=None, /)¶
Return the value for key if key is in the dictionary, else default.
items() → a set-like object providing a view on D's items¶
keys() → a set-like object providing a view on D's keys¶
pop(k[, d]) → v, remove specified key and return the corresponding value.¶
If the key is not found, return the default if given; otherwise,
raise a KeyError.
popitem()¶
Remove and return a (key, value) pair as a 2-tuple.
Pairs are returned in LIFO (last-in, first-out) order.
Raises KeyError if the dict is empty.
setdefault(key, default=None, /)¶
Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
update([E, ]**F) → None.  Update D from dict/iterable E and F.¶
If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
In either case, this is followed by: for k in F:  D[k] = F[k]
values() → an object providing a view on D's values¶
property answers: Any¶
Helper accessor on the json result.


langchain.utilities.openweathermap.OpenWeatherMapAPIWrapper¶
class langchain.utilities.openweathermap.OpenWeatherMapAPIWrapper(*, owm: Any = None, openweathermap_api_key: Optional[str] = None)[source]¶
Bases: BaseModel
Wrapper for OpenWeatherMap API using PyOWM.
Docs for using:
Go to OpenWeatherMap and sign up for an API key
Save your API KEY into OPENWEATHERMAP_API_KEY env variable
pip install pyowm
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param openweathermap_api_key: Optional[str] = None¶
param owm: Any = None¶
run(location: str) → str[source]¶
Get the current weather information for a specified location.
validator validate_environment  »  all fields[source]¶
Validate that api key exists in environment.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
extra = 'forbid'¶


langchain.utilities.google_places_api.GooglePlacesAPIWrapper¶
class langchain.utilities.google_places_api.GooglePlacesAPIWrapper(*, gplaces_api_key: Optional[str] = None, google_map_client: Any = None, top_k_results: Optional[int] = None)[source]¶
Bases: BaseModel
Wrapper around Google Places API.
To use, you should have the googlemaps python package installed,an API key for the google maps platform,
and the enviroment variable ‘’GPLACES_API_KEY’’
set with your API key , or pass ‘gplaces_api_key’
as a named parameter to the constructor.
By default, this will return the all the results on the input query.You can use the top_k_results argument to limit the number of results.
Example
from langchain import GooglePlacesAPIWrapper
gplaceapi = GooglePlacesAPIWrapper()
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param gplaces_api_key: Optional[str] = None¶
param top_k_results: Optional[int] = None¶
fetch_place_details(place_id: str) → Optional[str][source]¶
format_place_details(place_details: Dict[str, Any]) → Optional[str][source]¶
run(query: str) → str[source]¶
Run Places search and get k number of places that exists that match.
validator validate_environment  »  all fields[source]¶
Validate that api key is in your environment variable.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
arbitrary_types_allowed = True¶
extra = 'forbid'¶


langchain.utilities.loading.try_load_from_hub¶
langchain.utilities.loading.try_load_from_hub(path: Union[str, Path], loader: Callable[[str], T], valid_prefix: str, valid_suffixes: Set[str], **kwargs: Any) → Optional[T][source]¶
Load configuration from hub.  Returns None if path is not a hub path.


langchain.utilities.graphql.GraphQLAPIWrapper¶
class langchain.utilities.graphql.GraphQLAPIWrapper(*, custom_headers: Optional[Dict[str, str]] = None, graphql_endpoint: str, gql_client: Any = None, gql_function: Callable[[str], Any])[source]¶
Bases: BaseModel
Wrapper around GraphQL API.
To use, you should have the gql python package installed.
This wrapper will use the GraphQL API to conduct queries.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param custom_headers: Optional[Dict[str, str]] = None¶
param graphql_endpoint: str [Required]¶
run(query: str) → str[source]¶
Run a GraphQL query and get the results.
validator validate_environment  »  all fields[source]¶
Validate that the python package exists in the environment.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
extra = 'forbid'¶


langchain.utilities.serpapi.SerpAPIWrapper¶
class langchain.utilities.serpapi.SerpAPIWrapper(*, search_engine: Any = None, params: dict = {'engine': 'google', 'gl': 'us', 'google_domain': 'google.com', 'hl': 'en'}, serpapi_api_key: Optional[str] = None, aiosession: Optional[ClientSession] = None)[source]¶
Bases: BaseModel
Wrapper around SerpAPI.
To use, you should have the google-search-results python package installed,
and the environment variable SERPAPI_API_KEY set with your API key, or pass
serpapi_api_key as a named parameter to the constructor.
Example
from langchain.utilities import SerpAPIWrapper
serpapi = SerpAPIWrapper()
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param aiosession: Optional[aiohttp.client.ClientSession] = None¶
param params: dict = {'engine': 'google', 'gl': 'us', 'google_domain': 'google.com', 'hl': 'en'}¶
param serpapi_api_key: Optional[str] = None¶
async aresults(query: str) → dict[source]¶
Use aiohttp to run query through SerpAPI and return the results async.
async arun(query: str, **kwargs: Any) → str[source]¶
Run query through SerpAPI and parse result async.
get_params(query: str) → Dict[str, str][source]¶
Get parameters for SerpAPI.
results(query: str) → dict[source]¶
Run query through SerpAPI and return the raw result.
run(query: str, **kwargs: Any) → str[source]¶
Run query through SerpAPI and parse result.


Run query through SerpAPI and parse result.
validator validate_environment  »  all fields[source]¶
Validate that api key and python package exists in environment.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
arbitrary_types_allowed = True¶
extra = 'forbid'¶


langchain.utilities.powerbi.PowerBIDataset¶
class langchain.utilities.powerbi.PowerBIDataset(*, dataset_id: str, table_names: List[str], group_id: Optional[str] = None, credential: Optional[TokenCredential] = None, token: Optional[str] = None, impersonated_user_name: Optional[str] = None, sample_rows_in_table_info: ConstrainedIntValue = 1, schemas: Dict[str, str] = None, aiosession: Optional[ClientSession] = None)[source]¶
Bases: BaseModel
Create PowerBI engine from dataset ID and credential or token.
Use either the credential or a supplied token to authenticate.
If both are supplied the credential is used to generate a token.
The impersonated_user_name is the UPN of a user to be impersonated.
If the model is not RLS enabled, this will be ignored.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param aiosession: Optional[aiohttp.ClientSession] = None¶
param credential: Optional[TokenCredential] = None¶
param dataset_id: str [Required]¶
param group_id: Optional[str] = None¶
param impersonated_user_name: Optional[str] = None¶
param sample_rows_in_table_info: int = 1¶
Constraints
exclusiveMinimum = 0
maximum = 10
param schemas: Dict[str, str] [Optional]¶
param table_names: List[str] [Required]¶
param token: Optional[str] = None¶
async aget_table_info(table_names: Optional[Union[List[str], str]] = None) → str[source]¶
Get information about specified tables.
async arun(command: str) → Any[source]¶
Execute a DAX command and return the result asynchronously.


Execute a DAX command and return the result asynchronously.
validator fix_table_names  »  table_names[source]¶
Fix the table names.
get_schemas() → str[source]¶
Get the available schema’s.
get_table_info(table_names: Optional[Union[List[str], str]] = None) → str[source]¶
Get information about specified tables.
get_table_names() → Iterable[str][source]¶
Get names of tables available.
run(command: str) → Any[source]¶
Execute a DAX command and return a json representing the results.
validator token_or_credential_present  »  all fields[source]¶
Validate that at least one of token and credentials is present.
property headers: Dict[str, str]¶
Get the token.
property request_url: str¶
Get the request url.
property table_info: str¶
Information about all tables in the database.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
arbitrary_types_allowed = True¶


langchain.utilities.google_search.GoogleSearchAPIWrapper¶
class langchain.utilities.google_search.GoogleSearchAPIWrapper(*, search_engine: Any = None, google_api_key: Optional[str] = None, google_cse_id: Optional[str] = None, k: int = 10, siterestrict: bool = False)[source]¶
Bases: BaseModel
Wrapper for Google Search API.
Adapted from: Instructions adapted from https://stackoverflow.com/questions/
37083058/
programmatically-searching-google-in-python-using-custom-search
TODO: DOCS for using it
1. Install google-api-python-client
- If you don’t already have a Google account, sign up.
- If you have never created a Google APIs Console project,
read the Managing Projects page and create a project in the Google API Console.
- Install the library using pip install google-api-python-client
The current version of the library is 2.70.0 at this time
2. To create an API key:
- Navigate to the APIs & Services→Credentials panel in Cloud Console.
- Select Create credentials, then select API key from the drop-down menu.
- The API key created dialog box displays your newly created key.
- You now have an API_KEY
3. Setup Custom Search Engine so you can search the entire web
- Create a custom search engine in this link.
- In Sites to search, add any valid URL (i.e. www.stackoverflow.com).
- That’s all you have to fill up, the rest doesn’t matter.
In the left-side menu, click Edit search engine → {your search engine name}
→ Setup Set Search the entire web to ON. Remove the URL you added from
the list of Sites to search.
- Under Search engine ID you’ll find the search-engine-ID.
4. Enable the Custom Search API


4. Enable the Custom Search API
- Navigate to the APIs & Services→Dashboard panel in Cloud Console.
- Click Enable APIs and Services.
- Search for Custom Search API and click on it.
- Click Enable.
URL for it: https://console.cloud.google.com/apis/library/customsearch.googleapis
.com
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param google_api_key: Optional[str] = None¶
param google_cse_id: Optional[str] = None¶
param k: int = 10¶
param siterestrict: bool = False¶
results(query: str, num_results: int) → List[Dict][source]¶
Run query through GoogleSearch and return metadata.
Parameters
query – The query to search for.
num_results – The number of results to return.
Returns
snippet - The description of the result.
title - The title of the result.
link - The link to the result.
Return type
A list of dictionaries with the following keys
run(query: str) → str[source]¶
Run query through GoogleSearch and parse result.
validator validate_environment  »  all fields[source]¶
Validate that api key and python package exists in environment.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
extra = 'forbid'¶


langchain.utilities.pupmed.PubMedAPIWrapper¶
class langchain.utilities.pupmed.PubMedAPIWrapper(*, top_k_results: int = 3, load_max_docs: int = 25, doc_content_chars_max: int = 2000, load_all_available_meta: bool = False, email: str = 'your_email@example.com', base_url_esearch: str = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?', base_url_efetch: str = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?', max_retry: int = 5, sleep_time: float = 0.2, ARXIV_MAX_QUERY_LENGTH: int = 300)[source]¶
Bases: BaseModel
Wrapper around PubMed API.
This wrapper will use the PubMed API to conduct searches and fetch
document summaries. By default, it will return the document summaries
of the top-k results of an input search.
Parameters
top_k_results – number of the top-scored document used for the PubMed tool
load_max_docs – a limit to the number of loaded documents
load_all_available_meta –
if True: the metadata of the loaded Documents gets all available meta info(see https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ESearch)
if False: the metadata gets only the most informative fields.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param doc_content_chars_max: int = 2000¶
param email: str = 'your_email@example.com'¶
param load_all_available_meta: bool = False¶
param load_max_docs: int = 25¶
param top_k_results: int = 3¶


param top_k_results: int = 3¶
load(query: str) → List[dict][source]¶
Search PubMed for documents matching the query.
Return a list of dictionaries containing the document metadata.
load_docs(query: str) → List[Document][source]¶
retrieve_article(uid: str, webenv: str) → dict[source]¶
run(query: str) → str[source]¶
Run PubMed search and get the article meta information.
See https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ESearch
It uses only the most informative fields of article meta information.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
extra = 'forbid'¶


langchain.utilities.metaphor_search.MetaphorSearchAPIWrapper¶
class langchain.utilities.metaphor_search.MetaphorSearchAPIWrapper(*, metaphor_api_key: str, k: int = 10)[source]¶
Bases: BaseModel
Wrapper for Metaphor Search API.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param k: int = 10¶
param metaphor_api_key: str [Required]¶
results(query: str, num_results: int, include_domains: Optional[List[str]] = None, exclude_domains: Optional[List[str]] = None, start_crawl_date: Optional[str] = None, end_crawl_date: Optional[str] = None, start_published_date: Optional[str] = None, end_published_date: Optional[str] = None) → List[Dict][source]¶
Run query through Metaphor Search and return metadata.
Parameters
query – The query to search for.
num_results – The number of results to return.
Returns
title - The title of the
url - The url
author - Author of the content, if applicable. Otherwise, None.
published_date - Estimated date published
in YYYY-MM-DD format. Otherwise, None.
Return type
A list of dictionaries with the following keys
async results_async(query: str, num_results: int, include_domains: Optional[List[str]] = None, exclude_domains: Optional[List[str]] = None, start_crawl_date: Optional[str] = None, end_crawl_date: Optional[str] = None, start_published_date: Optional[str] = None, end_published_date: Optional[str] = None) → List[Dict][source]¶
Get results from the Metaphor Search API asynchronously.
validator validate_environment  »  all fields[source]¶


validator validate_environment  »  all fields[source]¶
Validate that api key and endpoint exists in environment.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
extra = 'forbid'¶


langchain.utilities.duckduckgo_search.DuckDuckGoSearchAPIWrapper¶
class langchain.utilities.duckduckgo_search.DuckDuckGoSearchAPIWrapper(*, k: int = 10, region: Optional[str] = 'wt-wt', safesearch: str = 'moderate', time: Optional[str] = 'y', max_results: int = 5)[source]¶
Bases: BaseModel
Wrapper for DuckDuckGo Search API.
Free and does not require any setup
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param k: int = 10¶
param max_results: int = 5¶
param region: Optional[str] = 'wt-wt'¶
param safesearch: str = 'moderate'¶
param time: Optional[str] = 'y'¶
get_snippets(query: str) → List[str][source]¶
Run query through DuckDuckGo and return concatenated results.
results(query: str, num_results: int) → List[Dict[str, str]][source]¶
Run query through DuckDuckGo and return metadata.
Parameters
query – The query to search for.
num_results – The number of results to return.
Returns
snippet - The description of the result.
title - The title of the result.
link - The link to the result.
Return type
A list of dictionaries with the following keys
run(query: str) → str[source]¶
validator validate_environment  »  all fields[source]¶
Validate that python package exists in environment.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
extra = 'forbid'¶


langchain.utilities.vertexai.raise_vertex_import_error¶
langchain.utilities.vertexai.raise_vertex_import_error() → None[source]¶
Raise ImportError related to Vertex SDK being not available.
Raises
ImportError – an ImportError that mentions a required version of the SDK.


langchain.utilities.apify.ApifyWrapper¶
class langchain.utilities.apify.ApifyWrapper(*, apify_client: Any = None, apify_client_async: Any = None)[source]¶
Bases: BaseModel
Wrapper around Apify.
To use, you should have the apify-client python package installed,
and the environment variable APIFY_API_TOKEN set with your API key, or pass
apify_api_token as a named parameter to the constructor.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param apify_client: Any = None¶
param apify_client_async: Any = None¶
async acall_actor(actor_id: str, run_input: Dict, dataset_mapping_function: Callable[[Dict], Document], *, build: Optional[str] = None, memory_mbytes: Optional[int] = None, timeout_secs: Optional[int] = None) → ApifyDatasetLoader[source]¶
Run an Actor on the Apify platform and wait for results to be ready.
Parameters
actor_id (str) – The ID or name of the Actor on the Apify platform.
run_input (Dict) – The input object of the Actor that you’re trying to run.
dataset_mapping_function (Callable) – A function that takes a single
dictionary (an Apify dataset item) and converts it to
an instance of the Document class.
build (str, optional) – Optionally specifies the actor build to run.
It can be either a build tag or build number.
memory_mbytes (int, optional) – Optional memory limit for the run,
in megabytes.
timeout_secs (int, optional) – Optional timeout for the run, in seconds.
Returns
A loader that will fetch the records from theActor run’s default dataset.
Return type
ApifyDatasetLoader


Return type
ApifyDatasetLoader
async acall_actor_task(task_id: str, task_input: Dict, dataset_mapping_function: Callable[[Dict], Document], *, build: Optional[str] = None, memory_mbytes: Optional[int] = None, timeout_secs: Optional[int] = None) → ApifyDatasetLoader[source]¶
Run a saved Actor task on Apify and wait for results to be ready.
Parameters
task_id (str) – The ID or name of the task on the Apify platform.
task_input (Dict) – The input object of the task that you’re trying to run.
Overrides the task’s saved input.
dataset_mapping_function (Callable) – A function that takes a single
dictionary (an Apify dataset item) and converts it to an
instance of the Document class.
build (str, optional) – Optionally specifies the actor build to run.
It can be either a build tag or build number.
memory_mbytes (int, optional) – Optional memory limit for the run,
in megabytes.
timeout_secs (int, optional) – Optional timeout for the run, in seconds.
Returns
A loader that will fetch the records from thetask run’s default dataset.
Return type
ApifyDatasetLoader
call_actor(actor_id: str, run_input: Dict, dataset_mapping_function: Callable[[Dict], Document], *, build: Optional[str] = None, memory_mbytes: Optional[int] = None, timeout_secs: Optional[int] = None) → ApifyDatasetLoader[source]¶
Run an Actor on the Apify platform and wait for results to be ready.
Parameters
actor_id (str) – The ID or name of the Actor on the Apify platform.
run_input (Dict) – The input object of the Actor that you’re trying to run.
dataset_mapping_function (Callable) – A function that takes a single


dataset_mapping_function (Callable) – A function that takes a single
dictionary (an Apify dataset item) and converts it to an
instance of the Document class.
build (str, optional) – Optionally specifies the actor build to run.
It can be either a build tag or build number.
memory_mbytes (int, optional) – Optional memory limit for the run,
in megabytes.
timeout_secs (int, optional) – Optional timeout for the run, in seconds.
Returns
A loader that will fetch the records from theActor run’s default dataset.
Return type
ApifyDatasetLoader
call_actor_task(task_id: str, task_input: Dict, dataset_mapping_function: Callable[[Dict], Document], *, build: Optional[str] = None, memory_mbytes: Optional[int] = None, timeout_secs: Optional[int] = None) → ApifyDatasetLoader[source]¶
Run a saved Actor task on Apify and wait for results to be ready.
Parameters
task_id (str) – The ID or name of the task on the Apify platform.
task_input (Dict) – The input object of the task that you’re trying to run.
Overrides the task’s saved input.
dataset_mapping_function (Callable) – A function that takes a single
dictionary (an Apify dataset item) and converts it to an
instance of the Document class.
build (str, optional) – Optionally specifies the actor build to run.
It can be either a build tag or build number.
memory_mbytes (int, optional) – Optional memory limit for the run,
in megabytes.
timeout_secs (int, optional) – Optional timeout for the run, in seconds.
Returns
A loader that will fetch the records from thetask run’s default dataset.
Return type
ApifyDatasetLoader
validator validate_environment  »  all fields[source]¶


Return type
ApifyDatasetLoader
validator validate_environment  »  all fields[source]¶
Validate environment.
Validate that an Apify API token is set and the apify-client
Python package exists in the current environment.


langchain.utilities.brave_search.BraveSearchWrapper¶
class langchain.utilities.brave_search.BraveSearchWrapper(*, api_key: str, search_kwargs: dict = None)[source]¶
Bases: BaseModel
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param api_key: str [Required]¶
param search_kwargs: dict [Optional]¶
run(query: str) → str[source]¶


langchain.utilities.jira.JiraAPIWrapper¶


class langchain.utilities.jira.JiraAPIWrapper(*, jira: Any = None, confluence: Any = None, jira_username: Optional[str] = None, jira_api_token: Optional[str] = None, jira_instance_url: Optional[str] = None, operations: List[Dict] = [{'mode': 'jql', 'name': 'JQL Query', 'description': '\n    This tool is a wrapper around atlassian-python-api\'s Jira jql API, useful when you need to search for Jira issues.\n    The input to this tool is a JQL query string, and will be passed into atlassian-python-api\'s Jira `jql` function,\n    For example, to find all the issues in project "Test" assigned to the me, you would pass in the following string:\n    project = Test AND assignee = currentUser()\n    or to find issues with summaries that contain the word "test", you would pass in the following string:\n    summary ~ \'test\'\n    '}, {'mode': 'get_projects', 'name': 'Get Projects', 'description': "\n    This tool is a wrapper around atlassian-python-api's Jira project API, \n    useful when you need to fetch all the projects the user has access to, find out how many projects there are, or as an intermediary step that involv searching by projects. \n    there is no input to this tool.\n    "}, {'mode': 'create_issue', 'name': 'Create Issue', 'description': '\n    This tool is a wrapper around atlassian-python-api\'s Jira issue_create API, useful when you need to create a Jira issue. \n    The input to this tool is a dictionary specifying the fields of the Jira issue, and will be passed into atlassian-python-api\'s Jira `issue_create`


issue, and will be passed into atlassian-python-api\'s Jira `issue_create` function.\n    For example, to create a low priority task called "test issue" with description "test description", you would pass in the following dictionary: \n    {{"summary": "test issue", "description": "test description", "issuetype": {{"name": "Task"}}, "priority": {{"name": "Low"}}}}\n    '}, {'mode': 'other', 'name': 'Catch all Jira API call', 'description': '\n    This tool is a wrapper around atlassian-python-api\'s Jira API.\n    There are other dedicated tools for fetching all projects, and creating and searching for issues, \n    use this tool if you need to perform any other actions allowed by the atlassian-python-api Jira API.\n    The input to this tool is line of python code that calls a function from atlassian-python-api\'s Jira API\n    For example, to update the summary field of an issue, you would pass in the following string:\n    self.jira.update_issue_field(key, {{"summary": "New summary"}})\n    or to find out how many projects are in the Jira instance, you would pass in the following string:\n    self.jira.projects()\n    For more information on the Jira API, refer to https://atlassian-python-api.readthedocs.io/jira.html\n    '}, {'mode': 'create_page', 'name': 'Create confluence page', 'description': 'This tool is a wrapper around atlassian-python-api\'s Confluence \natlassian-python-api API, useful when you need to create a Confluence page. The input to this tool is a dictionary \nspecifying the fields of the Confluence page, and will be passed into atlassian-python-api\'s Confluence `create_page`


page, and will be passed into atlassian-python-api\'s Confluence `create_page` \nfunction. For example, to create a page in the DEMO space titled "This is the title" with body "This is the body. You can use \nHTML tags!", you would pass in the following dictionary: {{"space": "DEMO", "title":"This is the \ntitle","body":"This is the body. You can use HTML tags!"}} '}])[source]¶


Bases: BaseModel
Wrapper for Jira API.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param confluence: Any = None¶
param jira_api_token: Optional[str] = None¶
param jira_instance_url: Optional[str] = None¶
param jira_username: Optional[str] = None¶


param operations: List[Dict] = [{'mode': 'jql', 'name': 'JQL Query', 'description': '\n    This tool is a wrapper around atlassian-python-api\'s Jira jql API, useful when you need to search for Jira issues.\n    The input to this tool is a JQL query string, and will be passed into atlassian-python-api\'s Jira `jql` function,\n    For example, to find all the issues in project "Test" assigned to the me, you would pass in the following string:\n    project = Test AND assignee = currentUser()\n    or to find issues with summaries that contain the word "test", you would pass in the following string:\n    summary ~ \'test\'\n    '}, {'mode': 'get_projects', 'name': 'Get Projects', 'description': "\n    This tool is a wrapper around atlassian-python-api's Jira project API, \n    useful when you need to fetch all the projects the user has access to, find out how many projects there are, or as an intermediary step that involv searching by projects. \n    there is no input to this tool.\n    "}, {'mode': 'create_issue', 'name': 'Create Issue', 'description': '\n    This tool is a wrapper around atlassian-python-api\'s Jira issue_create API, useful when you need to create a Jira issue. \n    The input to this tool is a dictionary specifying the fields of the Jira issue, and will be passed into atlassian-python-api\'s Jira `issue_create` function.\n    For example, to create a low priority task called "test issue" with description "test description", you would pass in the following dictionary: \n    {{"summary": "test issue", "description": "test description", "issuetype": {{"name":


"test issue", "description": "test description", "issuetype": {{"name": "Task"}}, "priority": {{"name": "Low"}}}}\n    '}, {'mode': 'other', 'name': 'Catch all Jira API call', 'description': '\n    This tool is a wrapper around atlassian-python-api\'s Jira API.\n    There are other dedicated tools for fetching all projects, and creating and searching for issues, \n    use this tool if you need to perform any other actions allowed by the atlassian-python-api Jira API.\n    The input to this tool is line of python code that calls a function from atlassian-python-api\'s Jira API\n    For example, to update the summary field of an issue, you would pass in the following string:\n    self.jira.update_issue_field(key, {{"summary": "New summary"}})\n    or to find out how many projects are in the Jira instance, you would pass in the following string:\n    self.jira.projects()\n    For more information on the Jira API, refer to https://atlassian-python-api.readthedocs.io/jira.html\n    '}, {'mode': 'create_page', 'name': 'Create confluence page', 'description': 'This tool is a wrapper around atlassian-python-api\'s Confluence \natlassian-python-api API, useful when you need to create a Confluence page. The input to this tool is a dictionary \nspecifying the fields of the Confluence page, and will be passed into atlassian-python-api\'s Confluence `create_page` \nfunction. For example, to create a page in the DEMO space titled "This is the title" with body "This is the body. You can use \nHTML tags!", you would pass in the following dictionary: {{"space": "DEMO",


you would pass in the following dictionary: {{"space": "DEMO", "title":"This is the \ntitle","body":"This is the body. You can use HTML tags!"}} '}]¶


issue_create(query: str) → str[source]¶
list() → List[Dict][source]¶
other(query: str) → str[source]¶
page_create(query: str) → str[source]¶
parse_issues(issues: Dict) → List[dict][source]¶
parse_projects(projects: List[dict]) → List[dict][source]¶
project() → str[source]¶
run(mode: str, query: str) → str[source]¶
search(query: str) → str[source]¶
validator validate_environment  »  all fields[source]¶
Validate that api key and python package exists in environment.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
extra = 'forbid'¶


langchain.utilities.arxiv.ArxivAPIWrapper¶
class langchain.utilities.arxiv.ArxivAPIWrapper(*, arxiv_search: Any = None, arxiv_exceptions: Any = None, top_k_results: int = 3, load_max_docs: int = 100, load_all_available_meta: bool = False, doc_content_chars_max: Optional[int] = 4000, ARXIV_MAX_QUERY_LENGTH: int = 300)[source]¶
Bases: BaseModel
Wrapper around ArxivAPI.
To use, you should have the arxiv python package installed.
https://lukasschwab.me/arxiv.py/index.html
This wrapper will use the Arxiv API to conduct searches and
fetch document summaries. By default, it will return the document summaries
of the top-k results.
It limits the Document content by doc_content_chars_max.
Set doc_content_chars_max=None if you don’t want to limit the content size.
Parameters
top_k_results – number of the top-scored document used for the arxiv tool
ARXIV_MAX_QUERY_LENGTH – the cut limit on the query used for the arxiv tool.
load_max_docs – a limit to the number of loaded documents
load_all_available_meta –
if True: the metadata of the loaded Documents gets all available meta info(see https://lukasschwab.me/arxiv.py/index.html#Result),
if False: the metadata gets only the most informative fields.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param arxiv_exceptions: Any = None¶
param doc_content_chars_max: Optional[int] = 4000¶
param load_all_available_meta: bool = False¶
param load_max_docs: int = 100¶
param top_k_results: int = 3¶


param top_k_results: int = 3¶
load(query: str) → List[Document][source]¶
Run Arxiv search and get the article texts plus the article meta information.
See https://lukasschwab.me/arxiv.py/index.html#Search
Returns: a list of documents with the document.page_content in text format
run(query: str) → str[source]¶
Run Arxiv search and get the article meta information.
See https://lukasschwab.me/arxiv.py/index.html#Search
See https://lukasschwab.me/arxiv.py/index.html#Result
It uses only the most informative fields of article meta information.
validator validate_environment  »  all fields[source]¶
Validate that the python package exists in environment.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
extra = 'forbid'¶


langchain.utilities.vertexai.init_vertexai¶
langchain.utilities.vertexai.init_vertexai(project: Optional[str] = None, location: Optional[str] = None, credentials: Optional[Credentials] = None) → None[source]¶
Init vertexai.
Parameters
project – The default GCP project to use when making Vertex API calls.
location – The default location to use when making API calls.
credentials – The default custom
credentials to use when making API calls. If not provided credentials
will be ascertained from the environment.
Raises
ImportError – If importing vertexai SDK did not succeed.


langchain.utilities.searx_search.SearxSearchWrapper¶
class langchain.utilities.searx_search.SearxSearchWrapper(*, searx_host: str = '', unsecure: bool = False, params: dict = None, headers: Optional[dict] = None, engines: Optional[List[str]] = [], categories: Optional[List[str]] = [], query_suffix: Optional[str] = '', k: int = 10, aiosession: Optional[Any] = None)[source]¶
Bases: BaseModel
Wrapper for Searx API.
To use you need to provide the searx host by passing the named parameter
searx_host or exporting the environment variable SEARX_HOST.
In some situations you might want to disable SSL verification, for example
if you are running searx locally. You can do this by passing the named parameter
unsecure. You can also pass the host url scheme as http to disable SSL.
Example
from langchain.utilities import SearxSearchWrapper
searx = SearxSearchWrapper(searx_host="http://localhost:8888")
Example with SSL disabled:from langchain.utilities import SearxSearchWrapper
# note the unsecure parameter is not needed if you pass the url scheme as
# http
searx = SearxSearchWrapper(searx_host="http://localhost:8888",
                                        unsecure=True)
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param aiosession: Optional[Any] = None¶
param categories: Optional[List[str]] = []¶
param engines: Optional[List[str]] = []¶
param headers: Optional[dict] = None¶
param k: int = 10¶
param params: dict [Optional]¶


param k: int = 10¶
param params: dict [Optional]¶
param query_suffix: Optional[str] = ''¶
param searx_host: str = ''¶
param unsecure: bool = False¶
async aresults(query: str, num_results: int, engines: Optional[List[str]] = None, query_suffix: Optional[str] = '', **kwargs: Any) → List[Dict][source]¶
Asynchronously query with json results.
Uses aiohttp. See results for more info.
async arun(query: str, engines: Optional[List[str]] = None, query_suffix: Optional[str] = '', **kwargs: Any) → str[source]¶
Asynchronously version of run.
validator disable_ssl_warnings  »  unsecure[source]¶
Disable SSL warnings.
results(query: str, num_results: int, engines: Optional[List[str]] = None, categories: Optional[List[str]] = None, query_suffix: Optional[str] = '', **kwargs: Any) → List[Dict][source]¶
Run query through Searx API and returns the results with metadata.
Parameters
query – The query to search for.
query_suffix – Extra suffix appended to the query.
num_results – Limit the number of results to return.
engines – List of engines to use for the query.
categories – List of categories to use for the query.
**kwargs – extra parameters to pass to the searx API.
Returns
{snippet:  The description of the result.
title:  The title of the result.
link: The link to the result.
engines: The engines used for the result.
category: Searx category of the result.
}
Return type
Dict with the following keys


}
Return type
Dict with the following keys
run(query: str, engines: Optional[List[str]] = None, categories: Optional[List[str]] = None, query_suffix: Optional[str] = '', **kwargs: Any) → str[source]¶
Run query through Searx API and parse results.
You can pass any other params to the searx query API.
Parameters
query – The query to search for.
query_suffix – Extra suffix appended to the query.
engines – List of engines to use for the query.
categories – List of categories to use for the query.
**kwargs – extra parameters to pass to the searx API.
Returns
The result of the query.
Return type
str
Raises
ValueError – If an error occurred with the query.
Example
This will make a query to the qwant engine:
from langchain.utilities import SearxSearchWrapper
searx = SearxSearchWrapper(searx_host="http://my.searx.host")
searx.run("what is the weather in France ?", engine="qwant")
# the same result can be achieved using the `!` syntax of searx
# to select the engine using `query_suffix`
searx.run("what is the weather in France ?", query_suffix="!qwant")
validator validate_params  »  all fields[source]¶
Validate that custom searx params are merged with default ones.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
extra = 'forbid'¶


langchain.utilities.powerbi.fix_table_name¶
langchain.utilities.powerbi.fix_table_name(table: str) → str[source]¶
Add single quotes around table names that contain spaces.


langchain.utilities.zapier.ZapierNLAWrapper¶
class langchain.utilities.zapier.ZapierNLAWrapper(*, zapier_nla_api_key: str, zapier_nla_oauth_access_token: str, zapier_nla_api_base: str = 'https://nla.zapier.com/api/v1/')[source]¶
Bases: BaseModel
Wrapper for Zapier NLA.
Full docs here: https://nla.zapier.com/start/
This wrapper supports both API Key and OAuth Credential auth methods. API Key
is the fastest way to get started using this wrapper.
Call this wrapper with either zapier_nla_api_key or
zapier_nla_oauth_access_token arguments, or set the ZAPIER_NLA_API_KEY
environment variable. If both arguments are set, the Access Token will take
precedence.
For use-cases where LangChain + Zapier NLA is powering a user-facing application,
and LangChain needs access to the end-user’s connected accounts on Zapier.com,
you’ll need to use OAuth. Review the full docs above to learn how to create
your own provider and generate credentials.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param zapier_nla_api_base: str = 'https://nla.zapier.com/api/v1/'¶
param zapier_nla_api_key: str [Required]¶
param zapier_nla_oauth_access_token: str [Required]¶
async alist() → List[Dict][source]¶
Returns a list of all exposed (enabled) actions associated with
current user (associated with the set api_key). Change your exposed
actions here: https://nla.zapier.com/demo/start/
The return list can be empty if no actions exposed. Else will contain


The return list can be empty if no actions exposed. Else will contain
a list of action objects:
[{“id”: str,
“description”: str,
“params”: Dict[str, str]
}]
params will always contain an instructions key, the only required
param. All others optional and if provided will override any AI guesses
(see “understanding the AI guessing flow” here:
https://nla.zapier.com/api/v1/docs)
async alist_as_str() → str[source]¶
Same as list, but returns a stringified version of the JSON for
insertting back into an LLM.
async apreview(action_id: str, instructions: str, params: Optional[Dict] = None) → Dict[source]¶
Same as run, but instead of actually executing the action, will
instead return a preview of params that have been guessed by the AI in
case you need to explicitly review before executing.
async apreview_as_str(*args, **kwargs) → str[source]¶
Same as preview, but returns a stringified version of the JSON for
insertting back into an LLM.
async arun(action_id: str, instructions: str, params: Optional[Dict] = None) → Dict[source]¶
Executes an action that is identified by action_id, must be exposed
(enabled) by the current user (associated with the set api_key). Change
your exposed actions here: https://nla.zapier.com/demo/start/
The return JSON is guaranteed to be less than ~500 words (350
tokens) making it safe to inject into the prompt of another LLM
call.
async arun_as_str(*args, **kwargs) → str[source]¶
Same as run, but returns a stringified version of the JSON for
insertting back into an LLM.


insertting back into an LLM.
list() → List[Dict][source]¶
Returns a list of all exposed (enabled) actions associated with
current user (associated with the set api_key). Change your exposed
actions here: https://nla.zapier.com/demo/start/
The return list can be empty if no actions exposed. Else will contain
a list of action objects:
[{“id”: str,
“description”: str,
“params”: Dict[str, str]
}]
params will always contain an instructions key, the only required
param. All others optional and if provided will override any AI guesses
(see “understanding the AI guessing flow” here:
https://nla.zapier.com/docs/using-the-api#ai-guessing)
list_as_str() → str[source]¶
Same as list, but returns a stringified version of the JSON for
insertting back into an LLM.
preview(action_id: str, instructions: str, params: Optional[Dict] = None) → Dict[source]¶
Same as run, but instead of actually executing the action, will
instead return a preview of params that have been guessed by the AI in
case you need to explicitly review before executing.
preview_as_str(*args, **kwargs) → str[source]¶
Same as preview, but returns a stringified version of the JSON for
insertting back into an LLM.
run(action_id: str, instructions: str, params: Optional[Dict] = None) → Dict[source]¶
Executes an action that is identified by action_id, must be exposed
(enabled) by the current user (associated with the set api_key). Change
your exposed actions here: https://nla.zapier.com/demo/start/
The return JSON is guaranteed to be less than ~500 words (350


The return JSON is guaranteed to be less than ~500 words (350
tokens) making it safe to inject into the prompt of another LLM
call.
run_as_str(*args, **kwargs) → str[source]¶
Same as run, but returns a stringified version of the JSON for
insertting back into an LLM.
validator validate_environment  »  all fields[source]¶
Validate that api key exists in environment.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
extra = 'forbid'¶


langchain.utilities.wolfram_alpha.WolframAlphaAPIWrapper¶
class langchain.utilities.wolfram_alpha.WolframAlphaAPIWrapper(*, wolfram_client: Any = None, wolfram_alpha_appid: Optional[str] = None)[source]¶
Bases: BaseModel
Wrapper for Wolfram Alpha.
Docs for using:
Go to wolfram alpha and sign up for a developer account
Create an app and get your APP ID
Save your APP ID into WOLFRAM_ALPHA_APPID env variable
pip install wolframalpha
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param wolfram_alpha_appid: Optional[str] = None¶
run(query: str) → str[source]¶
Run query through WolframAlpha and parse result.
validator validate_environment  »  all fields[source]¶
Validate that api key and python package exists in environment.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
extra = 'forbid'¶


langchain.utilities.bing_search.BingSearchAPIWrapper¶
class langchain.utilities.bing_search.BingSearchAPIWrapper(*, bing_subscription_key: str, bing_search_url: str, k: int = 10)[source]¶
Bases: BaseModel
Wrapper for Bing Search API.
In order to set this up, follow instructions at:
https://levelup.gitconnected.com/api-tutorial-how-to-use-bing-web-search-api-in-python-4165d5592a7e
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param bing_search_url: str [Required]¶
param bing_subscription_key: str [Required]¶
param k: int = 10¶
results(query: str, num_results: int) → List[Dict][source]¶
Run query through BingSearch and return metadata.
Parameters
query – The query to search for.
num_results – The number of results to return.
Returns
snippet - The description of the result.
title - The title of the result.
link - The link to the result.
Return type
A list of dictionaries with the following keys
run(query: str) → str[source]¶
Run query through BingSearch and parse result.
validator validate_environment  »  all fields[source]¶
Validate that api key and endpoint exists in environment.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
extra = 'forbid'¶


langchain.utilities.twilio.TwilioAPIWrapper¶
class langchain.utilities.twilio.TwilioAPIWrapper(*, client: Any = None, account_sid: Optional[str] = None, auth_token: Optional[str] = None, from_number: Optional[str] = None)[source]¶
Bases: BaseModel
Messaging Client using Twilio.
To use, you should have the twilio python package installed,
and the environment variables TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, and
TWILIO_FROM_NUMBER, or pass account_sid, auth_token, and from_number as
named parameters to the constructor.
Example
from langchain.utilities.twilio import TwilioAPIWrapper
twilio = TwilioAPIWrapper(
    account_sid="ACxxx",
    auth_token="xxx",
    from_number="+10123456789"
)
twilio.run('test', '+12484345508')
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param account_sid: Optional[str] = None¶
Twilio account string identifier.
param auth_token: Optional[str] = None¶
Twilio auth token.
param from_number: Optional[str] = None¶
A Twilio phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164)
format, an
[alphanumeric sender ID](https://www.twilio.com/docs/sms/send-messages#use-an-alphanumeric-sender-id),
or a [Channel Endpoint address](https://www.twilio.com/docs/sms/channels#channel-addresses)
that is enabled for the type of message you want to send. Phone numbers or
[short codes](https://www.twilio.com/docs/sms/api/short-code) purchased from


Twilio also work here. You cannot, for example, spoof messages from a private
cell phone number. If you are using messaging_service_sid, this parameter
must be empty.
run(body: str, to: str) → str[source]¶
Run body through Twilio and respond with message sid.
Parameters
body – The text of the message you want to send. Can be up to 1,600
characters in length.
to – The destination phone number in
[E.164](https://www.twilio.com/docs/glossary/what-e164) format for
SMS/MMS or
[Channel user address](https://www.twilio.com/docs/sms/channels#channel-addresses)
for other 3rd-party channels.
validator validate_environment  »  all fields[source]¶
Validate that api key and python package exists in environment.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
arbitrary_types_allowed = False¶
extra = 'forbid'¶


langchain.utilities.openapi.OpenAPISpec¶
class langchain.utilities.openapi.OpenAPISpec(*, openapi: str = '3.1.0', info: Info, jsonSchemaDialect: Optional[str] = None, servers: List[Server] = [Server(url='/', description=None, variables=None)], paths: Optional[Dict[str, PathItem]] = None, webhooks: Optional[Dict[str, Union[PathItem, Reference]]] = None, components: Optional[Components] = None, security: Optional[List[Dict[str, List[str]]]] = None, tags: Optional[List[Tag]] = None, externalDocs: Optional[ExternalDocumentation] = None)[source]¶
Bases: OpenAPI
OpenAPI Model that removes misformatted parts of the spec.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param components: Optional[openapi_schema_pydantic.v3.v3_1_0.components.Components] = None¶
An element to hold various schemas for the document.
param externalDocs: Optional[openapi_schema_pydantic.v3.v3_1_0.external_documentation.ExternalDocumentation] = None¶
Additional external documentation.
param info: openapi_schema_pydantic.v3.v3_1_0.info.Info [Required]¶
REQUIRED. Provides metadata about the API. The metadata MAY be used by tooling as required.
param jsonSchemaDialect: Optional[str] = None¶
The default value for the $schema keyword within [Schema Objects](#schemaObject)
contained within this OAS document. This MUST be in the form of a URI.
param openapi: str = '3.1.0'¶
REQUIRED. This string MUST be the [version number](#versions)


REQUIRED. This string MUST be the [version number](#versions)
of the OpenAPI Specification that the OpenAPI document uses.
The openapi field SHOULD be used by tooling to interpret the OpenAPI document.
This is not related to the API [info.version](#infoVersion) string.
param paths: Optional[Dict[str, openapi_schema_pydantic.v3.v3_1_0.path_item.PathItem]] = None¶
The available paths and operations for the API.
param security: Optional[List[Dict[str, List[str]]]] = None¶
A declaration of which security mechanisms can be used across the API.
The list of values includes alternative security requirement objects that can be used.
Only one of the security requirement objects need to be satisfied to authorize a request.
Individual operations can override this definition.
To make security optional, an empty security requirement ({}) can be included in the array.
param servers: List[openapi_schema_pydantic.v3.v3_1_0.server.Server] = [Server(url='/', description=None, variables=None)]¶
An array of Server Objects, which provide connectivity information to a target server.
If the servers property is not provided, or is an empty array,
the default value would be a [Server Object](#serverObject) with a [url](#serverUrl) value of /.
param tags: Optional[List[openapi_schema_pydantic.v3.v3_1_0.tag.Tag]] = None¶
A list of tags used by the document with additional metadata.
The order of the tags can be used to reflect on their order by the parsing tools.
Not all tags that are used by the [Operation Object](#operationObject) must be declared.
The tags that are not declared MAY be organized randomly or based on the tools’ logic.
Each tag name in the list MUST be unique.


Each tag name in the list MUST be unique.
param webhooks: Optional[Dict[str, Union[openapi_schema_pydantic.v3.v3_1_0.path_item.PathItem, openapi_schema_pydantic.v3.v3_1_0.reference.Reference]]] = None¶
The incoming webhooks that MAY be received as part of this API and that the API consumer MAY choose to implement.
Closely related to the callbacks feature, this section describes requests initiated other than by an API call,
for example by an out of band registration.
The key name is a unique string to refer to each webhook,
while the (optionally referenced) Path Item Object describes a request
that may be initiated by the API provider and the expected responses.
An [example](../examples/v3.1/webhook-example.yaml) is available.
classmethod from_file(path: Union[str, Path]) → OpenAPISpec[source]¶
Get an OpenAPI spec from a file path.
classmethod from_spec_dict(spec_dict: dict) → OpenAPISpec[source]¶
Get an OpenAPI spec from a dict.
classmethod from_text(text: str) → OpenAPISpec[source]¶
Get an OpenAPI spec from a text.
classmethod from_url(url: str) → OpenAPISpec[source]¶
Get an OpenAPI spec from a URL.
static get_cleaned_operation_id(operation: Operation, path: str, method: str) → str[source]¶
Get a cleaned operation id from an operation id.
get_methods_for_path(path: str) → List[str][source]¶
Return a list of valid methods for the specified path.
get_operation(path: str, method: str) → Operation[source]¶
Get the operation object for a given path and HTTP method.
get_parameters_for_operation(operation: Operation) → List[Parameter][source]¶


get_parameters_for_operation(operation: Operation) → List[Parameter][source]¶
Get the components for a given operation.
get_parameters_for_path(path: str) → List[Parameter][source]¶
get_referenced_schema(ref: Reference) → Schema[source]¶
Get a schema (or nested reference) or err.
get_request_body_for_operation(operation: Operation) → Optional[RequestBody][source]¶
Get the request body for a given operation.
get_schema(schema: Union[Reference, Schema]) → Schema[source]¶
classmethod parse_obj(obj: dict) → OpenAPISpec[source]¶
property base_url: str¶
Get the base url.
model Config¶
Bases: object
extra = 'ignore'¶


langchain.utilities.powerbi.json_to_md¶
langchain.utilities.powerbi.json_to_md(json_contents: List[Dict[str, Union[str, int, float]]], table_name: Optional[str] = None) → str[source]¶
Converts a JSON object to a markdown table.


langchain.utilities.google_serper.GoogleSerperAPIWrapper¶
class langchain.utilities.google_serper.GoogleSerperAPIWrapper(*, k: int = 10, gl: str = 'us', hl: str = 'en', type: Literal['news', 'search', 'places', 'images'] = 'search', tbs: Optional[str] = None, serper_api_key: Optional[str] = None, aiosession: Optional[ClientSession] = None, result_key_for_type: dict = {'images': 'images', 'news': 'news', 'places': 'places', 'search': 'organic'})[source]¶
Bases: BaseModel
Wrapper around the Serper.dev Google Search API.
You can create a free API key at https://serper.dev.
To use, you should have the environment variable SERPER_API_KEY
set with your API key, or pass serper_api_key as a named parameter
to the constructor.
Example
from langchain import GoogleSerperAPIWrapper
google_serper = GoogleSerperAPIWrapper()
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param aiosession: Optional[aiohttp.client.ClientSession] = None¶
param gl: str = 'us'¶
param hl: str = 'en'¶
param k: int = 10¶
param serper_api_key: Optional[str] = None¶
param tbs: Optional[str] = None¶
param type: Literal['news', 'search', 'places', 'images'] = 'search'¶
async aresults(query: str, **kwargs: Any) → Dict[source]¶
Run query through GoogleSearch.
async arun(query: str, **kwargs: Any) → str[source]¶


async arun(query: str, **kwargs: Any) → str[source]¶
Run query through GoogleSearch and parse result async.
results(query: str, **kwargs: Any) → Dict[source]¶
Run query through GoogleSearch.
run(query: str, **kwargs: Any) → str[source]¶
Run query through GoogleSearch and parse result.
validator validate_environment  »  all fields[source]¶
Validate that api key exists in environment.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
arbitrary_types_allowed = True¶


langchain.utilities.python.PythonREPL¶
class langchain.utilities.python.PythonREPL(*, _globals: Optional[Dict] = None, _locals: Optional[Dict] = None)[source]¶
Bases: BaseModel
Simulates a standalone Python REPL.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param globals: Optional[Dict] [Optional] (alias '_globals')¶
param locals: Optional[Dict] [Optional] (alias '_locals')¶
run(command: str) → str[source]¶
Run command with own globals/locals and returns anything printed.


langchain.utilities.bibtex.BibtexparserWrapper¶
class langchain.utilities.bibtex.BibtexparserWrapper[source]¶
Bases: BaseModel
Wrapper around bibtexparser.
To use, you should have the bibtexparser python package installed.
https://bibtexparser.readthedocs.io/en/master/
This wrapper will use bibtexparser to load a collection of references from
a bibtex file and fetch document summaries.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
get_metadata(entry: Mapping[str, Any], load_extra: bool = False) → Dict[str, Any][source]¶
Get metadata for the given entry.
load_bibtex_entries(path: str) → List[Dict[str, Any]][source]¶
Load bibtex entries from the bibtex file at the given path.
validator validate_environment  »  all fields[source]¶
Validate that the python package exists in environment.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
extra = 'forbid'¶


langchain.utilities.wikipedia.WikipediaAPIWrapper¶
class langchain.utilities.wikipedia.WikipediaAPIWrapper(*, wiki_client: Any = None, top_k_results: int = 3, lang: str = 'en', load_all_available_meta: bool = False, doc_content_chars_max: int = 4000)[source]¶
Bases: BaseModel
Wrapper around WikipediaAPI.
To use, you should have the wikipedia python package installed.
This wrapper will use the Wikipedia API to conduct searches and
fetch page summaries. By default, it will return the page summaries
of the top-k results.
It limits the Document content by doc_content_chars_max.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param doc_content_chars_max: int = 4000¶
param lang: str = 'en'¶
param load_all_available_meta: bool = False¶
param top_k_results: int = 3¶
load(query: str) → List[Document][source]¶
Run Wikipedia search and get the article text plus the meta information.
See
Returns: a list of documents.
run(query: str) → str[source]¶
Run Wikipedia search and get page summaries.
validator validate_environment  »  all fields[source]¶
Validate that the python package exists in environment.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
extra = 'forbid'¶


langchain.utilities.awslambda.LambdaWrapper¶
class langchain.utilities.awslambda.LambdaWrapper(*, lambda_client: Any = None, function_name: Optional[str] = None, awslambda_tool_name: Optional[str] = None, awslambda_tool_description: Optional[str] = None)[source]¶
Bases: BaseModel
Wrapper for AWS Lambda SDK.
Docs for using:
pip install boto3
Create a lambda function using the AWS Console or CLI
Run aws configure and enter your AWS credentials
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param awslambda_tool_description: Optional[str] = None¶
param awslambda_tool_name: Optional[str] = None¶
param function_name: Optional[str] = None¶
run(query: str) → str[source]¶
Invoke Lambda function and parse result.
validator validate_environment  »  all fields[source]¶
Validate that python package exists in environment.
model Config[source]¶
Bases: object
Configuration for this pydantic object.
extra = 'forbid'¶


langchain.utilities.scenexplain.SceneXplainAPIWrapper¶
class langchain.utilities.scenexplain.SceneXplainAPIWrapper(_env_file: Optional[Union[str, PathLike, List[Union[str, PathLike]], Tuple[Union[str, PathLike], ...]]] = '<object object>', _env_file_encoding: Optional[str] = None, _env_nested_delimiter: Optional[str] = None, _secrets_dir: Optional[Union[str, PathLike]] = None, *, scenex_api_key: str, scenex_api_url: str = 'https://us-central1-causal-diffusion.cloudfunctions.net/describe')[source]¶
Bases: BaseSettings, BaseModel
Wrapper for SceneXplain API.
In order to set this up, you need API key for the SceneXplain API.
You can obtain a key by following the steps below.
- Sign up for a free account at https://scenex.jina.ai/.
- Navigate to the API Access page (https://scenex.jina.ai/api)
and create a new API key.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param scenex_api_key: str [Required]¶
param scenex_api_url: str = 'https://us-central1-causal-diffusion.cloudfunctions.net/describe'¶
run(image: str) → str[source]¶
Run SceneXplain image explainer.
validator validate_environment  »  all fields[source]¶
Validate that api key exists in environment.
model Config¶
Bases: BaseConfig
getter_dict¶
alias of GetterDict


model Config¶
Bases: BaseConfig
getter_dict¶
alias of GetterDict
classmethod customise_sources(init_settings: Callable[[BaseSettings], Dict[str, Any]], env_settings: Callable[[BaseSettings], Dict[str, Any]], file_secret_settings: Callable[[BaseSettings], Dict[str, Any]]) → Tuple[Callable[[BaseSettings], Dict[str, Any]], ...]¶
classmethod get_field_info(name: unicode) → Dict[str, Any]¶
Get properties of FieldInfo from the fields property of the config class.
json_dumps(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)¶
Serialize obj to a JSON formatted str.
If skipkeys is true then dict keys that are not basic types
(str, int, float, bool, None) will be skipped
instead of raising a TypeError.
If ensure_ascii is false, then the return value can contain non-ASCII
characters if they appear in strings contained in obj. Otherwise, all
such characters are escaped in JSON strings.
If check_circular is false, then the circular reference check
for container types will be skipped and a circular reference will
result in an RecursionError (or worse).
If allow_nan is false, then it will be a ValueError to
serialize out of range float values (nan, inf, -inf) in
strict compliance of the JSON specification, instead of using the
JavaScript equivalents (NaN, Infinity, -Infinity).
If indent is a non-negative integer, then JSON array elements and
object members will be pretty-printed with that indent level. An indent
level of 0 will only insert newlines. None is the most compact
representation.
If specified, separators should be an (item_separator, key_separator)


representation.
If specified, separators should be an (item_separator, key_separator)
tuple.  The default is (', ', ': ') if indent is None and
(',', ': ') otherwise.  To get the most compact JSON representation,
you should specify (',', ':') to eliminate whitespace.
default(obj) is a function that should return a serializable version
of obj or raise TypeError. The default simply raises TypeError.
If sort_keys is true (default: False), then the output of
dictionaries will be sorted by key.
To use a custom JSONEncoder subclass (e.g. one that overrides the
.default() method to serialize additional types), specify it with
the cls kwarg; otherwise JSONEncoder is used.
json_loads(*, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)¶
Deserialize s (a str, bytes or bytearray instance
containing a JSON document) to a Python object.
object_hook is an optional function that will be called with the
result of any object literal decode (a dict). The return value of
object_hook will be used instead of the dict. This feature
can be used to implement custom decoders (e.g. JSON-RPC class hinting).
object_pairs_hook is an optional function that will be called with the
result of any object literal decoded with an ordered list of pairs.  The
return value of object_pairs_hook will be used instead of the dict.
This feature can be used to implement custom decoders.  If object_hook
is also defined, the object_pairs_hook takes priority.
parse_float, if specified, will be called with the string
of every JSON float to be decoded. By default this is equivalent to
float(num_str). This can be used to use another datatype or parser
for JSON floats (e.g. decimal.Decimal).


for JSON floats (e.g. decimal.Decimal).
parse_int, if specified, will be called with the string
of every JSON int to be decoded. By default this is equivalent to
int(num_str). This can be used to use another datatype or parser
for JSON integers (e.g. float).
parse_constant, if specified, will be called with one of the
following strings: -Infinity, Infinity, NaN.
This can be used to raise an exception if invalid JSON numbers
are encountered.
To use a custom JSONDecoder subclass, specify it with the cls
kwarg; otherwise JSONDecoder is used.
classmethod parse_env_var(field_name: unicode, raw_val: unicode) → Any¶
classmethod prepare_field(field: ModelField) → None¶
Optional hook to check or modify fields during model creation.
alias_generator = None¶
allow_inf_nan = True¶
allow_mutation = True¶
allow_population_by_field_name = False¶
anystr_lower = False¶
anystr_strip_whitespace = False¶
anystr_upper = False¶
arbitrary_types_allowed = True¶
case_sensitive = False¶
copy_on_model_validation = 'shallow'¶
env_file = None¶
env_file_encoding = None¶
env_nested_delimiter = None¶
env_prefix = ''¶
error_msg_templates = {}¶
extra = 'forbid'¶
fields = {}¶
frozen = False¶
json_encoders = {}¶
keep_untouched = ()¶
max_anystr_length = None¶
min_anystr_length = 0¶
orm_mode = False¶
post_init_call = 'before_validation'¶
schema_extra = {}¶
secrets_dir = None¶
smart_union = False¶
title = None¶
underscore_attrs_are_private = False¶
use_enum_values = False¶
validate_all = True¶
validate_assignment = False¶


langchain.output_parsers.boolean.BooleanOutputParser¶
class langchain.output_parsers.boolean.BooleanOutputParser(*, true_val: str = 'YES', false_val: str = 'NO')[source]¶
Bases: BaseOutputParser[bool]
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param false_val: str = 'NO'¶
param true_val: str = 'YES'¶
dict(**kwargs: Any) → Dict¶
Return dictionary representation of output parser.
get_format_instructions() → str¶
Instructions on how the LLM output should be formatted.
parse(text: str) → bool[source]¶
Parse the output of an LLM call to a boolean.
Parameters
text – output of language model
Returns
boolean
parse_result(result: List[Generation]) → T¶
Parse LLM Result.
parse_with_prompt(completion: str, prompt: PromptValue) → Any¶
Optional method to parse the output of an LLM call with a prompt.
The prompt is largely provided in the event the OutputParser wants
to retry or fix the output in some way, and needs information from
the prompt to do so.
Parameters
completion – output of language model
prompt – prompt value
Returns
structured output
to_json() → Union[SerializedConstructor, SerializedNotImplemented]¶
to_json_not_implemented() → SerializedNotImplemented¶
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]¶


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.
model Config¶
Bases: object
extra = 'ignore'¶


langchain.output_parsers.fix.OutputFixingParser¶
class langchain.output_parsers.fix.OutputFixingParser(*, parser: BaseOutputParser[T], retry_chain: LLMChain)[source]¶
Bases: BaseOutputParser[T]
Wraps a parser and tries to fix parsing errors.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param parser: langchain.schema.BaseOutputParser[langchain.output_parsers.fix.T] [Required]¶
param retry_chain: langchain.chains.llm.LLMChain [Required]¶
dict(**kwargs: Any) → Dict¶
Return dictionary representation of output parser.
classmethod from_llm(llm: BaseLanguageModel, parser: BaseOutputParser[T], prompt: BasePromptTemplate = PromptTemplate(input_variables=['completion', 'error', 'instructions'], output_parser=None, partial_variables={}, template='Instructions:\n--------------\n{instructions}\n--------------\nCompletion:\n--------------\n{completion}\n--------------\n\nAbove, the Completion did not satisfy the constraints given in the Instructions.\nError:\n--------------\n{error}\n--------------\n\nPlease try again. Please only respond with an answer that satisfies the constraints laid out in the Instructions:', template_format='f-string', validate_template=True)) → OutputFixingParser[T][source]¶
get_format_instructions() → str[source]¶
Instructions on how the LLM output should be formatted.
parse(completion: str) → T[source]¶
Parse the output of an LLM call.
A method which takes in a string (assumed output of a language model )
and parses it into some structure.
Parameters
text – output of language model
Returns
structured output
parse_result(result: List[Generation]) → T¶
Parse LLM Result.


parse_result(result: List[Generation]) → T¶
Parse LLM Result.
parse_with_prompt(completion: str, prompt: PromptValue) → Any¶
Optional method to parse the output of an LLM call with a prompt.
The prompt is largely provided in the event the OutputParser wants
to retry or fix the output in some way, and needs information from
the prompt to do so.
Parameters
completion – output of language model
prompt – prompt value
Returns
structured output
to_json() → Union[SerializedConstructor, SerializedNotImplemented]¶
to_json_not_implemented() → SerializedNotImplemented¶
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.
model Config¶
Bases: object
extra = 'ignore'¶


langchain.output_parsers.list.CommaSeparatedListOutputParser¶
class langchain.output_parsers.list.CommaSeparatedListOutputParser[source]¶
Bases: ListOutputParser
Parse out comma separated lists.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
dict(**kwargs: Any) → Dict¶
Return dictionary representation of output parser.
get_format_instructions() → str[source]¶
Instructions on how the LLM output should be formatted.
parse(text: str) → List[str][source]¶
Parse the output of an LLM call.
parse_result(result: List[Generation]) → T¶
Parse LLM Result.
parse_with_prompt(completion: str, prompt: PromptValue) → Any¶
Optional method to parse the output of an LLM call with a prompt.
The prompt is largely provided in the event the OutputParser wants
to retry or fix the output in some way, and needs information from
the prompt to do so.
Parameters
completion – output of language model
prompt – prompt value
Returns
structured output
to_json() → Union[SerializedConstructor, SerializedNotImplemented]¶
to_json_not_implemented() → SerializedNotImplemented¶
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.