id
stringlengths 14
16
| text
stringlengths 31
2.41k
| source
stringlengths 53
121
|
---|---|---|
06ea1ea7a2ba-20 | Parameters
query (str) β
Return type
Dict[int, Tuple[langchain.schema.Document, float]]
class langchain.retrievers.VespaRetriever(app, body, content_field, metadata_fields=None)[source]ο
Bases: langchain.schema.BaseRetriever
Retriever that uses the Vespa.
Parameters
app (Vespa) β
body (Dict) β
content_field (str) β
metadata_fields (Optional[Sequence[str]]) β
get_relevant_documents(query)[source]ο
Get documents relevant for a query.
Parameters
query (str) β string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
async aget_relevant_documents(query)[source]ο
Get documents relevant for a query.
Parameters
query (str) β string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
get_relevant_documents_with_filter(query, *, _filter=None)[source]ο
Parameters
query (str) β
_filter (Optional[str]) β
Return type
List[langchain.schema.Document]
classmethod from_params(url, content_field, *, k=None, metadata_fields=(), sources=None, _filter=None, yql=None, **kwargs)[source]ο
Instantiate retriever from params.
Parameters
url (str) β Vespa app URL.
content_field (str) β Field in results to return as Document page_content.
k (Optional[int]) β Number of Documents to return. Defaults to None.
metadata_fields (Sequence[str] or "*") β Fields in results to include in
document metadata. Defaults to empty tuple ().
sources (Sequence[str] or "*" or None) β Sources to retrieve
from. Defaults to None. | https://api.python.langchain.com/en/latest/modules/retrievers.html |
06ea1ea7a2ba-21 | from. Defaults to None.
_filter (Optional[str]) β Document filter condition expressed in YQL.
Defaults to None.
yql (Optional[str]) β Full YQL query to be used. Should not be specified
if _filter or sources are specified. Defaults to None.
kwargs (Any) β Keyword arguments added to query body.
Return type
langchain.retrievers.vespa_retriever.VespaRetriever
class langchain.retrievers.WeaviateHybridSearchRetriever(client, index_name, text_key, alpha=0.5, k=4, attributes=None, create_schema_if_missing=True)[source]ο
Bases: langchain.schema.BaseRetriever
Parameters
client (Any) β
index_name (str) β
text_key (str) β
alpha (float) β
k (int) β
attributes (Optional[List[str]]) β
create_schema_if_missing (bool) β
class Config[source]ο
Bases: object
Configuration for this pydantic object.
extra = 'forbid'ο
arbitrary_types_allowed = Trueο
add_documents(docs, **kwargs)[source]ο
Upload documents to Weaviate.
Parameters
docs (List[langchain.schema.Document]) β
kwargs (Any) β
Return type
List[str]
get_relevant_documents(query, where_filter=None)[source]ο
Look up similar documents in Weaviate.
Parameters
query (str) β
where_filter (Optional[Dict[str, object]]) β
Return type
List[langchain.schema.Document]
async aget_relevant_documents(query, where_filter=None)[source]ο
Get documents relevant for a query.
Parameters
query (str) β string to find relevant documents for | https://api.python.langchain.com/en/latest/modules/retrievers.html |
06ea1ea7a2ba-22 | Parameters
query (str) β string to find relevant documents for
where_filter (Optional[Dict[str, object]]) β
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
class langchain.retrievers.WikipediaRetriever(*, wiki_client=None, top_k_results=3, lang='en', load_all_available_meta=False, doc_content_chars_max=4000)[source]ο
Bases: langchain.schema.BaseRetriever, langchain.utilities.wikipedia.WikipediaAPIWrapper
It is effectively a wrapper for WikipediaAPIWrapper.
It wraps load() to get_relevant_documents().
It uses all WikipediaAPIWrapper arguments without any change.
Parameters
wiki_client (Any) β
top_k_results (int) β
lang (str) β
load_all_available_meta (bool) β
doc_content_chars_max (int) β
Return type
None
async aget_relevant_documents(query)[source]ο
Get documents relevant for a query.
Parameters
query (str) β string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
get_relevant_documents(query)[source]ο
Get documents relevant for a query.
Parameters
query (str) β string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
class langchain.retrievers.ZepRetriever(session_id, url, top_k=None)[source]ο
Bases: langchain.schema.BaseRetriever
A Retriever implementation for the Zep long-term memory store. Search your
userβs long-term chat history with Zep.
Note: You will need to provide the userβs session_id to use this retriever.
More on Zep: | https://api.python.langchain.com/en/latest/modules/retrievers.html |
06ea1ea7a2ba-23 | More on Zep:
Zep provides long-term conversation storage for LLM apps. The server stores,
summarizes, embeds, indexes, and enriches conversational AI chat
histories, and exposes them via simple, low-latency APIs.
For server installation instructions, see:
https://getzep.github.io/deployment/quickstart/
Parameters
session_id (str) β
url (str) β
top_k (Optional[int]) β
get_relevant_documents(query, metadata=None)[source]ο
Get documents relevant for a query.
Parameters
query (str) β string to find relevant documents for
metadata (Optional[Dict]) β
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
async aget_relevant_documents(query, metadata=None)[source]ο
Get documents relevant for a query.
Parameters
query (str) β string to find relevant documents for
metadata (Optional[Dict]) β
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
class langchain.retrievers.ZillizRetriever(embedding_function, collection_name='LangChainCollection', connection_args=None, consistency_level='Session', search_params=None)[source]ο
Bases: langchain.schema.BaseRetriever
Retriever that uses the Zilliz API.
Parameters
embedding_function (langchain.embeddings.base.Embeddings) β
collection_name (str) β
connection_args (Optional[Dict[str, Any]]) β
consistency_level (str) β
search_params (Optional[dict]) β
add_texts(texts, metadatas=None)[source]ο
Add text to the Zilliz store
Parameters
texts (List[str]) β The text | https://api.python.langchain.com/en/latest/modules/retrievers.html |
06ea1ea7a2ba-24 | Add text to the Zilliz store
Parameters
texts (List[str]) β The text
metadatas (List[dict]) β Metadata dicts, must line up with existing store
Return type
None
get_relevant_documents(query)[source]ο
Get documents relevant for a query.
Parameters
query (str) β string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
async aget_relevant_documents(query)[source]ο
Get documents relevant for a query.
Parameters
query (str) β string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
class langchain.retrievers.DocArrayRetriever(*, index=None, embeddings, search_field, content_field, search_type=SearchType.similarity, top_k=1, filters=None)[source]ο
Bases: langchain.schema.BaseRetriever, pydantic.main.BaseModel
Retriever class for DocArray Document Indices.
Currently, supports 5 backends:
InMemoryExactNNIndex, HnswDocumentIndex, QdrantDocumentIndex,
ElasticDocIndex, and WeaviateDocumentIndex.
Parameters
index (Any) β
embeddings (langchain.embeddings.base.Embeddings) β
search_field (str) β
content_field (str) β
search_type (langchain.retrievers.docarray.SearchType) β
top_k (int) β
filters (Optional[Any]) β
Return type
None
indexο
One of the above-mentioned index instances
embeddingsο
Embedding model to represent text as vectors
search_fieldο
Field to consider for searching in the documents.
Should be an embedding/vector/tensor.
content_fieldο | https://api.python.langchain.com/en/latest/modules/retrievers.html |
06ea1ea7a2ba-25 | Should be an embedding/vector/tensor.
content_fieldο
Field that represents the main content in your document schema.
Will be used as a page_content. Everything else will go into metadata.
search_typeο
Type of search to perform (similarity / mmr)
filtersο
Filters applied for document retrieval.
top_kο
Number of documents to return
attribute content_field: str [Required]ο
attribute embeddings: langchain.embeddings.base.Embeddings [Required]ο
attribute filters: Optional[Any] = Noneο
attribute index: Any = Noneο
attribute search_field: str [Required]ο
attribute search_type: langchain.retrievers.docarray.SearchType = SearchType.similarityο
attribute top_k: int = 1ο
async aget_relevant_documents(query)[source]ο
Get documents relevant for a query.
Parameters
query (str) β string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
get_relevant_documents(query)[source]ο
Get documents relevant for a query.
Parameters
query (str) β string to find relevant documents for
Returns
List of relevant documents
Return type
List[langchain.schema.Document]
Document compressorsο
class langchain.retrievers.document_compressors.DocumentCompressorPipeline(*, transformers)[source]ο
Bases: langchain.retrievers.document_compressors.base.BaseDocumentCompressor
Document compressor that uses a pipeline of transformers.
Parameters
transformers (List[Union[langchain.schema.BaseDocumentTransformer, langchain.retrievers.document_compressors.base.BaseDocumentCompressor]]) β
Return type
None | https://api.python.langchain.com/en/latest/modules/retrievers.html |
06ea1ea7a2ba-26 | Return type
None
attribute transformers: List[Union[langchain.schema.BaseDocumentTransformer, langchain.retrievers.document_compressors.base.BaseDocumentCompressor]] [Required]ο
List of document filters that are chained together and run in sequence.
async acompress_documents(documents, query)[source]ο
Compress retrieved documents given the query context.
Parameters
documents (Sequence[langchain.schema.Document]) β
query (str) β
Return type
Sequence[langchain.schema.Document]
compress_documents(documents, query)[source]ο
Transform a list of documents.
Parameters
documents (Sequence[langchain.schema.Document]) β
query (str) β
Return type
Sequence[langchain.schema.Document]
class langchain.retrievers.document_compressors.EmbeddingsFilter(*, embeddings, similarity_fn=<function cosine_similarity>, k=20, similarity_threshold=None)[source]ο
Bases: langchain.retrievers.document_compressors.base.BaseDocumentCompressor
Parameters
embeddings (langchain.embeddings.base.Embeddings) β
similarity_fn (Callable) β
k (Optional[int]) β
similarity_threshold (Optional[float]) β
Return type
None
attribute embeddings: langchain.embeddings.base.Embeddings [Required]ο
Embeddings to use for embedding document contents and queries.
attribute k: Optional[int] = 20ο
The number of relevant documents to return. Can be set to None, in which case
similarity_threshold must be specified. Defaults to 20.
attribute similarity_fn: Callable = <function cosine_similarity>ο
Similarity function for comparing documents. Function expected to take as input
two matrices (List[List[float]]) and return a matrix of scores where higher values
indicate greater similarity.
attribute similarity_threshold: Optional[float] = Noneο | https://api.python.langchain.com/en/latest/modules/retrievers.html |
06ea1ea7a2ba-27 | indicate greater similarity.
attribute similarity_threshold: Optional[float] = Noneο
Threshold for determining when two documents are similar enough
to be considered redundant. Defaults to None, must be specified if k is set
to None.
async acompress_documents(documents, query)[source]ο
Filter down documents.
Parameters
documents (Sequence[langchain.schema.Document]) β
query (str) β
Return type
Sequence[langchain.schema.Document]
compress_documents(documents, query)[source]ο
Filter documents based on similarity of their embeddings to the query.
Parameters
documents (Sequence[langchain.schema.Document]) β
query (str) β
Return type
Sequence[langchain.schema.Document]
class langchain.retrievers.document_compressors.LLMChainExtractor(*, llm_chain, get_input=<function default_get_input>)[source]ο
Bases: langchain.retrievers.document_compressors.base.BaseDocumentCompressor
Parameters
llm_chain (langchain.chains.llm.LLMChain) β
get_input (Callable[[str, langchain.schema.Document], dict]) β
Return type
None
attribute get_input: Callable[[str, langchain.schema.Document], dict] = <function default_get_input>ο
Callable for constructing the chain input from the query and a Document.
attribute llm_chain: langchain.chains.llm.LLMChain [Required]ο
LLM wrapper to use for compressing documents.
async acompress_documents(documents, query)[source]ο
Compress page content of raw documents asynchronously.
Parameters
documents (Sequence[langchain.schema.Document]) β
query (str) β
Return type
Sequence[langchain.schema.Document]
compress_documents(documents, query)[source]ο
Compress page content of raw documents.
Parameters | https://api.python.langchain.com/en/latest/modules/retrievers.html |
06ea1ea7a2ba-28 | Compress page content of raw documents.
Parameters
documents (Sequence[langchain.schema.Document]) β
query (str) β
Return type
Sequence[langchain.schema.Document]
classmethod from_llm(llm, prompt=None, get_input=None, llm_chain_kwargs=None)[source]ο
Initialize from LLM.
Parameters
llm (langchain.base_language.BaseLanguageModel) β
prompt (Optional[langchain.prompts.prompt.PromptTemplate]) β
get_input (Optional[Callable[[str, langchain.schema.Document], str]]) β
llm_chain_kwargs (Optional[dict]) β
Return type
langchain.retrievers.document_compressors.chain_extract.LLMChainExtractor
class langchain.retrievers.document_compressors.LLMChainFilter(*, llm_chain, get_input=<function default_get_input>)[source]ο
Bases: langchain.retrievers.document_compressors.base.BaseDocumentCompressor
Filter that drops documents that arenβt relevant to the query.
Parameters
llm_chain (langchain.chains.llm.LLMChain) β
get_input (Callable[[str, langchain.schema.Document], dict]) β
Return type
None
attribute get_input: Callable[[str, langchain.schema.Document], dict] = <function default_get_input>ο
Callable for constructing the chain input from the query and a Document.
attribute llm_chain: langchain.chains.llm.LLMChain [Required]ο
LLM wrapper to use for filtering documents.
The chain prompt is expected to have a BooleanOutputParser.
async acompress_documents(documents, query)[source]ο
Filter down documents.
Parameters
documents (Sequence[langchain.schema.Document]) β
query (str) β
Return type
Sequence[langchain.schema.Document] | https://api.python.langchain.com/en/latest/modules/retrievers.html |
06ea1ea7a2ba-29 | query (str) β
Return type
Sequence[langchain.schema.Document]
compress_documents(documents, query)[source]ο
Filter down documents based on their relevance to the query.
Parameters
documents (Sequence[langchain.schema.Document]) β
query (str) β
Return type
Sequence[langchain.schema.Document]
classmethod from_llm(llm, prompt=None, **kwargs)[source]ο
Parameters
llm (langchain.base_language.BaseLanguageModel) β
prompt (Optional[langchain.prompts.base.BasePromptTemplate]) β
kwargs (Any) β
Return type
langchain.retrievers.document_compressors.chain_filter.LLMChainFilter
class langchain.retrievers.document_compressors.CohereRerank(*, client, top_n=3, model='rerank-english-v2.0')[source]ο
Bases: langchain.retrievers.document_compressors.base.BaseDocumentCompressor
Parameters
client (Client) β
top_n (int) β
model (str) β
Return type
None
attribute client: Client [Required]ο
attribute model: str = 'rerank-english-v2.0'ο
attribute top_n: int = 3ο
async acompress_documents(documents, query)[source]ο
Compress retrieved documents given the query context.
Parameters
documents (Sequence[langchain.schema.Document]) β
query (str) β
Return type
Sequence[langchain.schema.Document]
compress_documents(documents, query)[source]ο
Compress retrieved documents given the query context.
Parameters
documents (Sequence[langchain.schema.Document]) β
query (str) β
Return type
Sequence[langchain.schema.Document] | https://api.python.langchain.com/en/latest/modules/retrievers.html |
d97158bcb296-0 | Example Selectorο
Logic for selecting examples to include in prompts.
class langchain.prompts.example_selector.LengthBasedExampleSelector(*, examples, example_prompt, get_text_length=<function _get_length_based>, max_length=2048, example_text_lengths=[])[source]ο
Bases: langchain.prompts.example_selector.base.BaseExampleSelector, pydantic.main.BaseModel
Select examples based on length.
Parameters
examples (List[dict]) β
example_prompt (langchain.prompts.prompt.PromptTemplate) β
get_text_length (Callable[[str], int]) β
max_length (int) β
example_text_lengths (List[int]) β
Return type
None
attribute example_prompt: langchain.prompts.prompt.PromptTemplate [Required]ο
Prompt template used to format the examples.
attribute examples: List[dict] [Required]ο
A list of the examples that the prompt template expects.
attribute get_text_length: Callable[[str], int] = <function _get_length_based>ο
Function to measure prompt length. Defaults to word count.
attribute max_length: int = 2048ο
Max length for the prompt, beyond which examples are cut.
add_example(example)[source]ο
Add new example to list.
Parameters
example (Dict[str, str]) β
Return type
None
select_examples(input_variables)[source]ο
Select which examples to use based on the input lengths.
Parameters
input_variables (Dict[str, str]) β
Return type
List[dict]
class langchain.prompts.example_selector.MaxMarginalRelevanceExampleSelector(*, vectorstore, k=4, example_keys=None, input_keys=None, fetch_k=20)[source]ο
Bases: langchain.prompts.example_selector.semantic_similarity.SemanticSimilarityExampleSelector | https://api.python.langchain.com/en/latest/modules/example_selector.html |
d97158bcb296-1 | Bases: langchain.prompts.example_selector.semantic_similarity.SemanticSimilarityExampleSelector
ExampleSelector that selects examples based on Max Marginal Relevance.
This was shown to improve performance in this paper:
https://arxiv.org/pdf/2211.13892.pdf
Parameters
vectorstore (langchain.vectorstores.base.VectorStore) β
k (int) β
example_keys (Optional[List[str]]) β
input_keys (Optional[List[str]]) β
fetch_k (int) β
Return type
None
attribute fetch_k: int = 20ο
Number of examples to fetch to rerank.
classmethod from_examples(examples, embeddings, vectorstore_cls, k=4, input_keys=None, fetch_k=20, **vectorstore_cls_kwargs)[source]ο
Create k-shot example selector using example list and embeddings.
Reshuffles examples dynamically based on query similarity.
Parameters
examples (List[dict]) β List of examples to use in the prompt.
embeddings (langchain.embeddings.base.Embeddings) β An iniialized embedding API interface, e.g. OpenAIEmbeddings().
vectorstore_cls (Type[langchain.vectorstores.base.VectorStore]) β A vector store DB interface class, e.g. FAISS.
k (int) β Number of examples to select
input_keys (Optional[List[str]]) β If provided, the search is based on the input variables
instead of all variables.
vectorstore_cls_kwargs (Any) β optional kwargs containing url for vector store
fetch_k (int) β
Returns
The ExampleSelector instantiated, backed by a vector store.
Return type
langchain.prompts.example_selector.semantic_similarity.MaxMarginalRelevanceExampleSelector
select_examples(input_variables)[source]ο
Select which examples to use based on semantic similarity.
Parameters
input_variables (Dict[str, str]) β | https://api.python.langchain.com/en/latest/modules/example_selector.html |
d97158bcb296-2 | Parameters
input_variables (Dict[str, str]) β
Return type
List[dict]
class langchain.prompts.example_selector.NGramOverlapExampleSelector(*, examples, example_prompt, threshold=- 1.0)[source]ο
Bases: langchain.prompts.example_selector.base.BaseExampleSelector, pydantic.main.BaseModel
Select and order examples based on ngram overlap score (sentence_bleu score).
https://www.nltk.org/_modules/nltk/translate/bleu_score.html
https://aclanthology.org/P02-1040.pdf
Parameters
examples (List[dict]) β
example_prompt (langchain.prompts.prompt.PromptTemplate) β
threshold (float) β
Return type
None
attribute example_prompt: langchain.prompts.prompt.PromptTemplate [Required]ο
Prompt template used to format the examples.
attribute examples: List[dict] [Required]ο
A list of the examples that the prompt template expects.
attribute threshold: float = -1.0ο
Threshold at which algorithm stops. Set to -1.0 by default.
For negative threshold:
select_examples sorts examples by ngram_overlap_score, but excludes none.
For threshold greater than 1.0:
select_examples excludes all examples, and returns an empty list.
For threshold equal to 0.0:
select_examples sorts examples by ngram_overlap_score,
and excludes examples with no ngram overlap with input.
add_example(example)[source]ο
Add new example to list.
Parameters
example (Dict[str, str]) β
Return type
None
select_examples(input_variables)[source]ο
Return list of examples sorted by ngram_overlap_score with input.
Descending order.
Excludes any examples with ngram_overlap_score less than or equal to threshold.
Parameters | https://api.python.langchain.com/en/latest/modules/example_selector.html |
d97158bcb296-3 | Excludes any examples with ngram_overlap_score less than or equal to threshold.
Parameters
input_variables (Dict[str, str]) β
Return type
List[dict]
class langchain.prompts.example_selector.SemanticSimilarityExampleSelector(*, vectorstore, k=4, example_keys=None, input_keys=None)[source]ο
Bases: langchain.prompts.example_selector.base.BaseExampleSelector, pydantic.main.BaseModel
Example selector that selects examples based on SemanticSimilarity.
Parameters
vectorstore (langchain.vectorstores.base.VectorStore) β
k (int) β
example_keys (Optional[List[str]]) β
input_keys (Optional[List[str]]) β
Return type
None
attribute example_keys: Optional[List[str]] = Noneο
Optional keys to filter examples to.
attribute input_keys: Optional[List[str]] = Noneο
Optional keys to filter input to. If provided, the search is based on
the input variables instead of all variables.
attribute k: int = 4ο
Number of examples to select.
attribute vectorstore: langchain.vectorstores.base.VectorStore [Required]ο
VectorStore than contains information about examples.
add_example(example)[source]ο
Add new example to vectorstore.
Parameters
example (Dict[str, str]) β
Return type
str
classmethod from_examples(examples, embeddings, vectorstore_cls, k=4, input_keys=None, **vectorstore_cls_kwargs)[source]ο
Create k-shot example selector using example list and embeddings.
Reshuffles examples dynamically based on query similarity.
Parameters
examples (List[dict]) β List of examples to use in the prompt.
embeddings (langchain.embeddings.base.Embeddings) β An initialized embedding API interface, e.g. OpenAIEmbeddings(). | https://api.python.langchain.com/en/latest/modules/example_selector.html |
d97158bcb296-4 | vectorstore_cls (Type[langchain.vectorstores.base.VectorStore]) β A vector store DB interface class, e.g. FAISS.
k (int) β Number of examples to select
input_keys (Optional[List[str]]) β If provided, the search is based on the input variables
instead of all variables.
vectorstore_cls_kwargs (Any) β optional kwargs containing url for vector store
Returns
The ExampleSelector instantiated, backed by a vector store.
Return type
langchain.prompts.example_selector.semantic_similarity.SemanticSimilarityExampleSelector
select_examples(input_variables)[source]ο
Select which examples to use based on semantic similarity.
Parameters
input_variables (Dict[str, str]) β
Return type
List[dict] | https://api.python.langchain.com/en/latest/modules/example_selector.html |
18d09815d48a-0 | Callbacksο
Callback handlers that allow listening to events in LangChain.
class langchain.callbacks.AimCallbackHandler(repo=None, experiment_name=None, system_tracking_interval=10, log_system_params=True)[source]ο
Bases: langchain.callbacks.aim_callback.BaseMetadataCallbackHandler, langchain.callbacks.base.BaseCallbackHandler
Callback Handler that logs to Aim.
Parameters
repo (str, optional) β Aim repository path or Repo object to which
Run object is bound. If skipped, default Repo is used.
experiment_name (str, optional) β Sets Runβs experiment property.
βdefaultβ if not specified. Can be used later to query runs/sequences.
system_tracking_interval (int, optional) β Sets the tracking interval
in seconds for system usage metrics (CPU, Memory, etc.). Set to None
to disable system metrics tracking.
log_system_params (bool, optional) β Enable/Disable logging of system
params such as installed packages, git info, environment variables, etc.
Return type
None
This handler will utilize the associated callback method called and formats
the input of each callback function with metadata regarding the state of LLM run
and then logs the response to Aim.
setup(**kwargs)[source]ο
Parameters
kwargs (Any) β
Return type
None
on_llm_start(serialized, prompts, **kwargs)[source]ο
Run when LLM starts.
Parameters
serialized (Dict[str, Any]) β
prompts (List[str]) β
kwargs (Any) β
Return type
None
on_llm_end(response, **kwargs)[source]ο
Run when LLM ends running.
Parameters
response (langchain.schema.LLMResult) β
kwargs (Any) β
Return type
None
on_llm_new_token(token, **kwargs)[source]ο | https://api.python.langchain.com/en/latest/modules/callbacks.html |
18d09815d48a-1 | Return type
None
on_llm_new_token(token, **kwargs)[source]ο
Run when LLM generates a new token.
Parameters
token (str) β
kwargs (Any) β
Return type
None
on_llm_error(error, **kwargs)[source]ο
Run when LLM errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) β
kwargs (Any) β
Return type
None
on_chain_start(serialized, inputs, **kwargs)[source]ο
Run when chain starts running.
Parameters
serialized (Dict[str, Any]) β
inputs (Dict[str, Any]) β
kwargs (Any) β
Return type
None
on_chain_end(outputs, **kwargs)[source]ο
Run when chain ends running.
Parameters
outputs (Dict[str, Any]) β
kwargs (Any) β
Return type
None
on_chain_error(error, **kwargs)[source]ο
Run when chain errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) β
kwargs (Any) β
Return type
None
on_tool_start(serialized, input_str, **kwargs)[source]ο
Run when tool starts running.
Parameters
serialized (Dict[str, Any]) β
input_str (str) β
kwargs (Any) β
Return type
None
on_tool_end(output, **kwargs)[source]ο
Run when tool ends running.
Parameters
output (str) β
kwargs (Any) β
Return type
None
on_tool_error(error, **kwargs)[source]ο
Run when tool errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) β
kwargs (Any) β
Return type
None
on_text(text, **kwargs)[source]ο | https://api.python.langchain.com/en/latest/modules/callbacks.html |
18d09815d48a-2 | Return type
None
on_text(text, **kwargs)[source]ο
Run when agent is ending.
Parameters
text (str) β
kwargs (Any) β
Return type
None
on_agent_finish(finish, **kwargs)[source]ο
Run when agent ends running.
Parameters
finish (langchain.schema.AgentFinish) β
kwargs (Any) β
Return type
None
on_agent_action(action, **kwargs)[source]ο
Run on agent action.
Parameters
action (langchain.schema.AgentAction) β
kwargs (Any) β
Return type
Any
flush_tracker(repo=None, experiment_name=None, system_tracking_interval=10, log_system_params=True, langchain_asset=None, reset=True, finish=False)[source]ο
Flush the tracker and reset the session.
Parameters
repo (str, optional) β Aim repository path or Repo object to which
Run object is bound. If skipped, default Repo is used.
experiment_name (str, optional) β Sets Runβs experiment property.
βdefaultβ if not specified. Can be used later to query runs/sequences.
system_tracking_interval (int, optional) β Sets the tracking interval
in seconds for system usage metrics (CPU, Memory, etc.). Set to None
to disable system metrics tracking.
log_system_params (bool, optional) β Enable/Disable logging of system
params such as installed packages, git info, environment variables, etc.
langchain_asset (Any) β The langchain asset to save.
reset (bool) β Whether to reset the session.
finish (bool) β Whether to finish the run.
Returns β None
Return type
None
class langchain.callbacks.ArgillaCallbackHandler(dataset_name, workspace_name=None, api_url=None, api_key=None)[source]ο | https://api.python.langchain.com/en/latest/modules/callbacks.html |
18d09815d48a-3 | Bases: langchain.callbacks.base.BaseCallbackHandler
Callback Handler that logs into Argilla.
Parameters
dataset_name (str) β name of the FeedbackDataset in Argilla. Note that it must
exist in advance. If you need help on how to create a FeedbackDataset in
Argilla, please visit
https://docs.argilla.io/en/latest/guides/llms/practical_guides/use_argilla_callback_in_langchain.html.
workspace_name (Optional[str]) β name of the workspace in Argilla where the specified
FeedbackDataset lives in. Defaults to None, which means that the
default workspace will be used.
api_url (Optional[str]) β URL of the Argilla Server that we want to use, and where the
FeedbackDataset lives in. Defaults to None, which means that either
ARGILLA_API_URL environment variable or the default http://localhost:6900
will be used.
api_key (Optional[str]) β API Key to connect to the Argilla Server. Defaults to None, which
means that either ARGILLA_API_KEY environment variable or the default
argilla.apikey will be used.
Raises
ImportError β if the argilla package is not installed.
ConnectionError β if the connection to Argilla fails.
FileNotFoundError β if the FeedbackDataset retrieval from Argilla fails.
Return type
None
Examples
>>> from langchain.llms import OpenAI
>>> from langchain.callbacks import ArgillaCallbackHandler
>>> argilla_callback = ArgillaCallbackHandler(
... dataset_name="my-dataset",
... workspace_name="my-workspace",
... api_url="http://localhost:6900",
... api_key="argilla.apikey",
... )
>>> llm = OpenAI(
... temperature=0,
... callbacks=[argilla_callback],
... verbose=True, | https://api.python.langchain.com/en/latest/modules/callbacks.html |
18d09815d48a-4 | ... callbacks=[argilla_callback],
... verbose=True,
... openai_api_key="API_KEY_HERE",
... )
>>> llm.generate([
... "What is the best NLP-annotation tool out there? (no bias at all)",
... ])
"Argilla, no doubt about it."
on_llm_start(serialized, prompts, **kwargs)[source]ο
Save the prompts in memory when an LLM starts.
Parameters
serialized (Dict[str, Any]) β
prompts (List[str]) β
kwargs (Any) β
Return type
None
on_llm_new_token(token, **kwargs)[source]ο
Do nothing when a new token is generated.
Parameters
token (str) β
kwargs (Any) β
Return type
None
on_llm_end(response, **kwargs)[source]ο
Log records to Argilla when an LLM ends.
Parameters
response (langchain.schema.LLMResult) β
kwargs (Any) β
Return type
None
on_llm_error(error, **kwargs)[source]ο
Do nothing when LLM outputs an error.
Parameters
error (Union[Exception, KeyboardInterrupt]) β
kwargs (Any) β
Return type
None
on_chain_start(serialized, inputs, **kwargs)[source]ο
If the key input is in inputs, then save it in self.prompts using
either the parent_run_id or the run_id as the key. This is done so that
we donβt log the same input prompt twice, once when the LLM starts and once
when the chain starts.
Parameters
serialized (Dict[str, Any]) β
inputs (Dict[str, Any]) β
kwargs (Any) β
Return type
None | https://api.python.langchain.com/en/latest/modules/callbacks.html |
18d09815d48a-5 | kwargs (Any) β
Return type
None
on_chain_end(outputs, **kwargs)[source]ο
If either the parent_run_id or the run_id is in self.prompts, then
log the outputs to Argilla, and pop the run from self.prompts. The behavior
differs if the output is a list or not.
Parameters
outputs (Dict[str, Any]) β
kwargs (Any) β
Return type
None
on_chain_error(error, **kwargs)[source]ο
Do nothing when LLM chain outputs an error.
Parameters
error (Union[Exception, KeyboardInterrupt]) β
kwargs (Any) β
Return type
None
on_tool_start(serialized, input_str, **kwargs)[source]ο
Do nothing when tool starts.
Parameters
serialized (Dict[str, Any]) β
input_str (str) β
kwargs (Any) β
Return type
None
on_agent_action(action, **kwargs)[source]ο
Do nothing when agent takes a specific action.
Parameters
action (langchain.schema.AgentAction) β
kwargs (Any) β
Return type
Any
on_tool_end(output, observation_prefix=None, llm_prefix=None, **kwargs)[source]ο
Do nothing when tool ends.
Parameters
output (str) β
observation_prefix (Optional[str]) β
llm_prefix (Optional[str]) β
kwargs (Any) β
Return type
None
on_tool_error(error, **kwargs)[source]ο
Do nothing when tool outputs an error.
Parameters
error (Union[Exception, KeyboardInterrupt]) β
kwargs (Any) β
Return type
None
on_text(text, **kwargs)[source]ο
Do nothing
Parameters
text (str) β
kwargs (Any) β | https://api.python.langchain.com/en/latest/modules/callbacks.html |
18d09815d48a-6 | Do nothing
Parameters
text (str) β
kwargs (Any) β
Return type
None
on_agent_finish(finish, **kwargs)[source]ο
Do nothing
Parameters
finish (langchain.schema.AgentFinish) β
kwargs (Any) β
Return type
None
class langchain.callbacks.ArizeCallbackHandler(model_id=None, model_version=None, SPACE_KEY=None, API_KEY=None)[source]ο
Bases: langchain.callbacks.base.BaseCallbackHandler
Callback Handler that logs to Arize.
Parameters
model_id (Optional[str]) β
model_version (Optional[str]) β
SPACE_KEY (Optional[str]) β
API_KEY (Optional[str]) β
Return type
None
on_llm_start(serialized, prompts, **kwargs)[source]ο
Run when LLM starts running.
Parameters
serialized (Dict[str, Any]) β
prompts (List[str]) β
kwargs (Any) β
Return type
None
on_llm_new_token(token, **kwargs)[source]ο
Do nothing.
Parameters
token (str) β
kwargs (Any) β
Return type
None
on_llm_end(response, **kwargs)[source]ο
Run when LLM ends running.
Parameters
response (langchain.schema.LLMResult) β
kwargs (Any) β
Return type
None
on_llm_error(error, **kwargs)[source]ο
Do nothing.
Parameters
error (Union[Exception, KeyboardInterrupt]) β
kwargs (Any) β
Return type
None
on_chain_start(serialized, inputs, **kwargs)[source]ο
Run when chain starts running.
Parameters
serialized (Dict[str, Any]) β
inputs (Dict[str, Any]) β
kwargs (Any) β | https://api.python.langchain.com/en/latest/modules/callbacks.html |
18d09815d48a-7 | inputs (Dict[str, Any]) β
kwargs (Any) β
Return type
None
on_chain_end(outputs, **kwargs)[source]ο
Do nothing.
Parameters
outputs (Dict[str, Any]) β
kwargs (Any) β
Return type
None
on_chain_error(error, **kwargs)[source]ο
Do nothing.
Parameters
error (Union[Exception, KeyboardInterrupt]) β
kwargs (Any) β
Return type
None
on_tool_start(serialized, input_str, **kwargs)[source]ο
Run when tool starts running.
Parameters
serialized (Dict[str, Any]) β
input_str (str) β
kwargs (Any) β
Return type
None
on_agent_action(action, **kwargs)[source]ο
Do nothing.
Parameters
action (langchain.schema.AgentAction) β
kwargs (Any) β
Return type
Any
on_tool_end(output, observation_prefix=None, llm_prefix=None, **kwargs)[source]ο
Run when tool ends running.
Parameters
output (str) β
observation_prefix (Optional[str]) β
llm_prefix (Optional[str]) β
kwargs (Any) β
Return type
None
on_tool_error(error, **kwargs)[source]ο
Run when tool errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) β
kwargs (Any) β
Return type
None
on_text(text, **kwargs)[source]ο
Run on arbitrary text.
Parameters
text (str) β
kwargs (Any) β
Return type
None
on_agent_finish(finish, **kwargs)[source]ο
Run on agent end.
Parameters
finish (langchain.schema.AgentFinish) β
kwargs (Any) β
Return type
None | https://api.python.langchain.com/en/latest/modules/callbacks.html |
18d09815d48a-8 | kwargs (Any) β
Return type
None
class langchain.callbacks.AsyncIteratorCallbackHandler[source]ο
Bases: langchain.callbacks.base.AsyncCallbackHandler
Callback handler that returns an async iterator.
Return type
None
property always_verbose: boolο
queue: asyncio.queues.Queue[str]ο
done: asyncio.locks.Eventο
async on_llm_start(serialized, prompts, **kwargs)[source]ο
Run when LLM starts running.
Parameters
serialized (Dict[str, Any]) β
prompts (List[str]) β
kwargs (Any) β
Return type
None
async on_llm_new_token(token, **kwargs)[source]ο
Run on new LLM token. Only available when streaming is enabled.
Parameters
token (str) β
kwargs (Any) β
Return type
None
async on_llm_end(response, **kwargs)[source]ο
Run when LLM ends running.
Parameters
response (langchain.schema.LLMResult) β
kwargs (Any) β
Return type
None
async on_llm_error(error, **kwargs)[source]ο
Run when LLM errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) β
kwargs (Any) β
Return type
None
async aiter()[source]ο
Return type
AsyncIterator[str]
class langchain.callbacks.ClearMLCallbackHandler(task_type='inference', project_name='langchain_callback_demo', tags=None, task_name=None, visualize=False, complexity_metrics=False, stream_logs=False)[source]ο
Bases: langchain.callbacks.utils.BaseMetadataCallbackHandler, langchain.callbacks.base.BaseCallbackHandler
Callback Handler that logs to ClearML.
Parameters | https://api.python.langchain.com/en/latest/modules/callbacks.html |
18d09815d48a-9 | Callback Handler that logs to ClearML.
Parameters
job_type (str) β The type of clearml task such as βinferenceβ, βtestingβ or βqcβ
project_name (str) β The clearml project name
tags (list) β Tags to add to the task
task_name (str) β Name of the clearml task
visualize (bool) β Whether to visualize the run.
complexity_metrics (bool) β Whether to log complexity metrics
stream_logs (bool) β Whether to stream callback actions to ClearML
task_type (Optional[str]) β
Return type
None
This handler will utilize the associated callback method and formats
the input of each callback function with metadata regarding the state of LLM run,
and adds the response to the list of records for both the {method}_records and
action. It then logs the response to the ClearML console.
on_llm_start(serialized, prompts, **kwargs)[source]ο
Run when LLM starts.
Parameters
serialized (Dict[str, Any]) β
prompts (List[str]) β
kwargs (Any) β
Return type
None
on_llm_new_token(token, **kwargs)[source]ο
Run when LLM generates a new token.
Parameters
token (str) β
kwargs (Any) β
Return type
None
on_llm_end(response, **kwargs)[source]ο
Run when LLM ends running.
Parameters
response (langchain.schema.LLMResult) β
kwargs (Any) β
Return type
None
on_llm_error(error, **kwargs)[source]ο
Run when LLM errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) β
kwargs (Any) β
Return type
None | https://api.python.langchain.com/en/latest/modules/callbacks.html |
18d09815d48a-10 | kwargs (Any) β
Return type
None
on_chain_start(serialized, inputs, **kwargs)[source]ο
Run when chain starts running.
Parameters
serialized (Dict[str, Any]) β
inputs (Dict[str, Any]) β
kwargs (Any) β
Return type
None
on_chain_end(outputs, **kwargs)[source]ο
Run when chain ends running.
Parameters
outputs (Dict[str, Any]) β
kwargs (Any) β
Return type
None
on_chain_error(error, **kwargs)[source]ο
Run when chain errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) β
kwargs (Any) β
Return type
None
on_tool_start(serialized, input_str, **kwargs)[source]ο
Run when tool starts running.
Parameters
serialized (Dict[str, Any]) β
input_str (str) β
kwargs (Any) β
Return type
None
on_tool_end(output, **kwargs)[source]ο
Run when tool ends running.
Parameters
output (str) β
kwargs (Any) β
Return type
None
on_tool_error(error, **kwargs)[source]ο
Run when tool errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) β
kwargs (Any) β
Return type
None
on_text(text, **kwargs)[source]ο
Run when agent is ending.
Parameters
text (str) β
kwargs (Any) β
Return type
None
on_agent_finish(finish, **kwargs)[source]ο
Run when agent ends running.
Parameters
finish (langchain.schema.AgentFinish) β
kwargs (Any) β
Return type
None
on_agent_action(action, **kwargs)[source]ο | https://api.python.langchain.com/en/latest/modules/callbacks.html |
18d09815d48a-11 | Return type
None
on_agent_action(action, **kwargs)[source]ο
Run on agent action.
Parameters
action (langchain.schema.AgentAction) β
kwargs (Any) β
Return type
Any
analyze_text(text)[source]ο
Analyze text using textstat and spacy.
Parameters
text (str) β The text to analyze.
Returns
A dictionary containing the complexity metrics.
Return type
(dict)
flush_tracker(name=None, langchain_asset=None, finish=False)[source]ο
Flush the tracker and setup the session.
Everything after this will be a new table.
Parameters
name (Optional[str]) β Name of the preformed session so far so it is identifyable
langchain_asset (Any) β The langchain asset to save.
finish (bool) β Whether to finish the run.
Returns β None
Return type
None
class langchain.callbacks.CometCallbackHandler(task_type='inference', workspace=None, project_name=None, tags=None, name=None, visualizations=None, complexity_metrics=False, custom_metrics=None, stream_logs=True)[source]ο
Bases: langchain.callbacks.utils.BaseMetadataCallbackHandler, langchain.callbacks.base.BaseCallbackHandler
Callback Handler that logs to Comet.
Parameters
job_type (str) β The type of comet_ml task such as βinferenceβ,
βtestingβ or βqcβ
project_name (str) β The comet_ml project name
tags (list) β Tags to add to the task
task_name (str) β Name of the comet_ml task
visualize (bool) β Whether to visualize the run.
complexity_metrics (bool) β Whether to log complexity metrics
stream_logs (bool) β Whether to stream callback actions to Comet
task_type (Optional[str]) β
workspace (Optional[str]) β
name (Optional[str]) β | https://api.python.langchain.com/en/latest/modules/callbacks.html |
18d09815d48a-12 | workspace (Optional[str]) β
name (Optional[str]) β
visualizations (Optional[List[str]]) β
custom_metrics (Optional[Callable]) β
Return type
None
This handler will utilize the associated callback method and formats
the input of each callback function with metadata regarding the state of LLM run,
and adds the response to the list of records for both the {method}_records and
action. It then logs the response to Comet.
on_llm_start(serialized, prompts, **kwargs)[source]ο
Run when LLM starts.
Parameters
serialized (Dict[str, Any]) β
prompts (List[str]) β
kwargs (Any) β
Return type
None
on_llm_new_token(token, **kwargs)[source]ο
Run when LLM generates a new token.
Parameters
token (str) β
kwargs (Any) β
Return type
None
on_llm_end(response, **kwargs)[source]ο
Run when LLM ends running.
Parameters
response (langchain.schema.LLMResult) β
kwargs (Any) β
Return type
None
on_llm_error(error, **kwargs)[source]ο
Run when LLM errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) β
kwargs (Any) β
Return type
None
on_chain_start(serialized, inputs, **kwargs)[source]ο
Run when chain starts running.
Parameters
serialized (Dict[str, Any]) β
inputs (Dict[str, Any]) β
kwargs (Any) β
Return type
None
on_chain_end(outputs, **kwargs)[source]ο
Run when chain ends running.
Parameters
outputs (Dict[str, Any]) β
kwargs (Any) β
Return type
None | https://api.python.langchain.com/en/latest/modules/callbacks.html |
18d09815d48a-13 | kwargs (Any) β
Return type
None
on_chain_error(error, **kwargs)[source]ο
Run when chain errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) β
kwargs (Any) β
Return type
None
on_tool_start(serialized, input_str, **kwargs)[source]ο
Run when tool starts running.
Parameters
serialized (Dict[str, Any]) β
input_str (str) β
kwargs (Any) β
Return type
None
on_tool_end(output, **kwargs)[source]ο
Run when tool ends running.
Parameters
output (str) β
kwargs (Any) β
Return type
None
on_tool_error(error, **kwargs)[source]ο
Run when tool errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) β
kwargs (Any) β
Return type
None
on_text(text, **kwargs)[source]ο
Run when agent is ending.
Parameters
text (str) β
kwargs (Any) β
Return type
None
on_agent_finish(finish, **kwargs)[source]ο
Run when agent ends running.
Parameters
finish (langchain.schema.AgentFinish) β
kwargs (Any) β
Return type
None
on_agent_action(action, **kwargs)[source]ο
Run on agent action.
Parameters
action (langchain.schema.AgentAction) β
kwargs (Any) β
Return type
Any
flush_tracker(langchain_asset=None, task_type='inference', workspace=None, project_name='comet-langchain-demo', tags=None, name=None, visualizations=None, complexity_metrics=False, custom_metrics=None, finish=False, reset=False)[source]ο
Flush the tracker and setup the session.
Everything after this will be a new table. | https://api.python.langchain.com/en/latest/modules/callbacks.html |
18d09815d48a-14 | Flush the tracker and setup the session.
Everything after this will be a new table.
Parameters
name (Optional[str]) β Name of the preformed session so far so it is identifyable
langchain_asset (Any) β The langchain asset to save.
finish (bool) β Whether to finish the run.
Returns β None
task_type (Optional[str]) β
workspace (Optional[str]) β
project_name (Optional[str]) β
tags (Optional[Sequence]) β
visualizations (Optional[List[str]]) β
complexity_metrics (bool) β
custom_metrics (Optional[Callable]) β
reset (bool) β
Return type
None
class langchain.callbacks.FileCallbackHandler(filename, mode='a', color=None)[source]ο
Bases: langchain.callbacks.base.BaseCallbackHandler
Callback Handler that writes to a file.
Parameters
filename (str) β
mode (str) β
color (Optional[str]) β
Return type
None
on_chain_start(serialized, inputs, **kwargs)[source]ο
Print out that we are entering a chain.
Parameters
serialized (Dict[str, Any]) β
inputs (Dict[str, Any]) β
kwargs (Any) β
Return type
None
on_chain_end(outputs, **kwargs)[source]ο
Print out that we finished a chain.
Parameters
outputs (Dict[str, Any]) β
kwargs (Any) β
Return type
None
on_agent_action(action, color=None, **kwargs)[source]ο
Run on agent action.
Parameters
action (langchain.schema.AgentAction) β
color (Optional[str]) β
kwargs (Any) β
Return type
Any | https://api.python.langchain.com/en/latest/modules/callbacks.html |
18d09815d48a-15 | color (Optional[str]) β
kwargs (Any) β
Return type
Any
on_tool_end(output, color=None, observation_prefix=None, llm_prefix=None, **kwargs)[source]ο
If not the final action, print out observation.
Parameters
output (str) β
color (Optional[str]) β
observation_prefix (Optional[str]) β
llm_prefix (Optional[str]) β
kwargs (Any) β
Return type
None
on_text(text, color=None, end='', **kwargs)[source]ο
Run when agent ends.
Parameters
text (str) β
color (Optional[str]) β
end (str) β
kwargs (Any) β
Return type
None
on_agent_finish(finish, color=None, **kwargs)[source]ο
Run on agent end.
Parameters
finish (langchain.schema.AgentFinish) β
color (Optional[str]) β
kwargs (Any) β
Return type
None
class langchain.callbacks.FinalStreamingStdOutCallbackHandler(*, answer_prefix_tokens=None, strip_tokens=True, stream_prefix=False)[source]ο
Bases: langchain.callbacks.streaming_stdout.StreamingStdOutCallbackHandler
Callback handler for streaming in agents.
Only works with agents using LLMs that support streaming.
Only the final output of the agent will be streamed.
Parameters
answer_prefix_tokens (Optional[List[str]]) β
strip_tokens (bool) β
stream_prefix (bool) β
Return type
None
append_to_last_tokens(token)[source]ο
Parameters
token (str) β
Return type
None
check_if_answer_reached()[source]ο
Return type
bool
on_llm_start(serialized, prompts, **kwargs)[source]ο
Run when LLM starts running.
Parameters | https://api.python.langchain.com/en/latest/modules/callbacks.html |
18d09815d48a-16 | Run when LLM starts running.
Parameters
serialized (Dict[str, Any]) β
prompts (List[str]) β
kwargs (Any) β
Return type
None
on_llm_new_token(token, **kwargs)[source]ο
Run on new LLM token. Only available when streaming is enabled.
Parameters
token (str) β
kwargs (Any) β
Return type
None
class langchain.callbacks.HumanApprovalCallbackHandler(approve=<function _default_approve>, should_check=<function _default_true>)[source]ο
Bases: langchain.callbacks.base.BaseCallbackHandler
Callback for manually validating values.
Parameters
approve (Callable[[Any], bool]) β
should_check (Callable[[Dict[str, Any]], bool]) β
raise_error: bool = Trueο
on_tool_start(serialized, input_str, *, run_id, parent_run_id=None, **kwargs)[source]ο
Run when tool starts running.
Parameters
serialized (Dict[str, Any]) β
input_str (str) β
run_id (uuid.UUID) β
parent_run_id (Optional[uuid.UUID]) β
kwargs (Any) β
Return type
Any
class langchain.callbacks.InfinoCallbackHandler(model_id=None, model_version=None, verbose=False)[source]ο
Bases: langchain.callbacks.base.BaseCallbackHandler
Callback Handler that logs to Infino.
Parameters
model_id (Optional[str]) β
model_version (Optional[str]) β
verbose (bool) β
Return type
None
on_llm_start(serialized, prompts, **kwargs)[source]ο
Log the prompts to Infino, and set start time and error flag.
Parameters
serialized (Dict[str, Any]) β
prompts (List[str]) β | https://api.python.langchain.com/en/latest/modules/callbacks.html |
18d09815d48a-17 | serialized (Dict[str, Any]) β
prompts (List[str]) β
kwargs (Any) β
Return type
None
on_llm_new_token(token, **kwargs)[source]ο
Do nothing when a new token is generated.
Parameters
token (str) β
kwargs (Any) β
Return type
None
on_llm_end(response, **kwargs)[source]ο
Log the latency, error, token usage, and response to Infino.
Parameters
response (langchain.schema.LLMResult) β
kwargs (Any) β
Return type
None
on_llm_error(error, **kwargs)[source]ο
Set the error flag.
Parameters
error (Union[Exception, KeyboardInterrupt]) β
kwargs (Any) β
Return type
None
on_chain_start(serialized, inputs, **kwargs)[source]ο
Do nothing when LLM chain starts.
Parameters
serialized (Dict[str, Any]) β
inputs (Dict[str, Any]) β
kwargs (Any) β
Return type
None
on_chain_end(outputs, **kwargs)[source]ο
Do nothing when LLM chain ends.
Parameters
outputs (Dict[str, Any]) β
kwargs (Any) β
Return type
None
on_chain_error(error, **kwargs)[source]ο
Need to log the error.
Parameters
error (Union[Exception, KeyboardInterrupt]) β
kwargs (Any) β
Return type
None
on_tool_start(serialized, input_str, **kwargs)[source]ο
Do nothing when tool starts.
Parameters
serialized (Dict[str, Any]) β
input_str (str) β
kwargs (Any) β
Return type
None
on_agent_action(action, **kwargs)[source]ο | https://api.python.langchain.com/en/latest/modules/callbacks.html |
18d09815d48a-18 | Return type
None
on_agent_action(action, **kwargs)[source]ο
Do nothing when agent takes a specific action.
Parameters
action (langchain.schema.AgentAction) β
kwargs (Any) β
Return type
Any
on_tool_end(output, observation_prefix=None, llm_prefix=None, **kwargs)[source]ο
Do nothing when tool ends.
Parameters
output (str) β
observation_prefix (Optional[str]) β
llm_prefix (Optional[str]) β
kwargs (Any) β
Return type
None
on_tool_error(error, **kwargs)[source]ο
Do nothing when tool outputs an error.
Parameters
error (Union[Exception, KeyboardInterrupt]) β
kwargs (Any) β
Return type
None
on_text(text, **kwargs)[source]ο
Do nothing.
Parameters
text (str) β
kwargs (Any) β
Return type
None
on_agent_finish(finish, **kwargs)[source]ο
Do nothing.
Parameters
finish (langchain.schema.AgentFinish) β
kwargs (Any) β
Return type
None
class langchain.callbacks.MlflowCallbackHandler(name='langchainrun-%', experiment='langchain', tags={}, tracking_uri=None)[source]ο
Bases: langchain.callbacks.utils.BaseMetadataCallbackHandler, langchain.callbacks.base.BaseCallbackHandler
Callback Handler that logs metrics and artifacts to mlflow server.
Parameters
name (str) β Name of the run.
experiment (str) β Name of the experiment.
tags (dict) β Tags to be attached for the run.
tracking_uri (str) β MLflow tracking server uri.
Return type
None
This handler will utilize the associated callback method called and formats
the input of each callback function with metadata regarding the state of LLM run, | https://api.python.langchain.com/en/latest/modules/callbacks.html |
18d09815d48a-19 | the input of each callback function with metadata regarding the state of LLM run,
and adds the response to the list of records for both the {method}_records and
action. It then logs the response to mlflow server.
on_llm_start(serialized, prompts, **kwargs)[source]ο
Run when LLM starts.
Parameters
serialized (Dict[str, Any]) β
prompts (List[str]) β
kwargs (Any) β
Return type
None
on_llm_new_token(token, **kwargs)[source]ο
Run when LLM generates a new token.
Parameters
token (str) β
kwargs (Any) β
Return type
None
on_llm_end(response, **kwargs)[source]ο
Run when LLM ends running.
Parameters
response (langchain.schema.LLMResult) β
kwargs (Any) β
Return type
None
on_llm_error(error, **kwargs)[source]ο
Run when LLM errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) β
kwargs (Any) β
Return type
None
on_chain_start(serialized, inputs, **kwargs)[source]ο
Run when chain starts running.
Parameters
serialized (Dict[str, Any]) β
inputs (Dict[str, Any]) β
kwargs (Any) β
Return type
None
on_chain_end(outputs, **kwargs)[source]ο
Run when chain ends running.
Parameters
outputs (Dict[str, Any]) β
kwargs (Any) β
Return type
None
on_chain_error(error, **kwargs)[source]ο
Run when chain errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) β
kwargs (Any) β
Return type
None | https://api.python.langchain.com/en/latest/modules/callbacks.html |
18d09815d48a-20 | kwargs (Any) β
Return type
None
on_tool_start(serialized, input_str, **kwargs)[source]ο
Run when tool starts running.
Parameters
serialized (Dict[str, Any]) β
input_str (str) β
kwargs (Any) β
Return type
None
on_tool_end(output, **kwargs)[source]ο
Run when tool ends running.
Parameters
output (str) β
kwargs (Any) β
Return type
None
on_tool_error(error, **kwargs)[source]ο
Run when tool errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) β
kwargs (Any) β
Return type
None
on_text(text, **kwargs)[source]ο
Run when agent is ending.
Parameters
text (str) β
kwargs (Any) β
Return type
None
on_agent_finish(finish, **kwargs)[source]ο
Run when agent ends running.
Parameters
finish (langchain.schema.AgentFinish) β
kwargs (Any) β
Return type
None
on_agent_action(action, **kwargs)[source]ο
Run on agent action.
Parameters
action (langchain.schema.AgentAction) β
kwargs (Any) β
Return type
Any
flush_tracker(langchain_asset=None, finish=False)[source]ο
Parameters
langchain_asset (Any) β
finish (bool) β
Return type
None
class langchain.callbacks.OpenAICallbackHandler[source]ο
Bases: langchain.callbacks.base.BaseCallbackHandler
Callback Handler that tracks OpenAI info.
total_tokens: int = 0ο
prompt_tokens: int = 0ο
completion_tokens: int = 0ο
successful_requests: int = 0ο | https://api.python.langchain.com/en/latest/modules/callbacks.html |
18d09815d48a-21 | completion_tokens: int = 0ο
successful_requests: int = 0ο
total_cost: float = 0.0ο
property always_verbose: boolο
Whether to call verbose callbacks even if verbose is False.
on_llm_start(serialized, prompts, **kwargs)[source]ο
Print out the prompts.
Parameters
serialized (Dict[str, Any]) β
prompts (List[str]) β
kwargs (Any) β
Return type
None
on_llm_new_token(token, **kwargs)[source]ο
Print out the token.
Parameters
token (str) β
kwargs (Any) β
Return type
None
on_llm_end(response, **kwargs)[source]ο
Collect token usage.
Parameters
response (langchain.schema.LLMResult) β
kwargs (Any) β
Return type
None
class langchain.callbacks.StdOutCallbackHandler(color=None)[source]ο
Bases: langchain.callbacks.base.BaseCallbackHandler
Callback Handler that prints to std out.
Parameters
color (Optional[str]) β
Return type
None
on_llm_start(serialized, prompts, **kwargs)[source]ο
Print out the prompts.
Parameters
serialized (Dict[str, Any]) β
prompts (List[str]) β
kwargs (Any) β
Return type
None
on_llm_end(response, **kwargs)[source]ο
Do nothing.
Parameters
response (langchain.schema.LLMResult) β
kwargs (Any) β
Return type
None
on_llm_new_token(token, **kwargs)[source]ο
Do nothing.
Parameters
token (str) β
kwargs (Any) β
Return type
None
on_llm_error(error, **kwargs)[source]ο | https://api.python.langchain.com/en/latest/modules/callbacks.html |
18d09815d48a-22 | Return type
None
on_llm_error(error, **kwargs)[source]ο
Do nothing.
Parameters
error (Union[Exception, KeyboardInterrupt]) β
kwargs (Any) β
Return type
None
on_chain_start(serialized, inputs, **kwargs)[source]ο
Print out that we are entering a chain.
Parameters
serialized (Dict[str, Any]) β
inputs (Dict[str, Any]) β
kwargs (Any) β
Return type
None
on_chain_end(outputs, **kwargs)[source]ο
Print out that we finished a chain.
Parameters
outputs (Dict[str, Any]) β
kwargs (Any) β
Return type
None
on_chain_error(error, **kwargs)[source]ο
Do nothing.
Parameters
error (Union[Exception, KeyboardInterrupt]) β
kwargs (Any) β
Return type
None
on_tool_start(serialized, input_str, **kwargs)[source]ο
Do nothing.
Parameters
serialized (Dict[str, Any]) β
input_str (str) β
kwargs (Any) β
Return type
None
on_agent_action(action, color=None, **kwargs)[source]ο
Run on agent action.
Parameters
action (langchain.schema.AgentAction) β
color (Optional[str]) β
kwargs (Any) β
Return type
Any
on_tool_end(output, color=None, observation_prefix=None, llm_prefix=None, **kwargs)[source]ο
If not the final action, print out observation.
Parameters
output (str) β
color (Optional[str]) β
observation_prefix (Optional[str]) β
llm_prefix (Optional[str]) β
kwargs (Any) β
Return type
None | https://api.python.langchain.com/en/latest/modules/callbacks.html |
18d09815d48a-23 | kwargs (Any) β
Return type
None
on_tool_error(error, **kwargs)[source]ο
Do nothing.
Parameters
error (Union[Exception, KeyboardInterrupt]) β
kwargs (Any) β
Return type
None
on_text(text, color=None, end='', **kwargs)[source]ο
Run when agent ends.
Parameters
text (str) β
color (Optional[str]) β
end (str) β
kwargs (Any) β
Return type
None
on_agent_finish(finish, color=None, **kwargs)[source]ο
Run on agent end.
Parameters
finish (langchain.schema.AgentFinish) β
color (Optional[str]) β
kwargs (Any) β
Return type
None
class langchain.callbacks.StreamingStdOutCallbackHandler[source]ο
Bases: langchain.callbacks.base.BaseCallbackHandler
Callback handler for streaming. Only works with LLMs that support streaming.
on_llm_start(serialized, prompts, **kwargs)[source]ο
Run when LLM starts running.
Parameters
serialized (Dict[str, Any]) β
prompts (List[str]) β
kwargs (Any) β
Return type
None
on_llm_new_token(token, **kwargs)[source]ο
Run on new LLM token. Only available when streaming is enabled.
Parameters
token (str) β
kwargs (Any) β
Return type
None
on_llm_end(response, **kwargs)[source]ο
Run when LLM ends running.
Parameters
response (langchain.schema.LLMResult) β
kwargs (Any) β
Return type
None
on_llm_error(error, **kwargs)[source]ο
Run when LLM errors.
Parameters | https://api.python.langchain.com/en/latest/modules/callbacks.html |
18d09815d48a-24 | Run when LLM errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) β
kwargs (Any) β
Return type
None
on_chain_start(serialized, inputs, **kwargs)[source]ο
Run when chain starts running.
Parameters
serialized (Dict[str, Any]) β
inputs (Dict[str, Any]) β
kwargs (Any) β
Return type
None
on_chain_end(outputs, **kwargs)[source]ο
Run when chain ends running.
Parameters
outputs (Dict[str, Any]) β
kwargs (Any) β
Return type
None
on_chain_error(error, **kwargs)[source]ο
Run when chain errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) β
kwargs (Any) β
Return type
None
on_tool_start(serialized, input_str, **kwargs)[source]ο
Run when tool starts running.
Parameters
serialized (Dict[str, Any]) β
input_str (str) β
kwargs (Any) β
Return type
None
on_agent_action(action, **kwargs)[source]ο
Run on agent action.
Parameters
action (langchain.schema.AgentAction) β
kwargs (Any) β
Return type
Any
on_tool_end(output, **kwargs)[source]ο
Run when tool ends running.
Parameters
output (str) β
kwargs (Any) β
Return type
None
on_tool_error(error, **kwargs)[source]ο
Run when tool errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) β
kwargs (Any) β
Return type
None
on_text(text, **kwargs)[source]ο
Run on arbitrary text.
Parameters
text (str) β
kwargs (Any) β
Return type | https://api.python.langchain.com/en/latest/modules/callbacks.html |
18d09815d48a-25 | Parameters
text (str) β
kwargs (Any) β
Return type
None
on_agent_finish(finish, **kwargs)[source]ο
Run on agent end.
Parameters
finish (langchain.schema.AgentFinish) β
kwargs (Any) β
Return type
None
langchain.callbacks.StreamlitCallbackHandler(parent_container, *, max_thought_containers=4, expand_new_thoughts=True, collapse_completed_thoughts=True, thought_labeler=None)[source]ο
Construct a new StreamlitCallbackHandler. This CallbackHandler is geared towards
use with a LangChain Agent; it displays the Agentβs LLM and tool-usage βthoughtsβ
inside a series of Streamlit expanders.
Parameters
parent_container (DeltaGenerator) β The st.container that will contain all the Streamlit elements that the
Handler creates.
max_thought_containers (int) β The max number of completed LLM thought containers to show at once. When this
threshold is reached, a new thought will cause the oldest thoughts to be
collapsed into a βHistoryβ expander. Defaults to 4.
expand_new_thoughts (bool) β Each LLM βthoughtβ gets its own st.expander. This param controls whether that
expander is expanded by default. Defaults to True.
collapse_completed_thoughts (bool) β If True, LLM thought expanders will be collapsed when completed.
Defaults to True.
thought_labeler (Optional[LLMThoughtLabeler]) β An optional custom LLMThoughtLabeler instance. If unspecified, the handler
will use the default thought labeling logic. Defaults to None.
Returns
A new StreamlitCallbackHandler instance.
Note that this is an βauto-updatingβ API (if the installed version of Streamlit)
has a more recent StreamlitCallbackHandler implementation, an instance of that class | https://api.python.langchain.com/en/latest/modules/callbacks.html |
18d09815d48a-26 | has a more recent StreamlitCallbackHandler implementation, an instance of that class
will be used.
Return type
BaseCallbackHandler
class langchain.callbacks.LLMThoughtLabeler[source]ο
Bases: object
Generates markdown labels for LLMThought containers. Pass a custom
subclass of this to StreamlitCallbackHandler to override its default
labeling logic.
get_initial_label()[source]ο
Return the markdown label for a new LLMThought that doesnβt have
an associated tool yet.
Return type
str
get_tool_label(tool, is_complete)[source]ο
Return the label for an LLMThought that has an associated
tool.
Parameters
tool (langchain.callbacks.streamlit.streamlit_callback_handler.ToolRecord) β The toolβs ToolRecord
is_complete (bool) β True if the thought is complete; False if the thought
is still receiving input.
Return type
The markdown label for the thoughtβs container.
get_history_label()[source]ο
Return a markdown label for the special βhistoryβ container
that contains overflow thoughts.
Return type
str
get_final_agent_thought_label()[source]ο
Return the markdown label for the agentβs final thought -
the βNow I have the answerβ thought, that doesnβt involve
a tool.
Return type
str
class langchain.callbacks.WandbCallbackHandler(job_type=None, project='langchain_callback_demo', entity=None, tags=None, group=None, name=None, notes=None, visualize=False, complexity_metrics=False, stream_logs=False)[source]ο
Bases: langchain.callbacks.utils.BaseMetadataCallbackHandler, langchain.callbacks.base.BaseCallbackHandler
Callback Handler that logs to Weights and Biases.
Parameters
job_type (str) β The type of job.
project (str) β The project to log to. | https://api.python.langchain.com/en/latest/modules/callbacks.html |
18d09815d48a-27 | project (str) β The project to log to.
entity (str) β The entity to log to.
tags (list) β The tags to log.
group (str) β The group to log to.
name (str) β The name of the run.
notes (str) β The notes to log.
visualize (bool) β Whether to visualize the run.
complexity_metrics (bool) β Whether to log complexity metrics.
stream_logs (bool) β Whether to stream callback actions to W&B
Return type
None
This handler will utilize the associated callback method called and formats
the input of each callback function with metadata regarding the state of LLM run,
and adds the response to the list of records for both the {method}_records and
action. It then logs the response using the run.log() method to Weights and Biases.
on_llm_start(serialized, prompts, **kwargs)[source]ο
Run when LLM starts.
Parameters
serialized (Dict[str, Any]) β
prompts (List[str]) β
kwargs (Any) β
Return type
None
on_llm_new_token(token, **kwargs)[source]ο
Run when LLM generates a new token.
Parameters
token (str) β
kwargs (Any) β
Return type
None
on_llm_end(response, **kwargs)[source]ο
Run when LLM ends running.
Parameters
response (langchain.schema.LLMResult) β
kwargs (Any) β
Return type
None
on_llm_error(error, **kwargs)[source]ο
Run when LLM errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) β
kwargs (Any) β
Return type
None
on_chain_start(serialized, inputs, **kwargs)[source]ο | https://api.python.langchain.com/en/latest/modules/callbacks.html |
18d09815d48a-28 | None
on_chain_start(serialized, inputs, **kwargs)[source]ο
Run when chain starts running.
Parameters
serialized (Dict[str, Any]) β
inputs (Dict[str, Any]) β
kwargs (Any) β
Return type
None
on_chain_end(outputs, **kwargs)[source]ο
Run when chain ends running.
Parameters
outputs (Dict[str, Any]) β
kwargs (Any) β
Return type
None
on_chain_error(error, **kwargs)[source]ο
Run when chain errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) β
kwargs (Any) β
Return type
None
on_tool_start(serialized, input_str, **kwargs)[source]ο
Run when tool starts running.
Parameters
serialized (Dict[str, Any]) β
input_str (str) β
kwargs (Any) β
Return type
None
on_tool_end(output, **kwargs)[source]ο
Run when tool ends running.
Parameters
output (str) β
kwargs (Any) β
Return type
None
on_tool_error(error, **kwargs)[source]ο
Run when tool errors.
Parameters
error (Union[Exception, KeyboardInterrupt]) β
kwargs (Any) β
Return type
None
on_text(text, **kwargs)[source]ο
Run when agent is ending.
Parameters
text (str) β
kwargs (Any) β
Return type
None
on_agent_finish(finish, **kwargs)[source]ο
Run when agent ends running.
Parameters
finish (langchain.schema.AgentFinish) β
kwargs (Any) β
Return type
None
on_agent_action(action, **kwargs)[source]ο
Run on agent action.
Parameters | https://api.python.langchain.com/en/latest/modules/callbacks.html |
18d09815d48a-29 | Run on agent action.
Parameters
action (langchain.schema.AgentAction) β
kwargs (Any) β
Return type
Any
flush_tracker(langchain_asset=None, reset=True, finish=False, job_type=None, project=None, entity=None, tags=None, group=None, name=None, notes=None, visualize=None, complexity_metrics=None)[source]ο
Flush the tracker and reset the session.
Parameters
langchain_asset (Any) β The langchain asset to save.
reset (bool) β Whether to reset the session.
finish (bool) β Whether to finish the run.
job_type (Optional[str]) β The job type.
project (Optional[str]) β The project.
entity (Optional[str]) β The entity.
tags (Optional[Sequence]) β The tags.
group (Optional[str]) β The group.
name (Optional[str]) β The name.
notes (Optional[str]) β The notes.
visualize (Optional[bool]) β Whether to visualize.
complexity_metrics (Optional[bool]) β Whether to compute complexity metrics.
Returns β None
Return type
None
class langchain.callbacks.WhyLabsCallbackHandler(logger)[source]ο
Bases: langchain.callbacks.base.BaseCallbackHandler
WhyLabs CallbackHandler.
Parameters
logger (Logger) β
on_llm_start(serialized, prompts, **kwargs)[source]ο
Pass the input prompts to the logger
Parameters
serialized (Dict[str, Any]) β
prompts (List[str]) β
kwargs (Any) β
Return type
None
on_llm_end(response, **kwargs)[source]ο
Pass the generated response to the logger.
Parameters
response (langchain.schema.LLMResult) β
kwargs (Any) β
Return type
None | https://api.python.langchain.com/en/latest/modules/callbacks.html |
18d09815d48a-30 | kwargs (Any) β
Return type
None
on_llm_new_token(token, **kwargs)[source]ο
Do nothing.
Parameters
token (str) β
kwargs (Any) β
Return type
None
on_llm_error(error, **kwargs)[source]ο
Do nothing.
Parameters
error (Union[Exception, KeyboardInterrupt]) β
kwargs (Any) β
Return type
None
on_chain_start(serialized, inputs, **kwargs)[source]ο
Do nothing.
Parameters
serialized (Dict[str, Any]) β
inputs (Dict[str, Any]) β
kwargs (Any) β
Return type
None
on_chain_end(outputs, **kwargs)[source]ο
Do nothing.
Parameters
outputs (Dict[str, Any]) β
kwargs (Any) β
Return type
None
on_chain_error(error, **kwargs)[source]ο
Do nothing.
Parameters
error (Union[Exception, KeyboardInterrupt]) β
kwargs (Any) β
Return type
None
on_tool_start(serialized, input_str, **kwargs)[source]ο
Do nothing.
Parameters
serialized (Dict[str, Any]) β
input_str (str) β
kwargs (Any) β
Return type
None
on_agent_action(action, color=None, **kwargs)[source]ο
Do nothing.
Parameters
action (langchain.schema.AgentAction) β
color (Optional[str]) β
kwargs (Any) β
Return type
Any
on_tool_end(output, color=None, observation_prefix=None, llm_prefix=None, **kwargs)[source]ο
Do nothing.
Parameters
output (str) β
color (Optional[str]) β
observation_prefix (Optional[str]) β | https://api.python.langchain.com/en/latest/modules/callbacks.html |
18d09815d48a-31 | color (Optional[str]) β
observation_prefix (Optional[str]) β
llm_prefix (Optional[str]) β
kwargs (Any) β
Return type
None
on_tool_error(error, **kwargs)[source]ο
Do nothing.
Parameters
error (Union[Exception, KeyboardInterrupt]) β
kwargs (Any) β
Return type
None
on_text(text, **kwargs)[source]ο
Do nothing.
Parameters
text (str) β
kwargs (Any) β
Return type
None
on_agent_finish(finish, color=None, **kwargs)[source]ο
Run on agent end.
Parameters
finish (langchain.schema.AgentFinish) β
color (Optional[str]) β
kwargs (Any) β
Return type
None
flush()[source]ο
Return type
None
close()[source]ο
Return type
None
classmethod from_params(*, api_key=None, org_id=None, dataset_id=None, sentiment=False, toxicity=False, themes=False)[source]ο
Instantiate whylogs Logger from params.
Parameters
api_key (Optional[str]) β WhyLabs API key. Optional because the preferred
way to specify the API key is with environment variable
WHYLABS_API_KEY.
org_id (Optional[str]) β WhyLabs organization id to write profiles to.
If not set must be specified in environment variable
WHYLABS_DEFAULT_ORG_ID.
dataset_id (Optional[str]) β The model or dataset this callback is gathering
telemetry for. If not set must be specified in environment variable
WHYLABS_DEFAULT_DATASET_ID.
sentiment (bool) β If True will initialize a model to perform
sentiment analysis compound score. Defaults to False and will not gather
this metric. | https://api.python.langchain.com/en/latest/modules/callbacks.html |
18d09815d48a-32 | sentiment analysis compound score. Defaults to False and will not gather
this metric.
toxicity (bool) β If True will initialize a model to score
toxicity. Defaults to False and will not gather this metric.
themes (bool) β If True will initialize a model to calculate
distance to configured themes. Defaults to None and will not gather this
metric.
Return type
Logger
langchain.callbacks.get_openai_callback()[source]ο
Get the OpenAI callback handler in a context manager.
which conveniently exposes token and cost information.
Returns
The OpenAI callback handler.
Return type
OpenAICallbackHandler
Example
>>> with get_openai_callback() as cb:
... # Use the OpenAI callback handler
langchain.callbacks.tracing_enabled(session_name='default')[source]ο
Get the Deprecated LangChainTracer in a context manager.
Parameters
session_name (str, optional) β The name of the session.
Defaults to βdefaultβ.
Returns
The LangChainTracer session.
Return type
TracerSessionV1
Example
>>> with tracing_enabled() as session:
... # Use the LangChainTracer session
langchain.callbacks.wandb_tracing_enabled(session_name='default')[source]ο
Get the WandbTracer in a context manager.
Parameters
session_name (str, optional) β The name of the session.
Defaults to βdefaultβ.
Returns
None
Return type
Generator[None, None, None]
Example
>>> with wandb_tracing_enabled() as session:
... # Use the WandbTracer session | https://api.python.langchain.com/en/latest/modules/callbacks.html |
f5ed643c3227-0 | Agentsο
Interface for agents.
class langchain.agents.Agent(*, llm_chain, output_parser, allowed_tools=None)[source]ο
Bases: langchain.agents.agent.BaseSingleActionAgent
Class responsible for calling the language model and deciding the action.
This is driven by an LLMChain. The prompt in the LLMChain MUST include
a variable called βagent_scratchpadβ where the agent can put its
intermediary work.
Parameters
llm_chain (langchain.chains.llm.LLMChain) β
output_parser (langchain.agents.agent.AgentOutputParser) β
allowed_tools (Optional[List[str]]) β
Return type
None
attribute allowed_tools: Optional[List[str]] = Noneο
attribute llm_chain: langchain.chains.llm.LLMChain [Required]ο
attribute output_parser: langchain.agents.agent.AgentOutputParser [Required]ο
async aplan(intermediate_steps, callbacks=None, **kwargs)[source]ο
Given input, decided what to do.
Parameters
intermediate_steps (List[Tuple[langchain.schema.AgentAction, str]]) β Steps the LLM has taken to date,
along with observations
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β Callbacks to run.
**kwargs β User inputs.
kwargs (Any) β
Returns
Action specifying what tool to use.
Return type
Union[langchain.schema.AgentAction, langchain.schema.AgentFinish]
abstract classmethod create_prompt(tools)[source]ο
Create a prompt for this class.
Parameters
tools (Sequence[langchain.tools.base.BaseTool]) β
Return type
langchain.prompts.base.BasePromptTemplate
dict(**kwargs)[source]ο
Return dictionary representation of agent.
Parameters | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-1 | dict(**kwargs)[source]ο
Return dictionary representation of agent.
Parameters
kwargs (Any) β
Return type
Dict
classmethod from_llm_and_tools(llm, tools, callback_manager=None, output_parser=None, **kwargs)[source]ο
Construct an agent from an LLM and tools.
Parameters
llm (langchain.base_language.BaseLanguageModel) β
tools (Sequence[langchain.tools.base.BaseTool]) β
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) β
output_parser (Optional[langchain.agents.agent.AgentOutputParser]) β
kwargs (Any) β
Return type
langchain.agents.agent.Agent
get_allowed_tools()[source]ο
Return type
Optional[List[str]]
get_full_inputs(intermediate_steps, **kwargs)[source]ο
Create the full inputs for the LLMChain from intermediate steps.
Parameters
intermediate_steps (List[Tuple[langchain.schema.AgentAction, str]]) β
kwargs (Any) β
Return type
Dict[str, Any]
plan(intermediate_steps, callbacks=None, **kwargs)[source]ο
Given input, decided what to do.
Parameters
intermediate_steps (List[Tuple[langchain.schema.AgentAction, str]]) β Steps the LLM has taken to date,
along with observations
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β Callbacks to run.
**kwargs β User inputs.
kwargs (Any) β
Returns
Action specifying what tool to use.
Return type
Union[langchain.schema.AgentAction, langchain.schema.AgentFinish]
return_stopped_response(early_stopping_method, intermediate_steps, **kwargs)[source]ο
Return response when agent has been stopped due to max iterations.
Parameters | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-2 | Return response when agent has been stopped due to max iterations.
Parameters
early_stopping_method (str) β
intermediate_steps (List[Tuple[langchain.schema.AgentAction, str]]) β
kwargs (Any) β
Return type
langchain.schema.AgentFinish
tool_run_logging_kwargs()[source]ο
Return type
Dict
abstract property llm_prefix: strο
Prefix to append the LLM call with.
abstract property observation_prefix: strο
Prefix to append the observation with.
property return_values: List[str]ο
Return values of the agent.
class langchain.agents.AgentExecutor(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, agent, tools, return_intermediate_steps=False, max_iterations=15, max_execution_time=None, early_stopping_method='force', handle_parsing_errors=False)[source]ο
Bases: langchain.chains.base.Chain
Consists of an agent using tools.
Parameters
memory (Optional[langchain.schema.BaseMemory]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) β
verbose (bool) β
tags (Optional[List[str]]) β
agent (Union[langchain.agents.agent.BaseSingleActionAgent, langchain.agents.agent.BaseMultiActionAgent]) β
tools (Sequence[langchain.tools.base.BaseTool]) β
return_intermediate_steps (bool) β
max_iterations (Optional[int]) β
max_execution_time (Optional[float]) β
early_stopping_method (str) β
handle_parsing_errors (Union[bool, str, Callable[[langchain.schema.OutputParserException], str]]) β
Return type
None | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-3 | Return type
None
attribute agent: Union[BaseSingleActionAgent, BaseMultiActionAgent] [Required]ο
The agent to run for creating a plan and determining actions
to take at each step of the execution loop.
attribute early_stopping_method: str = 'force'ο
The method to use for early stopping if the agent never
returns AgentFinish. Either βforceβ or βgenerateβ.
βforceβ returns a string saying that it stopped because it met atime or iteration limit.
βgenerateβ calls the agentβs LLM Chain one final time to generatea final answer based on the previous steps.
attribute handle_parsing_errors: Union[bool, str, Callable[[OutputParserException], str]] = Falseο
How to handle errors raised by the agentβs output parser.Defaults to False, which raises the error.
sIf true, the error will be sent back to the LLM as an observation.
If a string, the string itself will be sent to the LLM as an observation.
If a callable function, the function will be called with the exception
as an argument, and the result of that function will be passed to the agentas an observation.
attribute max_execution_time: Optional[float] = Noneο
The maximum amount of wall clock time to spend in the execution
loop.
attribute max_iterations: Optional[int] = 15ο
The maximum number of steps to take before ending the execution
loop.
Setting to βNoneβ could lead to an infinite loop.
attribute return_intermediate_steps: bool = Falseο
Whether to return the agentβs trajectory of intermediate steps
at the end in addition to the final output.
attribute tools: Sequence[BaseTool] [Required]ο
The valid tools the agent can call. | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-4 | The valid tools the agent can call.
classmethod from_agent_and_tools(agent, tools, callback_manager=None, **kwargs)[source]ο
Create from agent and tools.
Parameters
agent (Union[langchain.agents.agent.BaseSingleActionAgent, langchain.agents.agent.BaseMultiActionAgent]) β
tools (Sequence[langchain.tools.base.BaseTool]) β
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) β
kwargs (Any) β
Return type
langchain.agents.agent.AgentExecutor
lookup_tool(name)[source]ο
Lookup tool by name.
Parameters
name (str) β
Return type
langchain.tools.base.BaseTool
save(file_path)[source]ο
Raise error - saving not supported for Agent Executors.
Parameters
file_path (Union[pathlib.Path, str]) β
Return type
None
save_agent(file_path)[source]ο
Save the underlying agent.
Parameters
file_path (Union[pathlib.Path, str]) β
Return type
None
class langchain.agents.AgentOutputParser[source]ο
Bases: langchain.schema.BaseOutputParser
Return type
None
abstract parse(text)[source]ο
Parse text into agent action/finish.
Parameters
text (str) β
Return type
Union[langchain.schema.AgentAction, langchain.schema.AgentFinish]
class langchain.agents.AgentType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]ο
Bases: str, enum.Enum
Enumerator with the Agent types.
ZERO_SHOT_REACT_DESCRIPTION = 'zero-shot-react-description'ο
REACT_DOCSTORE = 'react-docstore'ο
SELF_ASK_WITH_SEARCH = 'self-ask-with-search'ο | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-5 | SELF_ASK_WITH_SEARCH = 'self-ask-with-search'ο
CONVERSATIONAL_REACT_DESCRIPTION = 'conversational-react-description'ο
CHAT_ZERO_SHOT_REACT_DESCRIPTION = 'chat-zero-shot-react-description'ο
CHAT_CONVERSATIONAL_REACT_DESCRIPTION = 'chat-conversational-react-description'ο
STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION = 'structured-chat-zero-shot-react-description'ο
OPENAI_FUNCTIONS = 'openai-functions'ο
OPENAI_MULTI_FUNCTIONS = 'openai-multi-functions'ο
class langchain.agents.BaseMultiActionAgent[source]ο
Bases: pydantic.main.BaseModel
Base Agent class.
Return type
None
abstract async aplan(intermediate_steps, callbacks=None, **kwargs)[source]ο
Given input, decided what to do.
Parameters
intermediate_steps (List[Tuple[langchain.schema.AgentAction, str]]) β Steps the LLM has taken to date,
along with observations
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β Callbacks to run.
**kwargs β User inputs.
kwargs (Any) β
Returns
Actions specifying what tool to use.
Return type
Union[List[langchain.schema.AgentAction], langchain.schema.AgentFinish]
dict(**kwargs)[source]ο
Return dictionary representation of agent.
Parameters
kwargs (Any) β
Return type
Dict
get_allowed_tools()[source]ο
Return type
Optional[List[str]]
abstract plan(intermediate_steps, callbacks=None, **kwargs)[source]ο
Given input, decided what to do.
Parameters
intermediate_steps (List[Tuple[langchain.schema.AgentAction, str]]) β Steps the LLM has taken to date,
along with observations | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-6 | along with observations
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β Callbacks to run.
**kwargs β User inputs.
kwargs (Any) β
Returns
Actions specifying what tool to use.
Return type
Union[List[langchain.schema.AgentAction], langchain.schema.AgentFinish]
return_stopped_response(early_stopping_method, intermediate_steps, **kwargs)[source]ο
Return response when agent has been stopped due to max iterations.
Parameters
early_stopping_method (str) β
intermediate_steps (List[Tuple[langchain.schema.AgentAction, str]]) β
kwargs (Any) β
Return type
langchain.schema.AgentFinish
save(file_path)[source]ο
Save the agent.
Parameters
file_path (Union[pathlib.Path, str]) β Path to file to save the agent to.
Return type
None
Example:
.. code-block:: python
# If working with agent executor
agent.agent.save(file_path=βpath/agent.yamlβ)
tool_run_logging_kwargs()[source]ο
Return type
Dict
property return_values: List[str]ο
Return values of the agent.
class langchain.agents.BaseSingleActionAgent[source]ο
Bases: pydantic.main.BaseModel
Base Agent class.
Return type
None
abstract async aplan(intermediate_steps, callbacks=None, **kwargs)[source]ο
Given input, decided what to do.
Parameters
intermediate_steps (List[Tuple[langchain.schema.AgentAction, str]]) β Steps the LLM has taken to date,
along with observations
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β Callbacks to run.
**kwargs β User inputs.
kwargs (Any) β | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-7 | **kwargs β User inputs.
kwargs (Any) β
Returns
Action specifying what tool to use.
Return type
Union[langchain.schema.AgentAction, langchain.schema.AgentFinish]
dict(**kwargs)[source]ο
Return dictionary representation of agent.
Parameters
kwargs (Any) β
Return type
Dict
classmethod from_llm_and_tools(llm, tools, callback_manager=None, **kwargs)[source]ο
Parameters
llm (langchain.base_language.BaseLanguageModel) β
tools (Sequence[langchain.tools.base.BaseTool]) β
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) β
kwargs (Any) β
Return type
langchain.agents.agent.BaseSingleActionAgent
get_allowed_tools()[source]ο
Return type
Optional[List[str]]
abstract plan(intermediate_steps, callbacks=None, **kwargs)[source]ο
Given input, decided what to do.
Parameters
intermediate_steps (List[Tuple[langchain.schema.AgentAction, str]]) β Steps the LLM has taken to date,
along with observations
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β Callbacks to run.
**kwargs β User inputs.
kwargs (Any) β
Returns
Action specifying what tool to use.
Return type
Union[langchain.schema.AgentAction, langchain.schema.AgentFinish]
return_stopped_response(early_stopping_method, intermediate_steps, **kwargs)[source]ο
Return response when agent has been stopped due to max iterations.
Parameters
early_stopping_method (str) β
intermediate_steps (List[Tuple[langchain.schema.AgentAction, str]]) β
kwargs (Any) β
Return type
langchain.schema.AgentFinish
save(file_path)[source]ο | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-8 | Return type
langchain.schema.AgentFinish
save(file_path)[source]ο
Save the agent.
Parameters
file_path (Union[pathlib.Path, str]) β Path to file to save the agent to.
Return type
None
Example:
.. code-block:: python
# If working with agent executor
agent.agent.save(file_path=βpath/agent.yamlβ)
tool_run_logging_kwargs()[source]ο
Return type
Dict
property return_values: List[str]ο
Return values of the agent.
class langchain.agents.ConversationalAgent(*, llm_chain, output_parser=None, allowed_tools=None, ai_prefix='AI')[source]ο
Bases: langchain.agents.agent.Agent
An agent designed to hold a conversation in addition to using tools.
Parameters
llm_chain (langchain.chains.llm.LLMChain) β
output_parser (langchain.agents.agent.AgentOutputParser) β
allowed_tools (Optional[List[str]]) β
ai_prefix (str) β
Return type
None
attribute ai_prefix: str = 'AI'ο
attribute output_parser: langchain.agents.agent.AgentOutputParser [Optional]ο | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-9 | classmethod create_prompt(tools, prefix='Assistant is a large language model trained by OpenAI.\n\nAssistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.\n\nAssistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.\n\nOverall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.\n\nTOOLS:\n------\n\nAssistant has access to the following tools:', suffix='Begin!\n\nPrevious conversation history:\n{chat_history}\n\nNew input: {input}\n{agent_scratchpad}', format_instructions='To use a tool, please use the following format:\n\n```\nThought: Do I need to use a tool? Yes\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n```\n\nWhen you have a response to say to the Human, or if you do not need to use a tool, you MUST use the format:\n\n```\nThought: Do I need to use a tool? | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-10 | MUST use the format:\n\n```\nThought: Do I need to use a tool? No\n{ai_prefix}: [your response here]\n```', ai_prefix='AI', human_prefix='Human', input_variables=None)[source]ο | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-11 | Create prompt in the style of the zero shot agent.
Parameters
tools (Sequence[langchain.tools.base.BaseTool]) β List of tools the agent will have access to, used to format the
prompt.
prefix (str) β String to put before the list of tools.
suffix (str) β String to put after the list of tools.
ai_prefix (str) β String to use before AI output.
human_prefix (str) β String to use before human output.
input_variables (Optional[List[str]]) β List of input variables the final prompt will expect.
format_instructions (str) β
Returns
A PromptTemplate with the template assembled from the pieces here.
Return type
langchain.prompts.prompt.PromptTemplate | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-12 | classmethod from_llm_and_tools(llm, tools, callback_manager=None, output_parser=None, prefix='Assistant is a large language model trained by OpenAI.\n\nAssistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.\n\nAssistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.\n\nOverall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.\n\nTOOLS:\n------\n\nAssistant has access to the following tools:', suffix='Begin!\n\nPrevious conversation history:\n{chat_history}\n\nNew input: {input}\n{agent_scratchpad}', format_instructions='To use a tool, please use the following format:\n\n```\nThought: Do I need to use a tool? Yes\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n```\n\nWhen you have a response to say to the Human, or if you do not need to use a tool, you MUST use the | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-13 | say to the Human, or if you do not need to use a tool, you MUST use the format:\n\n```\nThought: Do I need to use a tool? No\n{ai_prefix}: [your response here]\n```', ai_prefix='AI', human_prefix='Human', input_variables=None, **kwargs)[source]ο | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-14 | Construct an agent from an LLM and tools.
Parameters
llm (langchain.base_language.BaseLanguageModel) β
tools (Sequence[langchain.tools.base.BaseTool]) β
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) β
output_parser (Optional[langchain.agents.agent.AgentOutputParser]) β
prefix (str) β
suffix (str) β
format_instructions (str) β
ai_prefix (str) β
human_prefix (str) β
input_variables (Optional[List[str]]) β
kwargs (Any) β
Return type
langchain.agents.agent.Agent
property llm_prefix: strο
Prefix to append the llm call with.
property observation_prefix: strο
Prefix to append the observation with.
class langchain.agents.ConversationalChatAgent(*, llm_chain, output_parser=None, allowed_tools=None, template_tool_response="TOOL RESPONSE: \n---------------------\n{observation}\n\nUSER'S INPUT\n--------------------\n\nOkay, so what is the response to my last comment? If using information obtained from the tools you must mention it explicitly without mentioning the tool names - I have forgotten all TOOL RESPONSES! Remember to respond with a markdown code snippet of a json blob with a single action, and NOTHING else.")[source]ο
Bases: langchain.agents.agent.Agent
An agent designed to hold a conversation in addition to using tools.
Parameters
llm_chain (langchain.chains.llm.LLMChain) β
output_parser (langchain.agents.agent.AgentOutputParser) β
allowed_tools (Optional[List[str]]) β
template_tool_response (str) β
Return type
None
attribute output_parser: langchain.agents.agent.AgentOutputParser [Optional]ο | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-15 | None
attribute output_parser: langchain.agents.agent.AgentOutputParser [Optional]ο
attribute template_tool_response: str = "TOOL RESPONSE: \n---------------------\n{observation}\n\nUSER'S INPUT\n--------------------\n\nOkay, so what is the response to my last comment? If using information obtained from the tools you must mention it explicitly without mentioning the tool names - I have forgotten all TOOL RESPONSES! Remember to respond with a markdown code snippet of a json blob with a single action, and NOTHING else."ο | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-16 | classmethod create_prompt(tools, system_message='Assistant is a large language model trained by OpenAI.\n\nAssistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.\n\nAssistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.\n\nOverall, Assistant is a powerful system that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.', human_message="TOOLS\n------\nAssistant can ask the user to use tools to look up information that may be helpful in answering the users original question. The tools the human can use are:\n\n{{tools}}\n\n{format_instructions}\n\nUSER'S INPUT\n--------------------\nHere is the user's input (remember to respond with a markdown code snippet of a json blob with a single action, and NOTHING else):\n\n{{{{input}}}}", input_variables=None, output_parser=None)[source]ο
Create a prompt for this class.
Parameters
tools (Sequence[langchain.tools.base.BaseTool]) β
system_message (str) β
human_message (str) β
input_variables (Optional[List[str]]) β | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-17 | human_message (str) β
input_variables (Optional[List[str]]) β
output_parser (Optional[langchain.schema.BaseOutputParser]) β
Return type
langchain.prompts.base.BasePromptTemplate | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-18 | Return type
langchain.prompts.base.BasePromptTemplate
classmethod from_llm_and_tools(llm, tools, callback_manager=None, output_parser=None, system_message='Assistant is a large language model trained by OpenAI.\n\nAssistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.\n\nAssistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.\n\nOverall, Assistant is a powerful system that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.', human_message="TOOLS\n------\nAssistant can ask the user to use tools to look up information that may be helpful in answering the users original question. The tools the human can use are:\n\n{{tools}}\n\n{format_instructions}\n\nUSER'S INPUT\n--------------------\nHere is the user's input (remember to respond with a markdown code snippet of a json blob with a single action, and NOTHING else):\n\n{{{{input}}}}", input_variables=None, **kwargs)[source]ο
Construct an agent from an LLM and tools.
Parameters
llm (langchain.base_language.BaseLanguageModel) β | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-19 | Parameters
llm (langchain.base_language.BaseLanguageModel) β
tools (Sequence[langchain.tools.base.BaseTool]) β
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) β
output_parser (Optional[langchain.agents.agent.AgentOutputParser]) β
system_message (str) β
human_message (str) β
input_variables (Optional[List[str]]) β
kwargs (Any) β
Return type
langchain.agents.agent.Agent
property llm_prefix: strο
Prefix to append the llm call with.
property observation_prefix: strο
Prefix to append the observation with.
class langchain.agents.LLMSingleActionAgent(*, llm_chain, output_parser, stop)[source]ο
Bases: langchain.agents.agent.BaseSingleActionAgent
Parameters
llm_chain (langchain.chains.llm.LLMChain) β
output_parser (langchain.agents.agent.AgentOutputParser) β
stop (List[str]) β
Return type
None
attribute llm_chain: langchain.chains.llm.LLMChain [Required]ο
attribute output_parser: langchain.agents.agent.AgentOutputParser [Required]ο
attribute stop: List[str] [Required]ο
async aplan(intermediate_steps, callbacks=None, **kwargs)[source]ο
Given input, decided what to do.
Parameters
intermediate_steps (List[Tuple[langchain.schema.AgentAction, str]]) β Steps the LLM has taken to date,
along with observations
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β Callbacks to run.
**kwargs β User inputs.
kwargs (Any) β
Returns
Action specifying what tool to use.
Return type | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-20 | kwargs (Any) β
Returns
Action specifying what tool to use.
Return type
Union[langchain.schema.AgentAction, langchain.schema.AgentFinish]
dict(**kwargs)[source]ο
Return dictionary representation of agent.
Parameters
kwargs (Any) β
Return type
Dict
plan(intermediate_steps, callbacks=None, **kwargs)[source]ο
Given input, decided what to do.
Parameters
intermediate_steps (List[Tuple[langchain.schema.AgentAction, str]]) β Steps the LLM has taken to date,
along with observations
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β Callbacks to run.
**kwargs β User inputs.
kwargs (Any) β
Returns
Action specifying what tool to use.
Return type
Union[langchain.schema.AgentAction, langchain.schema.AgentFinish]
tool_run_logging_kwargs()[source]ο
Return type
Dict
class langchain.agents.MRKLChain(*, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, agent, tools, return_intermediate_steps=False, max_iterations=15, max_execution_time=None, early_stopping_method='force', handle_parsing_errors=False)[source]ο
Bases: langchain.agents.agent.AgentExecutor
Chain that implements the MRKL system.
Example
from langchain import OpenAI, MRKLChain
from langchain.chains.mrkl.base import ChainConfig
llm = OpenAI(temperature=0)
prompt = PromptTemplate(...)
chains = [...]
mrkl = MRKLChain.from_chains(llm=llm, prompt=prompt)
Parameters
memory (Optional[langchain.schema.BaseMemory]) β | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-21 | Parameters
memory (Optional[langchain.schema.BaseMemory]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) β
verbose (bool) β
tags (Optional[List[str]]) β
agent (Union[langchain.agents.agent.BaseSingleActionAgent, langchain.agents.agent.BaseMultiActionAgent]) β
tools (Sequence[langchain.tools.base.BaseTool]) β
return_intermediate_steps (bool) β
max_iterations (Optional[int]) β
max_execution_time (Optional[float]) β
early_stopping_method (str) β
handle_parsing_errors (Union[bool, str, Callable[[langchain.schema.OutputParserException], str]]) β
Return type
None
classmethod from_chains(llm, chains, **kwargs)[source]ο
User friendly way to initialize the MRKL chain.
This is intended to be an easy way to get up and running with the
MRKL chain.
Parameters
llm (langchain.base_language.BaseLanguageModel) β The LLM to use as the agent LLM.
chains (List[langchain.agents.mrkl.base.ChainConfig]) β The chains the MRKL system has access to.
**kwargs β parameters to be passed to initialization.
kwargs (Any) β
Returns
An initialized MRKL chain.
Return type
langchain.agents.agent.AgentExecutor
Example
from langchain import LLMMathChain, OpenAI, SerpAPIWrapper, MRKLChain
from langchain.chains.mrkl.base import ChainConfig
llm = OpenAI(temperature=0)
search = SerpAPIWrapper()
llm_math_chain = LLMMathChain(llm=llm)
chains = [ | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-22 | llm_math_chain = LLMMathChain(llm=llm)
chains = [
ChainConfig(
action_name = "Search",
action=search.search,
action_description="useful for searching"
),
ChainConfig(
action_name="Calculator",
action=llm_math_chain.run,
action_description="useful for doing math"
)
]
mrkl = MRKLChain.from_chains(llm, chains)
class langchain.agents.OpenAIFunctionsAgent(*, llm, tools, prompt)[source]ο
Bases: langchain.agents.agent.BaseSingleActionAgent
An Agent driven by OpenAIs function powered API.
Parameters
llm (langchain.base_language.BaseLanguageModel) β This should be an instance of ChatOpenAI, specifically a model
that supports using functions.
tools (Sequence[langchain.tools.base.BaseTool]) β The tools this agent has access to.
prompt (langchain.prompts.base.BasePromptTemplate) β The prompt for this agent, should support agent_scratchpad as one
of the variables. For an easy way to construct this prompt, use
OpenAIFunctionsAgent.create_prompt(β¦)
Return type
None
attribute llm: langchain.base_language.BaseLanguageModel [Required]ο
attribute prompt: langchain.prompts.base.BasePromptTemplate [Required]ο
attribute tools: Sequence[langchain.tools.base.BaseTool] [Required]ο
async aplan(intermediate_steps, callbacks=None, **kwargs)[source]ο
Given input, decided what to do.
Parameters
intermediate_steps (List[Tuple[langchain.schema.AgentAction, str]]) β Steps the LLM has taken to date,
along with observations
**kwargs β User inputs. | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-23 | along with observations
**kwargs β User inputs.
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
kwargs (Any) β
Returns
Action specifying what tool to use.
Return type
Union[langchain.schema.AgentAction, langchain.schema.AgentFinish]
classmethod create_prompt(system_message=SystemMessage(content='You are a helpful AI assistant.', additional_kwargs={}), extra_prompt_messages=None)[source]ο
Create prompt for this agent.
Parameters
system_message (Optional[langchain.schema.SystemMessage]) β Message to use as the system message that will be the
first in the prompt.
extra_prompt_messages (Optional[List[langchain.prompts.chat.BaseMessagePromptTemplate]]) β Prompt messages that will be placed between the
system message and the new human input.
Returns
A prompt template to pass into this agent.
Return type
langchain.prompts.base.BasePromptTemplate
classmethod from_llm_and_tools(llm, tools, callback_manager=None, extra_prompt_messages=None, system_message=SystemMessage(content='You are a helpful AI assistant.', additional_kwargs={}), **kwargs)[source]ο
Construct an agent from an LLM and tools.
Parameters
llm (langchain.base_language.BaseLanguageModel) β
tools (Sequence[langchain.tools.base.BaseTool]) β
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) β
extra_prompt_messages (Optional[List[langchain.prompts.chat.BaseMessagePromptTemplate]]) β
system_message (Optional[langchain.schema.SystemMessage]) β
kwargs (Any) β
Return type
langchain.agents.agent.BaseSingleActionAgent
get_allowed_tools()[source]ο
Get allowed tools.
Return type
List[str]
plan(intermediate_steps, callbacks=None, **kwargs)[source]ο | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-24 | List[str]
plan(intermediate_steps, callbacks=None, **kwargs)[source]ο
Given input, decided what to do.
Parameters
intermediate_steps (List[Tuple[langchain.schema.AgentAction, str]]) β Steps the LLM has taken to date, along with observations
**kwargs β User inputs.
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
kwargs (Any) β
Returns
Action specifying what tool to use.
Return type
Union[langchain.schema.AgentAction, langchain.schema.AgentFinish]
property functions: List[dict]ο
property input_keys: List[str]ο
Get input keys. Input refers to user input here.
class langchain.agents.ReActChain(llm, docstore, *, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, agent, tools, return_intermediate_steps=False, max_iterations=15, max_execution_time=None, early_stopping_method='force', handle_parsing_errors=False)[source]ο
Bases: langchain.agents.agent.AgentExecutor
Chain that implements the ReAct paper.
Example
from langchain import ReActChain, OpenAI
react = ReAct(llm=OpenAI())
Parameters
llm (langchain.base_language.BaseLanguageModel) β
docstore (langchain.docstore.base.Docstore) β
memory (Optional[langchain.schema.BaseMemory]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) β
verbose (bool) β
tags (Optional[List[str]]) β | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-25 | verbose (bool) β
tags (Optional[List[str]]) β
agent (Union[langchain.agents.agent.BaseSingleActionAgent, langchain.agents.agent.BaseMultiActionAgent]) β
tools (Sequence[langchain.tools.base.BaseTool]) β
return_intermediate_steps (bool) β
max_iterations (Optional[int]) β
max_execution_time (Optional[float]) β
early_stopping_method (str) β
handle_parsing_errors (Union[bool, str, Callable[[langchain.schema.OutputParserException], str]]) β
Return type
None
class langchain.agents.ReActTextWorldAgent(*, llm_chain, output_parser=None, allowed_tools=None)[source]ο
Bases: langchain.agents.react.base.ReActDocstoreAgent
Agent for the ReAct TextWorld chain.
Parameters
llm_chain (langchain.chains.llm.LLMChain) β
output_parser (langchain.agents.agent.AgentOutputParser) β
allowed_tools (Optional[List[str]]) β
Return type
None
classmethod create_prompt(tools)[source]ο
Return default prompt.
Parameters
tools (Sequence[langchain.tools.base.BaseTool]) β
Return type
langchain.prompts.base.BasePromptTemplate
class langchain.agents.SelfAskWithSearchChain(llm, search_chain, *, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, agent, tools, return_intermediate_steps=False, max_iterations=15, max_execution_time=None, early_stopping_method='force', handle_parsing_errors=False)[source]ο
Bases: langchain.agents.agent.AgentExecutor
Chain that does self ask with search.
Example
from langchain import SelfAskWithSearchChain, OpenAI, GoogleSerperAPIWrapper
search_chain = GoogleSerperAPIWrapper() | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-26 | search_chain = GoogleSerperAPIWrapper()
self_ask = SelfAskWithSearchChain(llm=OpenAI(), search_chain=search_chain)
Parameters
llm (langchain.base_language.BaseLanguageModel) β
search_chain (Union[langchain.utilities.google_serper.GoogleSerperAPIWrapper, langchain.utilities.serpapi.SerpAPIWrapper]) β
memory (Optional[langchain.schema.BaseMemory]) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) β
verbose (bool) β
tags (Optional[List[str]]) β
agent (Union[langchain.agents.agent.BaseSingleActionAgent, langchain.agents.agent.BaseMultiActionAgent]) β
tools (Sequence[langchain.tools.base.BaseTool]) β
return_intermediate_steps (bool) β
max_iterations (Optional[int]) β
max_execution_time (Optional[float]) β
early_stopping_method (str) β
handle_parsing_errors (Union[bool, str, Callable[[langchain.schema.OutputParserException], str]]) β
Return type
None
class langchain.agents.StructuredChatAgent(*, llm_chain, output_parser=None, allowed_tools=None)[source]ο
Bases: langchain.agents.agent.Agent
Parameters
llm_chain (langchain.chains.llm.LLMChain) β
output_parser (langchain.agents.agent.AgentOutputParser) β
allowed_tools (Optional[List[str]]) β
Return type
None
attribute output_parser: langchain.agents.agent.AgentOutputParser [Optional]ο | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-27 | None
attribute output_parser: langchain.agents.agent.AgentOutputParser [Optional]ο
classmethod create_prompt(tools, prefix='Respond to the human as helpfully and accurately as possible. You have access to the following tools:', suffix='Begin! Reminder to ALWAYS respond with a valid json blob of a single action. Use tools if necessary. Respond directly if appropriate. Format is Action:```$JSON_BLOB```then Observation:.\nThought:', human_message_template='{input}\n\n{agent_scratchpad}', format_instructions='Use a json blob to specify a tool by providing an action key (tool name) and an action_input key (tool input).\n\nValid "action" values: "Final Answer" or {tool_names}\n\nProvide only ONE action per $JSON_BLOB, as shown:\n\n```\n{{{{\nΒ "action": $TOOL_NAME,\nΒ "action_input": $INPUT\n}}}}\n```\n\nFollow this format:\n\nQuestion: input question to answer\nThought: consider previous and subsequent steps\nAction:\n```\n$JSON_BLOB\n```\nObservation: action result\n... (repeat Thought/Action/Observation N times)\nThought: I know what to respond\nAction:\n```\n{{{{\nΒ "action": "Final Answer",\nΒ "action_input": "Final response to human"\n}}}}\n```', input_variables=None, memory_prompts=None)[source]ο
Create a prompt for this class.
Parameters
tools (Sequence[langchain.tools.base.BaseTool]) β
prefix (str) β
suffix (str) β
human_message_template (str) β
format_instructions (str) β
input_variables (Optional[List[str]]) β | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-28 | format_instructions (str) β
input_variables (Optional[List[str]]) β
memory_prompts (Optional[List[langchain.prompts.base.BasePromptTemplate]]) β
Return type
langchain.prompts.base.BasePromptTemplate
classmethod from_llm_and_tools(llm, tools, callback_manager=None, output_parser=None, prefix='Respond to the human as helpfully and accurately as possible. You have access to the following tools:', suffix='Begin! Reminder to ALWAYS respond with a valid json blob of a single action. Use tools if necessary. Respond directly if appropriate. Format is Action:```$JSON_BLOB```then Observation:.\nThought:', human_message_template='{input}\n\n{agent_scratchpad}', format_instructions='Use a json blob to specify a tool by providing an action key (tool name) and an action_input key (tool input).\n\nValid "action" values: "Final Answer" or {tool_names}\n\nProvide only ONE action per $JSON_BLOB, as shown:\n\n```\n{{{{\nΒ "action": $TOOL_NAME,\nΒ "action_input": $INPUT\n}}}}\n```\n\nFollow this format:\n\nQuestion: input question to answer\nThought: consider previous and subsequent steps\nAction:\n```\n$JSON_BLOB\n```\nObservation: action result\n... (repeat Thought/Action/Observation N times)\nThought: I know what to respond\nAction:\n```\n{{{{\nΒ "action": "Final Answer",\nΒ "action_input": "Final response to human"\n}}}}\n```', input_variables=None, memory_prompts=None, **kwargs)[source]ο
Construct an agent from an LLM and tools.
Parameters
llm (langchain.base_language.BaseLanguageModel) β | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-29 | Parameters
llm (langchain.base_language.BaseLanguageModel) β
tools (Sequence[langchain.tools.base.BaseTool]) β
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) β
output_parser (Optional[langchain.agents.agent.AgentOutputParser]) β
prefix (str) β
suffix (str) β
human_message_template (str) β
format_instructions (str) β
input_variables (Optional[List[str]]) β
memory_prompts (Optional[List[langchain.prompts.base.BasePromptTemplate]]) β
kwargs (Any) β
Return type
langchain.agents.agent.Agent
property llm_prefix: strο
Prefix to append the llm call with.
property observation_prefix: strο
Prefix to append the observation with.
class langchain.agents.Tool(name, func, description, *, args_schema=None, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False, coroutine=None)[source]ο
Bases: langchain.tools.base.BaseTool
Tool that takes in function or coroutine directly.
Parameters
name (str) β
func (Callable[[...], str]) β
description (str) β
args_schema (Optional[Type[pydantic.main.BaseModel]]) β
return_direct (bool) β
verbose (bool) β
callbacks (Optional[Union[List[langchain.callbacks.base.BaseCallbackHandler], langchain.callbacks.base.BaseCallbackManager]]) β
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) β
handle_tool_error (Optional[Union[bool, str, Callable[[langchain.tools.base.ToolException], str]]]) β
coroutine (Optional[Callable[[...], Awaitable[str]]]) β
Return type
None | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-30 | Return type
None
attribute coroutine: Optional[Callable[[...], Awaitable[str]]] = Noneο
The asynchronous version of the function.
attribute description: str = ''ο
Used to tell the model how/when/why to use the tool.
You can provide few-shot examples as a part of the description.
attribute func: Callable[[...], str] [Required]ο
The function to run when the tool is called.
classmethod from_function(func, name, description, return_direct=False, args_schema=None, **kwargs)[source]ο
Initialize tool from a function.
Parameters
func (Callable) β
name (str) β
description (str) β
return_direct (bool) β
args_schema (Optional[Type[pydantic.main.BaseModel]]) β
kwargs (Any) β
Return type
langchain.tools.base.Tool
property args: dictο
The toolβs input arguments.
class langchain.agents.ZeroShotAgent(*, llm_chain, output_parser=None, allowed_tools=None)[source]ο
Bases: langchain.agents.agent.Agent
Agent for the MRKL chain.
Parameters
llm_chain (langchain.chains.llm.LLMChain) β
output_parser (langchain.agents.agent.AgentOutputParser) β
allowed_tools (Optional[List[str]]) β
Return type
None
attribute output_parser: langchain.agents.agent.AgentOutputParser [Optional]ο | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-31 | None
attribute output_parser: langchain.agents.agent.AgentOutputParser [Optional]ο
classmethod create_prompt(tools, prefix='Answer the following questions as best you can. You have access to the following tools:', suffix='Begin!\n\nQuestion: {input}\nThought:{agent_scratchpad}', format_instructions='Use the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question', input_variables=None)[source]ο
Create prompt in the style of the zero shot agent.
Parameters
tools (Sequence[langchain.tools.base.BaseTool]) β List of tools the agent will have access to, used to format the
prompt.
prefix (str) β String to put before the list of tools.
suffix (str) β String to put after the list of tools.
input_variables (Optional[List[str]]) β List of input variables the final prompt will expect.
format_instructions (str) β
Returns
A PromptTemplate with the template assembled from the pieces here.
Return type
langchain.prompts.prompt.PromptTemplate | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-32 | Return type
langchain.prompts.prompt.PromptTemplate
classmethod from_llm_and_tools(llm, tools, callback_manager=None, output_parser=None, prefix='Answer the following questions as best you can. You have access to the following tools:', suffix='Begin!\n\nQuestion: {input}\nThought:{agent_scratchpad}', format_instructions='Use the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question', input_variables=None, **kwargs)[source]ο
Construct an agent from an LLM and tools.
Parameters
llm (langchain.base_language.BaseLanguageModel) β
tools (Sequence[langchain.tools.base.BaseTool]) β
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) β
output_parser (Optional[langchain.agents.agent.AgentOutputParser]) β
prefix (str) β
suffix (str) β
format_instructions (str) β
input_variables (Optional[List[str]]) β
kwargs (Any) β
Return type
langchain.agents.agent.Agent
property llm_prefix: strο
Prefix to append the llm call with.
property observation_prefix: strο
Prefix to append the observation with.
langchain.agents.create_csv_agent(llm, path, pandas_kwargs=None, **kwargs)[source]ο
Create csv agent by loading to a dataframe and using pandas agent.
Parameters
llm (langchain.base_language.BaseLanguageModel) β | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-33 | Parameters
llm (langchain.base_language.BaseLanguageModel) β
path (Union[str, List[str]]) β
pandas_kwargs (Optional[dict]) β
kwargs (Any) β
Return type
langchain.agents.agent.AgentExecutor | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-34 | langchain.agents.create_json_agent(llm, toolkit, callback_manager=None, prefix='You are an agent designed to interact with JSON.\nYour goal is to return a final answer by interacting with the JSON.\nYou have access to the following tools which help you learn more about the JSON you are interacting with.\nOnly use the below tools. Only use the information returned by the below tools to construct your final answer.\nDo not make up any information that is not contained in the JSON.\nYour input to the tools should be in the form of `data["key"][0]` where `data` is the JSON blob you are interacting with, and the syntax used is Python. \nYou should only use keys that you know for a fact exist. You must validate that a key exists by seeing it previously when calling `json_spec_list_keys`. \nIf you have not seen a key in one of those responses, you cannot use it.\nYou should only add one key at a time to the path. You cannot add multiple keys at once.\nIf you encounter a "KeyError", go back to the previous key, look at the available keys, and try again.\n\nIf the question does not seem to be related to the JSON, just return "I don\'t know" as the answer.\nAlways begin your interaction with the `json_spec_list_keys` tool with input "data" to see what keys exist in the JSON.\n\nNote that sometimes the value at a given path is large. In this case, you will get an error "Value is a large dictionary, should explore its keys directly".\nIn this case, you should ALWAYS follow up by using the `json_spec_list_keys` tool to see what keys exist at that path.\nDo not simply refer the user to the JSON or a section of the JSON, as this is not a valid answer. Keep digging until you find the answer and explicitly | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-35 | the JSON, as this is not a valid answer. Keep digging until you find the answer and explicitly return it.\n', suffix='Begin!"\n\nQuestion: {input}\nThought: I should look at the keys that exist in data to see what I have access to\n{agent_scratchpad}', format_instructions='Use the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question', input_variables=None, verbose=False, agent_executor_kwargs=None, **kwargs)[source]ο | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-36 | Construct a json agent from an LLM and tools.
Parameters
llm (langchain.base_language.BaseLanguageModel) β
toolkit (langchain.agents.agent_toolkits.json.toolkit.JsonToolkit) β
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) β
prefix (str) β
suffix (str) β
format_instructions (str) β
input_variables (Optional[List[str]]) β
verbose (bool) β
agent_executor_kwargs (Optional[Dict[str, Any]]) β
kwargs (Dict[str, Any]) β
Return type
langchain.agents.agent.AgentExecutor | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-37 | langchain.agents.create_openapi_agent(llm, toolkit, callback_manager=None, prefix="You are an agent designed to answer questions by making web requests to an API given the openapi spec.\n\nIf the question does not seem related to the API, return I don't know. Do not make up an answer.\nOnly use information provided by the tools to construct your response.\n\nFirst, find the base URL needed to make the request.\n\nSecond, find the relevant paths needed to answer the question. Take note that, sometimes, you might need to make more than one request to more than one path to answer the question.\n\nThird, find the required parameters needed to make the request. For GET requests, these are usually URL parameters and for POST requests, these are request body parameters.\n\nFourth, make the requests needed to answer the question. Ensure that you are sending the correct parameters to the request by checking which parameters are required. For parameters with a fixed set of values, please use the spec to look at which values are allowed.\n\nUse the exact parameter names as listed in the spec, do not make up any names or abbreviate the names of parameters.\nIf you get a not found error, ensure that you are using a path that actually exists in the spec.\n", suffix='Begin!\n\nQuestion: {input}\nThought: I should explore the spec to find the base url for the API.\n{agent_scratchpad}', format_instructions='Use the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-38 | Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question', input_variables=None, max_iterations=15, max_execution_time=None, early_stopping_method='force', verbose=False, return_intermediate_steps=False, agent_executor_kwargs=None, **kwargs)[source]ο | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-39 | Construct a json agent from an LLM and tools.
Parameters
llm (langchain.base_language.BaseLanguageModel) β
toolkit (langchain.agents.agent_toolkits.openapi.toolkit.OpenAPIToolkit) β
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) β
prefix (str) β
suffix (str) β
format_instructions (str) β
input_variables (Optional[List[str]]) β
max_iterations (Optional[int]) β
max_execution_time (Optional[float]) β
early_stopping_method (str) β
verbose (bool) β
return_intermediate_steps (bool) β
agent_executor_kwargs (Optional[Dict[str, Any]]) β
kwargs (Dict[str, Any]) β
Return type
langchain.agents.agent.AgentExecutor
langchain.agents.create_pandas_dataframe_agent(llm, df, agent_type=AgentType.ZERO_SHOT_REACT_DESCRIPTION, callback_manager=None, prefix=None, suffix=None, input_variables=None, verbose=False, return_intermediate_steps=False, max_iterations=15, max_execution_time=None, early_stopping_method='force', agent_executor_kwargs=None, include_df_in_prompt=True, **kwargs)[source]ο
Construct a pandas agent from an LLM and dataframe.
Parameters
llm (langchain.base_language.BaseLanguageModel) β
df (Any) β
agent_type (langchain.agents.agent_types.AgentType) β
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) β
prefix (Optional[str]) β
suffix (Optional[str]) β
input_variables (Optional[List[str]]) β
verbose (bool) β
return_intermediate_steps (bool) β
max_iterations (Optional[int]) β
max_execution_time (Optional[float]) β | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-40 | max_iterations (Optional[int]) β
max_execution_time (Optional[float]) β
early_stopping_method (str) β
agent_executor_kwargs (Optional[Dict[str, Any]]) β
include_df_in_prompt (Optional[bool]) β
kwargs (Dict[str, Any]) β
Return type
langchain.agents.agent.AgentExecutor | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-41 | langchain.agents.create_pbi_agent(llm, toolkit, powerbi=None, callback_manager=None, prefix='You are an agent designed to help users interact with a PowerBI Dataset.\n\nAgent has access to a tool that can write a query based on the question and then run those against PowerBI, Microsofts business intelligence tool. The questions from the users should be interpreted as related to the dataset that is available and not general questions about the world. If the question does not seem related to the dataset, just return "This does not appear to be part of this dataset." as the answer.\n\nGiven an input question, ask to run the questions against the dataset, then look at the results and return the answer, the answer should be a complete sentence that answers the question, if multiple rows are asked find a way to write that in a easily readable format for a human, also make sure to represent numbers in readable ways, like 1M instead of 1000000. Unless the user specifies a specific number of examples they wish to obtain, always limit your query to at most {top_k} results.\n', suffix='Begin!\n\nQuestion: {input}\nThought: I can first ask which tables I have, then how each table is defined and then ask the query tool the question I need, and finally create a nice sentence that answers the question.\n{agent_scratchpad}', format_instructions='Use the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question', examples=None, input_variables=None, | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-42 | Answer: the final answer to the original input question', examples=None, input_variables=None, top_k=10, verbose=False, agent_executor_kwargs=None, **kwargs)[source]ο | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-43 | Construct a pbi agent from an LLM and tools.
Parameters
llm (langchain.base_language.BaseLanguageModel) β
toolkit (Optional[langchain.agents.agent_toolkits.powerbi.toolkit.PowerBIToolkit]) β
powerbi (Optional[langchain.utilities.powerbi.PowerBIDataset]) β
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) β
prefix (str) β
suffix (str) β
format_instructions (str) β
examples (Optional[str]) β
input_variables (Optional[List[str]]) β
top_k (int) β
verbose (bool) β
agent_executor_kwargs (Optional[Dict[str, Any]]) β
kwargs (Dict[str, Any]) β
Return type
langchain.agents.agent.AgentExecutor | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-44 | Return type
langchain.agents.agent.AgentExecutor
langchain.agents.create_pbi_chat_agent(llm, toolkit, powerbi=None, callback_manager=None, output_parser=None, prefix='Assistant is a large language model built to help users interact with a PowerBI Dataset.\n\nAssistant has access to a tool that can write a query based on the question and then run those against PowerBI, Microsofts business intelligence tool. The questions from the users should be interpreted as related to the dataset that is available and not general questions about the world. If the question does not seem related to the dataset, just return "This does not appear to be part of this dataset." as the answer.\n\nGiven an input question, ask to run the questions against the dataset, then look at the results and return the answer, the answer should be a complete sentence that answers the question, if multiple rows are asked find a way to write that in a easily readable format for a human, also make sure to represent numbers in readable ways, like 1M instead of 1000000. Unless the user specifies a specific number of examples they wish to obtain, always limit your query to at most {top_k} results.\n', suffix="TOOLS\n------\nAssistant can ask the user to use tools to look up information that may be helpful in answering the users original question. The tools the human can use are:\n\n{{tools}}\n\n{format_instructions}\n\nUSER'S INPUT\n--------------------\nHere is the user's input (remember to respond with a markdown code snippet of a json blob with a single action, and NOTHING else):\n\n{{{{input}}}}\n", examples=None, input_variables=None, memory=None, top_k=10, verbose=False, agent_executor_kwargs=None, **kwargs)[source]ο
Construct a pbi agent from an Chat LLM and tools. | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-45 | Construct a pbi agent from an Chat LLM and tools.
If you supply only a toolkit and no powerbi dataset, the same LLM is used for both.
Parameters
llm (langchain.chat_models.base.BaseChatModel) β
toolkit (Optional[langchain.agents.agent_toolkits.powerbi.toolkit.PowerBIToolkit]) β
powerbi (Optional[langchain.utilities.powerbi.PowerBIDataset]) β
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) β
output_parser (Optional[langchain.agents.agent.AgentOutputParser]) β
prefix (str) β
suffix (str) β
examples (Optional[str]) β
input_variables (Optional[List[str]]) β
memory (Optional[langchain.memory.chat_memory.BaseChatMemory]) β
top_k (int) β
verbose (bool) β
agent_executor_kwargs (Optional[Dict[str, Any]]) β
kwargs (Dict[str, Any]) β
Return type
langchain.agents.agent.AgentExecutor
langchain.agents.create_spark_dataframe_agent(llm, df, callback_manager=None, prefix='\nYou are working with a spark dataframe in Python. The name of the dataframe is `df`.\nYou should use the tools below to answer the question posed of you:', suffix='\nThis is the result of `print(df.first())`:\n{df}\n\nBegin!\nQuestion: {input}\n{agent_scratchpad}', input_variables=None, verbose=False, return_intermediate_steps=False, max_iterations=15, max_execution_time=None, early_stopping_method='force', agent_executor_kwargs=None, **kwargs)[source]ο
Construct a spark agent from an LLM and dataframe.
Parameters
llm (langchain.llms.base.BaseLLM) β
df (Any) β | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-46 | df (Any) β
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) β
prefix (str) β
suffix (str) β
input_variables (Optional[List[str]]) β
verbose (bool) β
return_intermediate_steps (bool) β
max_iterations (Optional[int]) β
max_execution_time (Optional[float]) β
early_stopping_method (str) β
agent_executor_kwargs (Optional[Dict[str, Any]]) β
kwargs (Dict[str, Any]) β
Return type
langchain.agents.agent.AgentExecutor | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-47 | langchain.agents.create_spark_sql_agent(llm, toolkit, callback_manager=None, prefix='You are an agent designed to interact with Spark SQL.\nGiven an input question, create a syntactically correct Spark SQL query to run, then look at the results of the query and return the answer.\nUnless the user specifies a specific number of examples they wish to obtain, always limit your query to at most {top_k} results.\nYou can order the results by a relevant column to return the most interesting examples in the database.\nNever query for all the columns from a specific table, only ask for the relevant columns given the question.\nYou have access to tools for interacting with the database.\nOnly use the below tools. Only use the information returned by the below tools to construct your final answer.\nYou MUST double check your query before executing it. If you get an error while executing a query, rewrite the query and try again.\n\nDO NOT make any DML statements (INSERT, UPDATE, DELETE, DROP etc.) to the database.\n\nIf the question does not seem related to the database, just return "I don\'t know" as the answer.\n', suffix='Begin!\n\nQuestion: {input}\nThought: I should look at the tables in the database to see what I can query.\n{agent_scratchpad}', format_instructions='Use the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question', input_variables=None, top_k=10, | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-48 | Answer: the final answer to the original input question', input_variables=None, top_k=10, max_iterations=15, max_execution_time=None, early_stopping_method='force', verbose=False, agent_executor_kwargs=None, **kwargs)[source]ο | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-49 | Construct a sql agent from an LLM and tools.
Parameters
llm (langchain.base_language.BaseLanguageModel) β
toolkit (langchain.agents.agent_toolkits.spark_sql.toolkit.SparkSQLToolkit) β
callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) β
prefix (str) β
suffix (str) β
format_instructions (str) β
input_variables (Optional[List[str]]) β
top_k (int) β
max_iterations (Optional[int]) β
max_execution_time (Optional[float]) β
early_stopping_method (str) β
verbose (bool) β
agent_executor_kwargs (Optional[Dict[str, Any]]) β
kwargs (Dict[str, Any]) β
Return type
langchain.agents.agent.AgentExecutor | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-50 | langchain.agents.create_sql_agent(llm, toolkit, agent_type=AgentType.ZERO_SHOT_REACT_DESCRIPTION, callback_manager=None, prefix='You are an agent designed to interact with a SQL database.\nGiven an input question, create a syntactically correct {dialect} query to run, then look at the results of the query and return the answer.\nUnless the user specifies a specific number of examples they wish to obtain, always limit your query to at most {top_k} results.\nYou can order the results by a relevant column to return the most interesting examples in the database.\nNever query for all the columns from a specific table, only ask for the relevant columns given the question.\nYou have access to tools for interacting with the database.\nOnly use the below tools. Only use the information returned by the below tools to construct your final answer.\nYou MUST double check your query before executing it. If you get an error while executing a query, rewrite the query and try again.\n\nDO NOT make any DML statements (INSERT, UPDATE, DELETE, DROP etc.) to the database.\n\nIf the question does not seem related to the database, just return "I don\'t know" as the answer.\n', suffix=None, format_instructions='Use the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question', input_variables=None, top_k=10, max_iterations=15, max_execution_time=None, early_stopping_method='force', verbose=False, agent_executor_kwargs=None, | https://api.python.langchain.com/en/latest/modules/agents.html |
f5ed643c3227-51 | max_execution_time=None, early_stopping_method='force', verbose=False, agent_executor_kwargs=None, **kwargs)[source]ο | https://api.python.langchain.com/en/latest/modules/agents.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.