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